Merge branch 'search'
[org-mode.git] / org.el
blob8b57f7beb558e79b728b60fabfbe2192295e7f1a
1 ;;; org.el --- Outline-based notes management and organizer
2 ;; Carstens outline-mode for keeping track of everything.
3 ;; Copyright (C) 2004, 2005, 2006, 2007, 2008 Free Software Foundation, Inc.
4 ;;
5 ;; Author: Carsten Dominik <carsten at orgmode dot org>
6 ;; Keywords: outlines, hypermedia, calendar, wp
7 ;; Homepage: http://orgmode.org
8 ;; Version: 5.22a+
9 ;;
10 ;; This file is part of GNU Emacs.
12 ;; GNU Emacs is free software; you can redistribute it and/or modify
13 ;; it under the terms of the GNU General Public License as published by
14 ;; the Free Software Foundation; either version 3, or (at your option)
15 ;; any later version.
17 ;; GNU Emacs is distributed in the hope that it will be useful,
18 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
19 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 ;; GNU General Public License for more details.
22 ;; You should have received a copy of the GNU General Public License
23 ;; along with GNU Emacs; see the file COPYING. If not, write to the
24 ;; Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
25 ;; Boston, MA 02110-1301, USA.
26 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
28 ;;; Commentary:
30 ;; Org-mode is a mode for keeping notes, maintaining ToDo lists, and doing
31 ;; project planning with a fast and effective plain-text system.
33 ;; Org-mode develops organizational tasks around NOTES files that contain
34 ;; information about projects as plain text. Org-mode is implemented on
35 ;; top of outline-mode, which makes it possible to keep the content of
36 ;; large files well structured. Visibility cycling and structure editing
37 ;; help to work with the tree. Tables are easily created with a built-in
38 ;; table editor. Org-mode supports ToDo items, deadlines, time stamps,
39 ;; and scheduling. It dynamically compiles entries into an agenda that
40 ;; utilizes and smoothly integrates much of the Emacs calendar and diary.
41 ;; Plain text URL-like links connect to websites, emails, Usenet
42 ;; messages, BBDB entries, and any files related to the projects. For
43 ;; printing and sharing of notes, an Org-mode file can be exported as a
44 ;; structured ASCII file, as HTML, or (todo and agenda items only) as an
45 ;; iCalendar file. It can also serve as a publishing tool for a set of
46 ;; linked webpages.
48 ;; Installation and Activation
49 ;; ---------------------------
50 ;; See the corresponding sections in the manual at
52 ;; http://orgmode.org/org.html#Installation
54 ;; Documentation
55 ;; -------------
56 ;; The documentation of Org-mode can be found in the TeXInfo file. The
57 ;; distribution also contains a PDF version of it. At the homepage of
58 ;; Org-mode, you can read the same text online as HTML. There is also an
59 ;; excellent reference card made by Philip Rooke. This card can be found
60 ;; in the etc/ directory of Emacs 22.
62 ;; A list of recent changes can be found at
63 ;; http://orgmode.org/Changes.html
65 ;;; Code:
67 ;;;; Require other packages
69 (eval-when-compile
70 (require 'cl)
71 (require 'gnus-sum)
72 (require 'calendar))
73 ;; For XEmacs, noutline is not yet provided by outline.el, so arrange for
74 ;; the file noutline.el being loaded.
75 (if (featurep 'xemacs) (condition-case nil (require 'noutline)))
76 ;; We require noutline, which might be provided in outline.el
77 (require 'outline) (require 'noutline)
78 ;; Other stuff we need.
79 (require 'time-date)
80 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
81 (require 'easymenu)
83 ;;;; Customization variables
85 ;;; Version
87 (defconst org-version "5.22a+"
88 "The version number of the file org.el.")
90 (defun org-version (&optional here)
91 "Show the org-mode version in the echo area.
92 With prefix arg HERE, insert it at point."
93 (interactive "P")
94 (let ((version (format "Org-mode version %s" org-version)))
95 (message version)
96 (if here
97 (insert version))))
99 ;;; Compatibility constants
100 (defconst org-xemacs-p (featurep 'xemacs)) ; not used by org.el itself
101 (defconst org-format-transports-properties-p
102 (let ((x "a"))
103 (add-text-properties 0 1 '(test t) x)
104 (get-text-property 0 'test (format "%s" x)))
105 "Does format transport text properties?")
107 (defmacro org-bound-and-true-p (var)
108 "Return the value of symbol VAR if it is bound, else nil."
109 `(and (boundp (quote ,var)) ,var))
111 (defmacro org-unmodified (&rest body)
112 "Execute body without changing `buffer-modified-p'."
113 `(set-buffer-modified-p
114 (prog1 (buffer-modified-p) ,@body)))
116 (defmacro org-re (s)
117 "Replace posix classes in regular expression."
118 (if (featurep 'xemacs)
119 (let ((ss s))
120 (save-match-data
121 (while (string-match "\\[:alnum:\\]" ss)
122 (setq ss (replace-match "a-zA-Z0-9" t t ss)))
123 (while (string-match "\\[:alpha:\\]" ss)
124 (setq ss (replace-match "a-zA-Z" t t ss)))
125 ss))
128 (defmacro org-preserve-lc (&rest body)
129 `(let ((_line (org-current-line))
130 (_col (current-column)))
131 (unwind-protect
132 (progn ,@body)
133 (goto-line _line)
134 (move-to-column _col))))
136 (defmacro org-without-partial-completion (&rest body)
137 `(let ((pc-mode (and (boundp 'partial-completion-mode)
138 partial-completion-mode)))
139 (unwind-protect
140 (progn
141 (if pc-mode (partial-completion-mode -1))
142 ,@body)
143 (if pc-mode (partial-completion-mode 1)))))
145 ;;; The custom variables
147 (defgroup org nil
148 "Outline-based notes management and organizer."
149 :tag "Org"
150 :group 'outlines
151 :group 'hypermedia
152 :group 'calendar)
154 (defcustom org-load-hook '(org-load-default-extensions)
155 "Hook that is run after org.el has been loaded.
156 This happens also after `org' has been provided, so
157 requiring something in this hook that does a (require 'org) is ok."
158 :group 'org
159 :type 'hook)
161 (defcustom org-default-extensions '(org-irc)
162 "Extensions that should always be loaded together with org.el
163 If the description starts with <A>, this means the extension
164 will be autoloaded when needed, to preloading is not necessary."
165 :group 'org
166 :type
167 '(set :greedy t
168 (const :tag " Mouse support (org-mouse.el)" org-mouse)
169 (const :tag "<A> Publishing (org-publish.el)" org-publish)
170 (const :tag "<A> LaTeX export (org-export-latex.el)" org-export-latex)
171 (const :tag " IRC/ERC links (org-irc.el)" org-irc)
172 (const :tag " Apple Mail message links under OS X (org-mac-message.el)" org-mac-message)))
174 (defun org-load-default-extensions ()
175 "Load all extensions that are listed in `org-default-extensions'."
176 (mapc 'require org-default-extensions))
178 ;; FIXME: Needs a separate group...
179 (defcustom org-completion-fallback-command 'hippie-expand
180 "The expansion command called by \\[org-complete] in normal context.
181 Normal means, no org-mode-specific context."
182 :group 'org
183 :type 'function)
185 (defgroup org-startup nil
186 "Options concerning startup of Org-mode."
187 :tag "Org Startup"
188 :group 'org)
190 (defcustom org-startup-folded t
191 "Non-nil means, entering Org-mode will switch to OVERVIEW.
192 This can also be configured on a per-file basis by adding one of
193 the following lines anywhere in the buffer:
195 #+STARTUP: fold
196 #+STARTUP: nofold
197 #+STARTUP: content"
198 :group 'org-startup
199 :type '(choice
200 (const :tag "nofold: show all" nil)
201 (const :tag "fold: overview" t)
202 (const :tag "content: all headlines" content)))
204 (defcustom org-startup-truncated t
205 "Non-nil means, entering Org-mode will set `truncate-lines'.
206 This is useful since some lines containing links can be very long and
207 uninteresting. Also tables look terrible when wrapped."
208 :group 'org-startup
209 :type 'boolean)
211 (defcustom org-startup-align-all-tables nil
212 "Non-nil means, align all tables when visiting a file.
213 This is useful when the column width in tables is forced with <N> cookies
214 in table fields. Such tables will look correct only after the first re-align.
215 This can also be configured on a per-file basis by adding one of
216 the following lines anywhere in the buffer:
217 #+STARTUP: align
218 #+STARTUP: noalign"
219 :group 'org-startup
220 :type 'boolean)
222 (defcustom org-insert-mode-line-in-empty-file nil
223 "Non-nil means insert the first line setting Org-mode in empty files.
224 When the function `org-mode' is called interactively in an empty file, this
225 normally means that the file name does not automatically trigger Org-mode.
226 To ensure that the file will always be in Org-mode in the future, a
227 line enforcing Org-mode will be inserted into the buffer, if this option
228 has been set."
229 :group 'org-startup
230 :type 'boolean)
232 (defcustom org-replace-disputed-keys nil
233 "Non-nil means use alternative key bindings for some keys.
234 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
235 These keys are also used by other packages like `CUA-mode' or `windmove.el'.
236 If you want to use Org-mode together with one of these other modes,
237 or more generally if you would like to move some Org-mode commands to
238 other keys, set this variable and configure the keys with the variable
239 `org-disputed-keys'.
241 This option is only relevant at load-time of Org-mode, and must be set
242 *before* org.el is loaded. Changing it requires a restart of Emacs to
243 become effective."
244 :group 'org-startup
245 :type 'boolean)
247 (if (fboundp 'defvaralias)
248 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys))
250 (defcustom org-disputed-keys
251 '(([(shift up)] . [(meta p)])
252 ([(shift down)] . [(meta n)])
253 ([(shift left)] . [(meta -)])
254 ([(shift right)] . [(meta +)])
255 ([(control shift right)] . [(meta shift +)])
256 ([(control shift left)] . [(meta shift -)]))
257 "Keys for which Org-mode and other modes compete.
258 This is an alist, cars are the default keys, second element specifies
259 the alternative to use when `org-replace-disputed-keys' is t.
261 Keys can be specified in any syntax supported by `define-key'.
262 The value of this option takes effect only at Org-mode's startup,
263 therefore you'll have to restart Emacs to apply it after changing."
264 :group 'org-startup
265 :type 'alist)
267 (defun org-key (key)
268 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
269 Or return the original if not disputed."
270 (if org-replace-disputed-keys
271 (let* ((nkey (key-description key))
272 (x (org-find-if (lambda (x)
273 (equal (key-description (car x)) nkey))
274 org-disputed-keys)))
275 (if x (cdr x) key))
276 key))
278 (defun org-find-if (predicate seq)
279 (catch 'exit
280 (while seq
281 (if (funcall predicate (car seq))
282 (throw 'exit (car seq))
283 (pop seq)))))
285 (defun org-defkey (keymap key def)
286 "Define a key, possibly translated, as returned by `org-key'."
287 (define-key keymap (org-key key) def))
289 (defcustom org-ellipsis nil
290 "The ellipsis to use in the Org-mode outline.
291 When nil, just use the standard three dots. When a string, use that instead,
292 When a face, use the standart 3 dots, but with the specified face.
293 The change affects only Org-mode (which will then use its own display table).
294 Changing this requires executing `M-x org-mode' in a buffer to become
295 effective."
296 :group 'org-startup
297 :type '(choice (const :tag "Default" nil)
298 (face :tag "Face" :value org-warning)
299 (string :tag "String" :value "...#")))
301 (defvar org-display-table nil
302 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
304 (defgroup org-keywords nil
305 "Keywords in Org-mode."
306 :tag "Org Keywords"
307 :group 'org)
309 (defcustom org-deadline-string "DEADLINE:"
310 "String to mark deadline entries.
311 A deadline is this string, followed by a time stamp. Should be a word,
312 terminated by a colon. You can insert a schedule keyword and
313 a timestamp with \\[org-deadline].
314 Changes become only effective after restarting Emacs."
315 :group 'org-keywords
316 :type 'string)
318 (defcustom org-scheduled-string "SCHEDULED:"
319 "String to mark scheduled TODO entries.
320 A schedule is this string, followed by a time stamp. Should be a word,
321 terminated by a colon. You can insert a schedule keyword and
322 a timestamp with \\[org-schedule].
323 Changes become only effective after restarting Emacs."
324 :group 'org-keywords
325 :type 'string)
327 (defcustom org-closed-string "CLOSED:"
328 "String used as the prefix for timestamps logging closing a TODO entry."
329 :group 'org-keywords
330 :type 'string)
332 (defcustom org-clock-string "CLOCK:"
333 "String used as prefix for timestamps clocking work hours on an item."
334 :group 'org-keywords
335 :type 'string)
337 (defcustom org-comment-string "COMMENT"
338 "Entries starting with this keyword will never be exported.
339 An entry can be toggled between COMMENT and normal with
340 \\[org-toggle-comment].
341 Changes become only effective after restarting Emacs."
342 :group 'org-keywords
343 :type 'string)
345 (defcustom org-quote-string "QUOTE"
346 "Entries starting with this keyword will be exported in fixed-width font.
347 Quoting applies only to the text in the entry following the headline, and does
348 not extend beyond the next headline, even if that is lower level.
349 An entry can be toggled between QUOTE and normal with
350 \\[org-toggle-fixed-width-section]."
351 :group 'org-keywords
352 :type 'string)
354 (defconst org-repeat-re
355 ; (concat "\\(?:\\<\\(?:" org-scheduled-string "\\|" org-deadline-string "\\)"
356 ; " +<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*\\)\\(\\+[0-9]+[dwmy]\\)")
357 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*\\(\\+[0-9]+[dwmy]\\)"
358 "Regular expression for specifying repeated events.
359 After a match, group 1 contains the repeat expression.")
361 (defgroup org-structure nil
362 "Options concerning the general structure of Org-mode files."
363 :tag "Org Structure"
364 :group 'org)
366 (defgroup org-reveal-location nil
367 "Options about how to make context of a location visible."
368 :tag "Org Reveal Location"
369 :group 'org-structure)
371 (defconst org-context-choice
372 '(choice
373 (const :tag "Always" t)
374 (const :tag "Never" nil)
375 (repeat :greedy t :tag "Individual contexts"
376 (cons
377 (choice :tag "Context"
378 (const agenda)
379 (const org-goto)
380 (const occur-tree)
381 (const tags-tree)
382 (const link-search)
383 (const mark-goto)
384 (const bookmark-jump)
385 (const isearch)
386 (const default))
387 (boolean))))
388 "Contexts for the reveal options.")
390 (defcustom org-show-hierarchy-above '((default . t))
391 "Non-nil means, show full hierarchy when revealing a location.
392 Org-mode often shows locations in an org-mode file which might have
393 been invisible before. When this is set, the hierarchy of headings
394 above the exposed location is shown.
395 Turning this off for example for sparse trees makes them very compact.
396 Instead of t, this can also be an alist specifying this option for different
397 contexts. Valid contexts are
398 agenda when exposing an entry from the agenda
399 org-goto when using the command `org-goto' on key C-c C-j
400 occur-tree when using the command `org-occur' on key C-c /
401 tags-tree when constructing a sparse tree based on tags matches
402 link-search when exposing search matches associated with a link
403 mark-goto when exposing the jump goal of a mark
404 bookmark-jump when exposing a bookmark location
405 isearch when exiting from an incremental search
406 default default for all contexts not set explicitly"
407 :group 'org-reveal-location
408 :type org-context-choice)
410 (defcustom org-show-following-heading '((default . nil))
411 "Non-nil means, show following heading when revealing a location.
412 Org-mode often shows locations in an org-mode file which might have
413 been invisible before. When this is set, the heading following the
414 match is shown.
415 Turning this off for example for sparse trees makes them very compact,
416 but makes it harder to edit the location of the match. In such a case,
417 use the command \\[org-reveal] to show more context.
418 Instead of t, this can also be an alist specifying this option for different
419 contexts. See `org-show-hierarchy-above' for valid contexts."
420 :group 'org-reveal-location
421 :type org-context-choice)
423 (defcustom org-show-siblings '((default . nil) (isearch t))
424 "Non-nil means, show all sibling heading when revealing a location.
425 Org-mode often shows locations in an org-mode file which might have
426 been invisible before. When this is set, the sibling of the current entry
427 heading are all made visible. If `org-show-hierarchy-above' is t,
428 the same happens on each level of the hierarchy above the current entry.
430 By default this is on for the isearch context, off for all other contexts.
431 Turning this off for example for sparse trees makes them very compact,
432 but makes it harder to edit the location of the match. In such a case,
433 use the command \\[org-reveal] to show more context.
434 Instead of t, this can also be an alist specifying this option for different
435 contexts. See `org-show-hierarchy-above' for valid contexts."
436 :group 'org-reveal-location
437 :type org-context-choice)
439 (defcustom org-show-entry-below '((default . nil))
440 "Non-nil means, show the entry below a headline when revealing a location.
441 Org-mode often shows locations in an org-mode file which might have
442 been invisible before. When this is set, the text below the headline that is
443 exposed is also shown.
445 By default this is off for all contexts.
446 Instead of t, this can also be an alist specifying this option for different
447 contexts. See `org-show-hierarchy-above' for valid contexts."
448 :group 'org-reveal-location
449 :type org-context-choice)
451 (defgroup org-cycle nil
452 "Options concerning visibility cycling in Org-mode."
453 :tag "Org Cycle"
454 :group 'org-structure)
456 (defcustom org-drawers '("PROPERTIES" "CLOCK")
457 "Names of drawers. Drawers are not opened by cycling on the headline above.
458 Drawers only open with a TAB on the drawer line itself. A drawer looks like
459 this:
460 :DRAWERNAME:
461 .....
462 :END:
463 The drawer \"PROPERTIES\" is special for capturing properties through
464 the property API.
466 Drawers can be defined on the per-file basis with a line like:
468 #+DRAWERS: HIDDEN STATE PROPERTIES"
469 :group 'org-structure
470 :type '(repeat (string :tag "Drawer Name")))
472 (defcustom org-cycle-global-at-bob nil
473 "Cycle globally if cursor is at beginning of buffer and not at a headline.
474 This makes it possible to do global cycling without having to use S-TAB or
475 C-u TAB. For this special case to work, the first line of the buffer
476 must not be a headline - it may be empty ot some other text. When used in
477 this way, `org-cycle-hook' is disables temporarily, to make sure the
478 cursor stays at the beginning of the buffer.
479 When this option is nil, don't do anything special at the beginning
480 of the buffer."
481 :group 'org-cycle
482 :type 'boolean)
484 (defcustom org-cycle-emulate-tab t
485 "Where should `org-cycle' emulate TAB.
486 nil Never
487 white Only in completely white lines
488 whitestart Only at the beginning of lines, before the first non-white char
489 t Everywhere except in headlines
490 exc-hl-bol Everywhere except at the start of a headline
491 If TAB is used in a place where it does not emulate TAB, the current subtree
492 visibility is cycled."
493 :group 'org-cycle
494 :type '(choice (const :tag "Never" nil)
495 (const :tag "Only in completely white lines" white)
496 (const :tag "Before first char in a line" whitestart)
497 (const :tag "Everywhere except in headlines" t)
498 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)
501 (defcustom org-cycle-separator-lines 2
502 "Number of empty lines needed to keep an empty line between collapsed trees.
503 If you leave an empty line between the end of a subtree and the following
504 headline, this empty line is hidden when the subtree is folded.
505 Org-mode will leave (exactly) one empty line visible if the number of
506 empty lines is equal or larger to the number given in this variable.
507 So the default 2 means, at least 2 empty lines after the end of a subtree
508 are needed to produce free space between a collapsed subtree and the
509 following headline.
511 Special case: when 0, never leave empty lines in collapsed view."
512 :group 'org-cycle
513 :type 'integer)
515 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
516 org-cycle-hide-drawers
517 org-cycle-show-empty-lines
518 org-optimize-window-after-visibility-change)
519 "Hook that is run after `org-cycle' has changed the buffer visibility.
520 The function(s) in this hook must accept a single argument which indicates
521 the new state that was set by the most recent `org-cycle' command. The
522 argument is a symbol. After a global state change, it can have the values
523 `overview', `content', or `all'. After a local state change, it can have
524 the values `folded', `children', or `subtree'."
525 :group 'org-cycle
526 :type 'hook)
528 (defgroup org-edit-structure nil
529 "Options concerning structure editing in Org-mode."
530 :tag "Org Edit Structure"
531 :group 'org-structure)
533 (defcustom org-odd-levels-only nil
534 "Non-nil means, skip even levels and only use odd levels for the outline.
535 This has the effect that two stars are being added/taken away in
536 promotion/demotion commands. It also influences how levels are
537 handled by the exporters.
538 Changing it requires restart of `font-lock-mode' to become effective
539 for fontification also in regions already fontified.
540 You may also set this on a per-file basis by adding one of the following
541 lines to the buffer:
543 #+STARTUP: odd
544 #+STARTUP: oddeven"
545 :group 'org-edit-structure
546 :group 'org-font-lock
547 :type 'boolean)
549 (defcustom org-adapt-indentation t
550 "Non-nil means, adapt indentation when promoting and demoting.
551 When this is set and the *entire* text in an entry is indented, the
552 indentation is increased by one space in a demotion command, and
553 decreased by one in a promotion command. If any line in the entry
554 body starts at column 0, indentation is not changed at all."
555 :group 'org-edit-structure
556 :type 'boolean)
558 (defcustom org-special-ctrl-a/e nil
559 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
560 When t, `C-a' will bring back the cursor to the beginning of the
561 headline text, i.e. after the stars and after a possible TODO keyword.
562 In an item, this will be the position after the bullet.
563 When the cursor is already at that position, another `C-a' will bring
564 it to the beginning of the line.
565 `C-e' will jump to the end of the headline, ignoring the presence of tags
566 in the headline. A second `C-e' will then jump to the true end of the
567 line, after any tags.
568 When set to the symbol `reversed', the first `C-a' or `C-e' works normally,
569 and only a directly following, identical keypress will bring the cursor
570 to the special positions."
571 :group 'org-edit-structure
572 :type '(choice
573 (const :tag "off" nil)
574 (const :tag "after bullet first" t)
575 (const :tag "border first" reversed)))
577 (if (fboundp 'defvaralias)
578 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e))
580 (defcustom org-special-ctrl-k nil
581 "Non-nil means `C-k' will behave specially in headlines.
582 When nil, `C-k' will call the default `kill-line' command.
583 When t, the following will happen while the cursor is in the headline:
585 - When the cursor is at the beginning of a headline, kill the entire
586 line and possible the folded subtree below the line.
587 - When in the middle of the headline text, kill the headline up to the tags.
588 - When after the headline text, kill the tags."
589 :group 'org-edit-structure
590 :type 'boolean)
592 (defcustom org-M-RET-may-split-line '((default . t))
593 "Non-nil means, M-RET will split the line at the cursor position.
594 When nil, it will go to the end of the line before making a
595 new line.
596 You may also set this option in a different way for different
597 contexts. Valid contexts are:
599 headline when creating a new headline
600 item when creating a new item
601 table in a table field
602 default the value to be used for all contexts not explicitly
603 customized"
604 :group 'org-structure
605 :group 'org-table
606 :type '(choice
607 (const :tag "Always" t)
608 (const :tag "Never" nil)
609 (repeat :greedy t :tag "Individual contexts"
610 (cons
611 (choice :tag "Context"
612 (const headline)
613 (const item)
614 (const table)
615 (const default))
616 (boolean)))))
619 (defcustom org-blank-before-new-entry '((heading . nil)
620 (plain-list-item . nil))
621 "Should `org-insert-heading' leave a blank line before new heading/item?
622 The value is an alist, with `heading' and `plain-list-item' as car,
623 and a boolean flag as cdr."
624 :group 'org-edit-structure
625 :type '(list
626 (cons (const heading) (boolean))
627 (cons (const plain-list-item) (boolean))))
629 (defcustom org-insert-heading-hook nil
630 "Hook being run after inserting a new heading."
631 :group 'org-edit-structure
632 :type 'hook)
634 (defcustom org-enable-fixed-width-editor t
635 "Non-nil means, lines starting with \":\" are treated as fixed-width.
636 This currently only means, they are never auto-wrapped.
637 When nil, such lines will be treated like ordinary lines.
638 See also the QUOTE keyword."
639 :group 'org-edit-structure
640 :type 'boolean)
642 (defcustom org-goto-auto-isearch t
643 "Non-nil means, typing characters in org-goto starts incremental search."
644 :group 'org-edit-structure
645 :type 'boolean)
647 (defgroup org-sparse-trees nil
648 "Options concerning sparse trees in Org-mode."
649 :tag "Org Sparse Trees"
650 :group 'org-structure)
652 (defcustom org-highlight-sparse-tree-matches t
653 "Non-nil means, highlight all matches that define a sparse tree.
654 The highlights will automatically disappear the next time the buffer is
655 changed by an edit command."
656 :group 'org-sparse-trees
657 :type 'boolean)
659 (defcustom org-remove-highlights-with-change t
660 "Non-nil means, any change to the buffer will remove temporary highlights.
661 Such highlights are created by `org-occur' and `org-clock-display'.
662 When nil, `C-c C-c needs to be used to get rid of the highlights.
663 The highlights created by `org-preview-latex-fragment' always need
664 `C-c C-c' to be removed."
665 :group 'org-sparse-trees
666 :group 'org-time
667 :type 'boolean)
670 (defcustom org-occur-hook '(org-first-headline-recenter)
671 "Hook that is run after `org-occur' has constructed a sparse tree.
672 This can be used to recenter the window to show as much of the structure
673 as possible."
674 :group 'org-sparse-trees
675 :type 'hook)
677 (defgroup org-plain-lists nil
678 "Options concerning plain lists in Org-mode."
679 :tag "Org Plain lists"
680 :group 'org-structure)
682 (defcustom org-cycle-include-plain-lists nil
683 "Non-nil means, include plain lists into visibility cycling.
684 This means that during cycling, plain list items will *temporarily* be
685 interpreted as outline headlines with a level given by 1000+i where i is the
686 indentation of the bullet. In all other operations, plain list items are
687 not seen as headlines. For example, you cannot assign a TODO keyword to
688 such an item."
689 :group 'org-plain-lists
690 :type 'boolean)
692 (defcustom org-plain-list-ordered-item-terminator t
693 "The character that makes a line with leading number an ordered list item.
694 Valid values are ?. and ?\). To get both terminators, use t. While
695 ?. may look nicer, it creates the danger that a line with leading
696 number may be incorrectly interpreted as an item. ?\) therefore is
697 the safe choice."
698 :group 'org-plain-lists
699 :type '(choice (const :tag "dot like in \"2.\"" ?.)
700 (const :tag "paren like in \"2)\"" ?\))
701 (const :tab "both" t)))
703 (defcustom org-auto-renumber-ordered-lists t
704 "Non-nil means, automatically renumber ordered plain lists.
705 Renumbering happens when the sequence have been changed with
706 \\[org-shiftmetaup] or \\[org-shiftmetadown]. After other editing commands,
707 use \\[org-ctrl-c-ctrl-c] to trigger renumbering."
708 :group 'org-plain-lists
709 :type 'boolean)
711 (defcustom org-provide-checkbox-statistics t
712 "Non-nil means, update checkbox statistics after insert and toggle.
713 When this is set, checkbox statistics is updated each time you either insert
714 a new checkbox with \\[org-insert-todo-heading] or toggle a checkbox
715 with \\[org-ctrl-c-ctrl-c\\]."
716 :group 'org-plain-lists
717 :type 'boolean)
719 (defgroup org-archive nil
720 "Options concerning archiving in Org-mode."
721 :tag "Org Archive"
722 :group 'org-structure)
724 (defcustom org-archive-tag "ARCHIVE"
725 "The tag that marks a subtree as archived.
726 An archived subtree does not open during visibility cycling, and does
727 not contribute to the agenda listings.
728 After changing this, font-lock must be restarted in the relevant buffers to
729 get the proper fontification."
730 :group 'org-archive
731 :group 'org-keywords
732 :type 'string)
734 (defcustom org-agenda-skip-archived-trees t
735 "Non-nil means, the agenda will skip any items located in archived trees.
736 An archived tree is a tree marked with the tag ARCHIVE."
737 :group 'org-archive
738 :group 'org-agenda-skip
739 :type 'boolean)
741 (defcustom org-cycle-open-archived-trees nil
742 "Non-nil means, `org-cycle' will open archived trees.
743 An archived tree is a tree marked with the tag ARCHIVE.
744 When nil, archived trees will stay folded. You can still open them with
745 normal outline commands like `show-all', but not with the cycling commands."
746 :group 'org-archive
747 :group 'org-cycle
748 :type 'boolean)
750 (defcustom org-sparse-tree-open-archived-trees nil
751 "Non-nil means sparse tree construction shows matches in archived trees.
752 When nil, matches in these trees are highlighted, but the trees are kept in
753 collapsed state."
754 :group 'org-archive
755 :group 'org-sparse-trees
756 :type 'boolean)
758 (defcustom org-archive-location "%s_archive::"
759 "The location where subtrees should be archived.
760 This string consists of two parts, separated by a double-colon.
762 The first part is a file name - when omitted, archiving happens in the same
763 file. %s will be replaced by the current file name (without directory part).
764 Archiving to a different file is useful to keep archived entries from
765 contributing to the Org-mode Agenda.
767 The part after the double colon is a headline. The archived entries will be
768 filed under that headline. When omitted, the subtrees are simply filed away
769 at the end of the file, as top-level entries.
771 Here are a few examples:
772 \"%s_archive::\"
773 If the current file is Projects.org, archive in file
774 Projects.org_archive, as top-level trees. This is the default.
776 \"::* Archived Tasks\"
777 Archive in the current file, under the top-level headline
778 \"* Archived Tasks\".
780 \"~/org/archive.org::\"
781 Archive in file ~/org/archive.org (absolute path), as top-level trees.
783 \"basement::** Finished Tasks\"
784 Archive in file ./basement (relative path), as level 3 trees
785 below the level 2 heading \"** Finished Tasks\".
787 You may set this option on a per-file basis by adding to the buffer a
788 line like
790 #+ARCHIVE: basement::** Finished Tasks"
791 :group 'org-archive
792 :type 'string)
794 (defcustom org-archive-mark-done t
795 "Non-nil means, mark entries as DONE when they are moved to the archive file.
796 This can be a string to set the keyword to use. When t, Org-mode will
797 use the first keyword in its list that means done."
798 :group 'org-archive
799 :type '(choice
800 (const :tag "No" nil)
801 (const :tag "Yes" t)
802 (string :tag "Use this keyword")))
804 (defcustom org-archive-stamp-time t
805 "Non-nil means, add a time stamp to entries moved to an archive file.
806 This variable is obsolete and has no effect anymore, instead add ot remove
807 `time' from the variablle `org-archive-save-context-info'."
808 :group 'org-archive
809 :type 'boolean)
811 (defcustom org-archive-save-context-info '(time file olpath category todo itags)
812 "Parts of context info that should be stored as properties when archiving.
813 When a subtree is moved to an archive file, it looses information given by
814 context, like inherited tags, the category, and possibly also the TODO
815 state (depending on the variable `org-archive-mark-done').
816 This variable can be a list of any of the following symbols:
818 time The time of archiving.
819 file The file where the entry originates.
820 itags The local tags, in the headline of the subtree.
821 ltags The tags the subtree inherits from further up the hierarchy.
822 todo The pre-archive TODO state.
823 category The category, taken from file name or #+CATEGORY lines.
824 olpath The outline path to the item. These are all headlines above
825 the current item, separated by /, like a file path.
827 For each symbol present in the list, a property will be created in
828 the archived entry, with a prefix \"PRE_ARCHIVE_\", to remember this
829 information."
830 :group 'org-archive
831 :type '(set :greedy t
832 (const :tag "Time" time)
833 (const :tag "File" file)
834 (const :tag "Category" category)
835 (const :tag "TODO state" todo)
836 (const :tag "TODO state" priority)
837 (const :tag "Inherited tags" itags)
838 (const :tag "Outline path" olpath)
839 (const :tag "Local tags" ltags)))
841 (defgroup org-imenu-and-speedbar nil
842 "Options concerning imenu and speedbar in Org-mode."
843 :tag "Org Imenu and Speedbar"
844 :group 'org-structure)
846 (defcustom org-imenu-depth 2
847 "The maximum level for Imenu access to Org-mode headlines.
848 This also applied for speedbar access."
849 :group 'org-imenu-and-speedbar
850 :type 'number)
852 (defgroup org-table nil
853 "Options concerning tables in Org-mode."
854 :tag "Org Table"
855 :group 'org)
857 (defcustom org-enable-table-editor 'optimized
858 "Non-nil means, lines starting with \"|\" are handled by the table editor.
859 When nil, such lines will be treated like ordinary lines.
861 When equal to the symbol `optimized', the table editor will be optimized to
862 do the following:
863 - Automatic overwrite mode in front of whitespace in table fields.
864 This makes the structure of the table stay in tact as long as the edited
865 field does not exceed the column width.
866 - Minimize the number of realigns. Normally, the table is aligned each time
867 TAB or RET are pressed to move to another field. With optimization this
868 happens only if changes to a field might have changed the column width.
869 Optimization requires replacing the functions `self-insert-command',
870 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
871 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
872 very good at guessing when a re-align will be necessary, but you can always
873 force one with \\[org-ctrl-c-ctrl-c].
875 If you would like to use the optimized version in Org-mode, but the
876 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
878 This variable can be used to turn on and off the table editor during a session,
879 but in order to toggle optimization, a restart is required.
881 See also the variable `org-table-auto-blank-field'."
882 :group 'org-table
883 :type '(choice
884 (const :tag "off" nil)
885 (const :tag "on" t)
886 (const :tag "on, optimized" optimized)))
888 (defcustom orgtbl-optimized (eq org-enable-table-editor 'optimized)
889 "Non-nil means, use the optimized table editor version for `orgtbl-mode'.
890 In the optimized version, the table editor takes over all simple keys that
891 normally just insert a character. In tables, the characters are inserted
892 in a way to minimize disturbing the table structure (i.e. in overwrite mode
893 for empty fields). Outside tables, the correct binding of the keys is
894 restored.
896 The default for this option is t if the optimized version is also used in
897 Org-mode. See the variable `org-enable-table-editor' for details. Changing
898 this variable requires a restart of Emacs to become effective."
899 :group 'org-table
900 :type 'boolean)
902 (defcustom orgtbl-radio-table-templates
903 '((latex-mode "% BEGIN RECEIVE ORGTBL %n
904 % END RECEIVE ORGTBL %n
905 \\begin{comment}
906 #+ORGTBL: SEND %n orgtbl-to-latex :splice nil :skip 0
907 | | |
908 \\end{comment}\n")
909 (texinfo-mode "@c BEGIN RECEIVE ORGTBL %n
910 @c END RECEIVE ORGTBL %n
911 @ignore
912 #+ORGTBL: SEND %n orgtbl-to-html :splice nil :skip 0
913 | | |
914 @end ignore\n")
915 (html-mode "<!-- BEGIN RECEIVE ORGTBL %n -->
916 <!-- END RECEIVE ORGTBL %n -->
917 <!--
918 #+ORGTBL: SEND %n orgtbl-to-html :splice nil :skip 0
919 | | |
920 -->\n"))
921 "Templates for radio tables in different major modes.
922 All occurrences of %n in a template will be replaced with the name of the
923 table, obtained by prompting the user."
924 :group 'org-table
925 :type '(repeat
926 (list (symbol :tag "Major mode")
927 (string :tag "Format"))))
929 (defgroup org-table-settings nil
930 "Settings for tables in Org-mode."
931 :tag "Org Table Settings"
932 :group 'org-table)
934 (defcustom org-table-default-size "5x2"
935 "The default size for newly created tables, Columns x Rows."
936 :group 'org-table-settings
937 :type 'string)
939 (defcustom org-table-number-regexp
940 "^\\([<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%:]*\\|\\(0[xX]\\)[0-9a-fA-F]+\\|nan\\)$"
941 "Regular expression for recognizing numbers in table columns.
942 If a table column contains mostly numbers, it will be aligned to the
943 right. If not, it will be aligned to the left.
945 The default value of this option is a regular expression which allows
946 anything which looks remotely like a number as used in scientific
947 context. For example, all of the following will be considered a
948 number:
949 12 12.2 2.4e-08 2x10^12 4.034+-0.02 2.7(10) >3.5
951 Other options offered by the customize interface are more restrictive."
952 :group 'org-table-settings
953 :type '(choice
954 (const :tag "Positive Integers"
955 "^[0-9]+$")
956 (const :tag "Integers"
957 "^[-+]?[0-9]+$")
958 (const :tag "Floating Point Numbers"
959 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.[0-9]*\\)$")
960 (const :tag "Floating Point Number or Integer"
961 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.?[0-9]*\\)$")
962 (const :tag "Exponential, Floating point, Integer"
963 "^[-+]?[0-9.]+\\([eEdD][-+0-9]+\\)?$")
964 (const :tag "Very General Number-Like, including hex"
965 "^\\([<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%]*\\|\\(0[xX]\\)[0-9a-fA-F]+\\|nan\\)$")
966 (string :tag "Regexp:")))
968 (defcustom org-table-number-fraction 0.5
969 "Fraction of numbers in a column required to make the column align right.
970 In a column all non-white fields are considered. If at least this
971 fraction of fields is matched by `org-table-number-fraction',
972 alignment to the right border applies."
973 :group 'org-table-settings
974 :type 'number)
976 (defgroup org-table-editing nil
977 "Behavior of tables during editing in Org-mode."
978 :tag "Org Table Editing"
979 :group 'org-table)
981 (defcustom org-table-automatic-realign t
982 "Non-nil means, automatically re-align table when pressing TAB or RETURN.
983 When nil, aligning is only done with \\[org-table-align], or after column
984 removal/insertion."
985 :group 'org-table-editing
986 :type 'boolean)
988 (defcustom org-table-auto-blank-field t
989 "Non-nil means, automatically blank table field when starting to type into it.
990 This only happens when typing immediately after a field motion
991 command (TAB, S-TAB or RET).
992 Only relevant when `org-enable-table-editor' is equal to `optimized'."
993 :group 'org-table-editing
994 :type 'boolean)
996 (defcustom org-table-tab-jumps-over-hlines t
997 "Non-nil means, tab in the last column of a table with jump over a hline.
998 If a horizontal separator line is following the current line,
999 `org-table-next-field' can either create a new row before that line, or jump
1000 over the line. When this option is nil, a new line will be created before
1001 this line."
1002 :group 'org-table-editing
1003 :type 'boolean)
1005 (defcustom org-table-tab-recognizes-table.el t
1006 "Non-nil means, TAB will automatically notice a table.el table.
1007 When it sees such a table, it moves point into it and - if necessary -
1008 calls `table-recognize-table'."
1009 :group 'org-table-editing
1010 :type 'boolean)
1012 (defgroup org-table-calculation nil
1013 "Options concerning tables in Org-mode."
1014 :tag "Org Table Calculation"
1015 :group 'org-table)
1017 (defcustom org-table-use-standard-references t
1018 "Should org-mode work with table refrences like B3 instead of @3$2?
1019 Possible values are:
1020 nil never use them
1021 from accept as input, do not present for editing
1022 t: accept as input and present for editing"
1023 :group 'org-table-calculation
1024 :type '(choice
1025 (const :tag "Never, don't even check unser input for them" nil)
1026 (const :tag "Always, both as user input, and when editing" t)
1027 (const :tag "Convert user input, don't offer during editing" 'from)))
1029 (defcustom org-table-copy-increment t
1030 "Non-nil means, increment when copying current field with \\[org-table-copy-down]."
1031 :group 'org-table-calculation
1032 :type 'boolean)
1034 (defcustom org-calc-default-modes
1035 '(calc-internal-prec 12
1036 calc-float-format (float 5)
1037 calc-angle-mode deg
1038 calc-prefer-frac nil
1039 calc-symbolic-mode nil
1040 calc-date-format (YYYY "-" MM "-" DD " " Www (" " HH ":" mm))
1041 calc-display-working-message t
1043 "List with Calc mode settings for use in calc-eval for table formulas.
1044 The list must contain alternating symbols (Calc modes variables and values).
1045 Don't remove any of the default settings, just change the values. Org-mode
1046 relies on the variables to be present in the list."
1047 :group 'org-table-calculation
1048 :type 'plist)
1050 (defcustom org-table-formula-evaluate-inline t
1051 "Non-nil means, TAB and RET evaluate a formula in current table field.
1052 If the current field starts with an equal sign, it is assumed to be a formula
1053 which should be evaluated as described in the manual and in the documentation
1054 string of the command `org-table-eval-formula'. This feature requires the
1055 Emacs calc package.
1056 When this variable is nil, formula calculation is only available through
1057 the command \\[org-table-eval-formula]."
1058 :group 'org-table-calculation
1059 :type 'boolean)
1061 (defcustom org-table-formula-use-constants t
1062 "Non-nil means, interpret constants in formulas in tables.
1063 A constant looks like `$c' or `$Grav' and will be replaced before evaluation
1064 by the value given in `org-table-formula-constants', or by a value obtained
1065 from the `constants.el' package."
1066 :group 'org-table-calculation
1067 :type 'boolean)
1069 (defcustom org-table-formula-constants nil
1070 "Alist with constant names and values, for use in table formulas.
1071 The car of each element is a name of a constant, without the `$' before it.
1072 The cdr is the value as a string. For example, if you'd like to use the
1073 speed of light in a formula, you would configure
1075 (setq org-table-formula-constants '((\"c\" . \"299792458.\")))
1077 and then use it in an equation like `$1*$c'.
1079 Constants can also be defined on a per-file basis using a line like
1081 #+CONSTANTS: c=299792458. pi=3.14 eps=2.4e-6"
1082 :group 'org-table-calculation
1083 :type '(repeat
1084 (cons (string :tag "name")
1085 (string :tag "value"))))
1087 (defvar org-table-formula-constants-local nil
1088 "Local version of `org-table-formula-constants'.")
1089 (make-variable-buffer-local 'org-table-formula-constants-local)
1091 (defcustom org-table-allow-automatic-line-recalculation t
1092 "Non-nil means, lines marked with |#| or |*| will be recomputed automatically.
1093 Automatically means, when TAB or RET or C-c C-c are pressed in the line."
1094 :group 'org-table-calculation
1095 :type 'boolean)
1097 (defgroup org-link nil
1098 "Options concerning links in Org-mode."
1099 :tag "Org Link"
1100 :group 'org)
1102 (defvar org-link-abbrev-alist-local nil
1103 "Buffer-local version of `org-link-abbrev-alist', which see.
1104 The value of this is taken from the #+LINK lines.")
1105 (make-variable-buffer-local 'org-link-abbrev-alist-local)
1107 (defcustom org-link-abbrev-alist nil
1108 "Alist of link abbreviations.
1109 The car of each element is a string, to be replaced at the start of a link.
1110 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1111 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1113 [[linkkey:tag][description]]
1115 If REPLACE is a string, the tag will simply be appended to create the link.
1116 If the string contains \"%s\", the tag will be inserted there.
1118 REPLACE may also be a function that will be called with the tag as the
1119 only argument to create the link, which should be returned as a string.
1121 See the manual for examples."
1122 :group 'org-link
1123 :type 'alist)
1125 (defcustom org-descriptive-links t
1126 "Non-nil means, hide link part and only show description of bracket links.
1127 Bracket links are like [[link][descritpion]]. This variable sets the initial
1128 state in new org-mode buffers. The setting can then be toggled on a
1129 per-buffer basis from the Org->Hyperlinks menu."
1130 :group 'org-link
1131 :type 'boolean)
1133 (defcustom org-link-file-path-type 'adaptive
1134 "How the path name in file links should be stored.
1135 Valid values are:
1137 relative Relative to the current directory, i.e. the directory of the file
1138 into which the link is being inserted.
1139 absolute Absolute path, if possible with ~ for home directory.
1140 noabbrev Absolute path, no abbreviation of home directory.
1141 adaptive Use relative path for files in the current directory and sub-
1142 directories of it. For other files, use an absolute path."
1143 :group 'org-link
1144 :type '(choice
1145 (const relative)
1146 (const absolute)
1147 (const noabbrev)
1148 (const adaptive)))
1150 (defcustom org-activate-links '(bracket angle plain radio tag date)
1151 "Types of links that should be activated in Org-mode files.
1152 This is a list of symbols, each leading to the activation of a certain link
1153 type. In principle, it does not hurt to turn on most link types - there may
1154 be a small gain when turning off unused link types. The types are:
1156 bracket The recommended [[link][description]] or [[link]] links with hiding.
1157 angular Links in angular brackes that may contain whitespace like
1158 <bbdb:Carsten Dominik>.
1159 plain Plain links in normal text, no whitespace, like http://google.com.
1160 radio Text that is matched by a radio target, see manual for details.
1161 tag Tag settings in a headline (link to tag search).
1162 date Time stamps (link to calendar).
1164 Changing this variable requires a restart of Emacs to become effective."
1165 :group 'org-link
1166 :type '(set (const :tag "Double bracket links (new style)" bracket)
1167 (const :tag "Angular bracket links (old style)" angular)
1168 (const :tag "Plain text links" plain)
1169 (const :tag "Radio target matches" radio)
1170 (const :tag "Tags" tag)
1171 (const :tag "Timestamps" date)))
1173 (defgroup org-link-store nil
1174 "Options concerning storing links in Org-mode"
1175 :tag "Org Store Link"
1176 :group 'org-link)
1178 (defcustom org-email-link-description-format "Email %c: %.30s"
1179 "Format of the description part of a link to an email or usenet message.
1180 The following %-excapes will be replaced by corresponding information:
1182 %F full \"From\" field
1183 %f name, taken from \"From\" field, address if no name
1184 %T full \"To\" field
1185 %t first name in \"To\" field, address if no name
1186 %c correspondent. Unually \"from NAME\", but if you sent it yourself, it
1187 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1188 %s subject
1189 %m message-id.
1191 You may use normal field width specification between the % and the letter.
1192 This is for example useful to limit the length of the subject.
1194 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1195 :group 'org-link-store
1196 :type 'string)
1198 (defcustom org-from-is-user-regexp
1199 (let (r1 r2)
1200 (when (and user-mail-address (not (string= user-mail-address "")))
1201 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1202 (when (and user-full-name (not (string= user-full-name "")))
1203 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1204 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1205 "Regexp mached against the \"From:\" header of an email or usenet message.
1206 It should match if the message is from the user him/herself."
1207 :group 'org-link-store
1208 :type 'regexp)
1210 (defcustom org-context-in-file-links t
1211 "Non-nil means, file links from `org-store-link' contain context.
1212 A search string will be added to the file name with :: as separator and
1213 used to find the context when the link is activated by the command
1214 `org-open-at-point'.
1215 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1216 negates this setting for the duration of the command."
1217 :group 'org-link-store
1218 :type 'boolean)
1220 (defcustom org-keep-stored-link-after-insertion nil
1221 "Non-nil means, keep link in list for entire session.
1223 The command `org-store-link' adds a link pointing to the current
1224 location to an internal list. These links accumulate during a session.
1225 The command `org-insert-link' can be used to insert links into any
1226 Org-mode file (offering completion for all stored links). When this
1227 option is nil, every link which has been inserted once using \\[org-insert-link]
1228 will be removed from the list, to make completing the unused links
1229 more efficient."
1230 :group 'org-link-store
1231 :type 'boolean)
1233 (defcustom org-usenet-links-prefer-google nil
1234 "Non-nil means, `org-store-link' will create web links to Google groups.
1235 When nil, Gnus will be used for such links.
1236 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1237 negates this setting for the duration of the command."
1238 :group 'org-link-store
1239 :type 'boolean)
1241 (defgroup org-link-follow nil
1242 "Options concerning following links in Org-mode"
1243 :tag "Org Follow Link"
1244 :group 'org-link)
1246 (defcustom org-tab-follows-link nil
1247 "Non-nil means, on links TAB will follow the link.
1248 Needs to be set before org.el is loaded."
1249 :group 'org-link-follow
1250 :type 'boolean)
1252 (defcustom org-return-follows-link nil
1253 "Non-nil means, on links RET will follow the link.
1254 Needs to be set before org.el is loaded."
1255 :group 'org-link-follow
1256 :type 'boolean)
1258 (defcustom org-mouse-1-follows-link mouse-1-click-follows-link
1259 "Non-nil means, mouse-1 on a link will follow the link.
1260 A longer mouse click will still set point. Does not work on XEmacs.
1261 Needs to be set before org.el is loaded."
1262 :group 'org-link-follow
1263 :type 'boolean)
1265 (defcustom org-mark-ring-length 4
1266 "Number of different positions to be recorded in the ring
1267 Changing this requires a restart of Emacs to work correctly."
1268 :group 'org-link-follow
1269 :type 'interger)
1271 (defcustom org-link-frame-setup
1272 '((vm . vm-visit-folder-other-frame)
1273 (gnus . gnus-other-frame)
1274 (file . find-file-other-window))
1275 "Setup the frame configuration for following links.
1276 When following a link with Emacs, it may often be useful to display
1277 this link in another window or frame. This variable can be used to
1278 set this up for the different types of links.
1279 For VM, use any of
1280 `vm-visit-folder'
1281 `vm-visit-folder-other-frame'
1282 For Gnus, use any of
1283 `gnus'
1284 `gnus-other-frame'
1285 For FILE, use any of
1286 `find-file'
1287 `find-file-other-window'
1288 `find-file-other-frame'
1289 For the calendar, use the variable `calendar-setup'.
1290 For BBDB, it is currently only possible to display the matches in
1291 another window."
1292 :group 'org-link-follow
1293 :type '(list
1294 (cons (const vm)
1295 (choice
1296 (const vm-visit-folder)
1297 (const vm-visit-folder-other-window)
1298 (const vm-visit-folder-other-frame)))
1299 (cons (const gnus)
1300 (choice
1301 (const gnus)
1302 (const gnus-other-frame)))
1303 (cons (const file)
1304 (choice
1305 (const find-file)
1306 (const find-file-other-window)
1307 (const find-file-other-frame)))))
1309 (defcustom org-display-internal-link-with-indirect-buffer nil
1310 "Non-nil means, use indirect buffer to display infile links.
1311 Activating internal links (from one location in a file to another location
1312 in the same file) normally just jumps to the location. When the link is
1313 activated with a C-u prefix (or with mouse-3), the link is displayed in
1314 another window. When this option is set, the other window actually displays
1315 an indirect buffer clone of the current buffer, to avoid any visibility
1316 changes to the current buffer."
1317 :group 'org-link-follow
1318 :type 'boolean)
1320 (defcustom org-open-non-existing-files nil
1321 "Non-nil means, `org-open-file' will open non-existing files.
1322 When nil, an error will be generated."
1323 :group 'org-link-follow
1324 :type 'boolean)
1326 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1327 "Function and arguments to call for following mailto links.
1328 This is a list with the first element being a lisp function, and the
1329 remaining elements being arguments to the function. In string arguments,
1330 %a will be replaced by the address, and %s will be replaced by the subject
1331 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1332 :group 'org-link-follow
1333 :type '(choice
1334 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1335 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1336 (const :tag "message-mail" (message-mail "%a" "%s"))
1337 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1339 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1340 "Non-nil means, ask for confirmation before executing shell links.
1341 Shell links can be dangerous: just think about a link
1343 [[shell:rm -rf ~/*][Google Search]]
1345 This link would show up in your Org-mode document as \"Google Search\",
1346 but really it would remove your entire home directory.
1347 Therefore we advise against setting this variable to nil.
1348 Just change it to `y-or-n-p' of you want to confirm with a
1349 single keystroke rather than having to type \"yes\"."
1350 :group 'org-link-follow
1351 :type '(choice
1352 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1353 (const :tag "with y-or-n (faster)" y-or-n-p)
1354 (const :tag "no confirmation (dangerous)" nil)))
1356 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1357 "Non-nil means, ask for confirmation before executing Emacs Lisp links.
1358 Elisp links can be dangerous: just think about a link
1360 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1362 This link would show up in your Org-mode document as \"Google Search\",
1363 but really it would remove your entire home directory.
1364 Therefore we advise against setting this variable to nil.
1365 Just change it to `y-or-n-p' of you want to confirm with a
1366 single keystroke rather than having to type \"yes\"."
1367 :group 'org-link-follow
1368 :type '(choice
1369 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1370 (const :tag "with y-or-n (faster)" y-or-n-p)
1371 (const :tag "no confirmation (dangerous)" nil)))
1373 (defconst org-file-apps-defaults-gnu
1374 '((remote . emacs)
1375 (t . mailcap))
1376 "Default file applications on a UNIX or GNU/Linux system.
1377 See `org-file-apps'.")
1379 (defconst org-file-apps-defaults-macosx
1380 '((remote . emacs)
1381 (t . "open %s")
1382 ("ps" . "gv %s")
1383 ("ps.gz" . "gv %s")
1384 ("eps" . "gv %s")
1385 ("eps.gz" . "gv %s")
1386 ("dvi" . "xdvi %s")
1387 ("fig" . "xfig %s"))
1388 "Default file applications on a MacOS X system.
1389 The system \"open\" is known as a default, but we use X11 applications
1390 for some files for which the OS does not have a good default.
1391 See `org-file-apps'.")
1393 (defconst org-file-apps-defaults-windowsnt
1394 (list
1395 '(remote . emacs)
1396 (cons t
1397 (list (if (featurep 'xemacs)
1398 'mswindows-shell-execute
1399 'w32-shell-execute)
1400 "open" 'file)))
1401 "Default file applications on a Windows NT system.
1402 The system \"open\" is used for most files.
1403 See `org-file-apps'.")
1405 (defcustom org-file-apps
1407 ("txt" . emacs)
1408 ("tex" . emacs)
1409 ("ltx" . emacs)
1410 ("org" . emacs)
1411 ("el" . emacs)
1412 ("bib" . emacs)
1414 "External applications for opening `file:path' items in a document.
1415 Org-mode uses system defaults for different file types, but
1416 you can use this variable to set the application for a given file
1417 extension. The entries in this list are cons cells where the car identifies
1418 files and the cdr the corresponding command. Possible values for the
1419 file identifier are
1420 \"ext\" A string identifying an extension
1421 `directory' Matches a directory
1422 `remote' Matches a remote file, accessible through tramp or efs.
1423 Remote files most likely should be visited through Emacs
1424 because external applications cannot handle such paths.
1425 t Default for all remaining files
1427 Possible values for the command are:
1428 `emacs' The file will be visited by the current Emacs process.
1429 `default' Use the default application for this file type.
1430 string A command to be executed by a shell; %s will be replaced
1431 by the path to the file.
1432 sexp A Lisp form which will be evaluated. The file path will
1433 be available in the Lisp variable `file'.
1434 For more examples, see the system specific constants
1435 `org-file-apps-defaults-macosx'
1436 `org-file-apps-defaults-windowsnt'
1437 `org-file-apps-defaults-gnu'."
1438 :group 'org-link-follow
1439 :type '(repeat
1440 (cons (choice :value ""
1441 (string :tag "Extension")
1442 (const :tag "Default for unrecognized files" t)
1443 (const :tag "Remote file" remote)
1444 (const :tag "Links to a directory" directory))
1445 (choice :value ""
1446 (const :tag "Visit with Emacs" emacs)
1447 (const :tag "Use system default" default)
1448 (string :tag "Command")
1449 (sexp :tag "Lisp form")))))
1451 (defcustom org-mhe-search-all-folders nil
1452 "Non-nil means, that the search for the mh-message will be extended to
1453 all folders if the message cannot be found in the folder given in the link.
1454 Searching all folders is very efficient with one of the search engines
1455 supported by MH-E, but will be slow with pick."
1456 :group 'org-link-follow
1457 :type 'boolean)
1459 (defgroup org-remember nil
1460 "Options concerning interaction with remember.el."
1461 :tag "Org Remember"
1462 :group 'org)
1464 (defcustom org-directory "~/org"
1465 "Directory with org files.
1466 This directory will be used as default to prompt for org files.
1467 Used by the hooks for remember.el."
1468 :group 'org-remember
1469 :type 'directory)
1471 (defcustom org-default-notes-file "~/.notes"
1472 "Default target for storing notes.
1473 Used by the hooks for remember.el. This can be a string, or nil to mean
1474 the value of `remember-data-file'.
1475 You can set this on a per-template basis with the variable
1476 `org-remember-templates'."
1477 :group 'org-remember
1478 :type '(choice
1479 (const :tag "Default from remember-data-file" nil)
1480 file))
1482 (defcustom org-remember-store-without-prompt t
1483 "Non-nil means, `C-c C-c' stores remember note without further promts.
1484 In this case, you need `C-u C-c C-c' to get the prompts for
1485 note file and headline.
1486 When this variable is nil, `C-c C-c' give you the prompts, and
1487 `C-u C-c C-c' trigger the fasttrack."
1488 :group 'org-remember
1489 :type 'boolean)
1491 (defcustom org-remember-interactive-interface 'refile
1492 "The interface to be used for interactive filing of remember notes.
1493 This is only used when the interactive mode for selecting a filing
1494 location is used (see the variable `org-remember-store-without-prompt').
1495 Allowed vaues are:
1496 outline The interface shows an outline of the relevant file
1497 and the correct heading is found by moving through
1498 the outline or by searching with incremental search.
1499 outline-path-completion Headlines in the current buffer are offered via
1500 completion.
1501 refile Use the refile interface, and offer headlines,
1502 possibly from different buffers."
1503 :group 'org-remember
1504 :type '(choice
1505 (const :tag "Refile" refile)
1506 (const :tag "Outline" outline)
1507 (const :tag "Outline-path-completion" outline-path-completion)))
1509 (defcustom org-goto-interface 'outline
1510 "The default interface to be used for `org-goto'.
1511 Allowed vaues are:
1512 outline The interface shows an outline of the relevant file
1513 and the correct heading is found by moving through
1514 the outline or by searching with incremental search.
1515 outline-path-completion Headlines in the current buffer are offered via
1516 completion."
1517 :group 'org-remember ; FIXME: different group for org-goto and org-refile
1518 :type '(choice
1519 (const :tag "Outline" outline)
1520 (const :tag "Outline-path-completion" outline-path-completion)))
1522 (defcustom org-remember-default-headline ""
1523 "The headline that should be the default location in the notes file.
1524 When filing remember notes, the cursor will start at that position.
1525 You can set this on a per-template basis with the variable
1526 `org-remember-templates'."
1527 :group 'org-remember
1528 :type 'string)
1530 (defcustom org-remember-templates nil
1531 "Templates for the creation of remember buffers.
1532 When nil, just let remember make the buffer.
1533 When not nil, this is a list of 5-element lists. In each entry, the first
1534 element is the name of the template, which should be a single short word.
1535 The second element is a character, a unique key to select this template.
1536 The third element is the template. The fourth element is optional and can
1537 specify a destination file for remember items created with this template.
1538 The default file is given by `org-default-notes-file'. An optional fifth
1539 element can specify the headline in that file that should be offered
1540 first when the user is asked to file the entry. The default headline is
1541 given in the variable `org-remember-default-headline'.
1543 The template specifies the structure of the remember buffer. It should have
1544 a first line starting with a star, to act as the org-mode headline.
1545 Furthermore, the following %-escapes will be replaced with content:
1547 %^{prompt} Prompt the user for a string and replace this sequence with it.
1548 A default value and a completion table ca be specified like this:
1549 %^{prompt|default|completion2|completion3|...}
1550 %t time stamp, date only
1551 %T time stamp with date and time
1552 %u, %U like the above, but inactive time stamps
1553 %^t like %t, but prompt for date. Similarly %^T, %^u, %^U
1554 You may define a prompt like %^{Please specify birthday}t
1555 %n user name (taken from `user-full-name')
1556 %a annotation, normally the link created with org-store-link
1557 %i initial content, the region active. If %i is indented,
1558 the entire inserted text will be indented as well.
1559 %c content of the clipboard, or current kill ring head
1560 %^g prompt for tags, with completion on tags in target file
1561 %^G prompt for tags, with completion all tags in all agenda files
1562 %:keyword specific information for certain link types, see below
1563 %[pathname] insert the contents of the file given by `pathname'
1564 %(sexp) evaluate elisp `(sexp)' and replace with the result
1565 %! Store this note immediately after filling the template
1567 %? After completing the template, position cursor here.
1569 Apart from these general escapes, you can access information specific to the
1570 link type that is created. For example, calling `remember' in emails or gnus
1571 will record the author and the subject of the message, which you can access
1572 with %:author and %:subject, respectively. Here is a complete list of what
1573 is recorded for each link type.
1575 Link type | Available information
1576 -------------------+------------------------------------------------------
1577 bbdb | %:type %:name %:company
1578 vm, wl, mh, rmail | %:type %:subject %:message-id
1579 | %:from %:fromname %:fromaddress
1580 | %:to %:toname %:toaddress
1581 | %:fromto (either \"to NAME\" or \"from NAME\")
1582 gnus | %:group, for messages also all email fields
1583 w3, w3m | %:type %:url
1584 info | %:type %:file %:node
1585 calendar | %:type %:date"
1586 :group 'org-remember
1587 :get (lambda (var) ; Make sure all entries have 5 elements
1588 (mapcar (lambda (x)
1589 (if (not (stringp (car x))) (setq x (cons "" x)))
1590 (cond ((= (length x) 4) (append x '("")))
1591 ((= (length x) 3) (append x '("" "")))
1592 (t x)))
1593 (default-value var)))
1594 :type '(repeat
1595 :tag "enabled"
1596 (list :value ("" ?a "\n" nil nil)
1597 (string :tag "Name")
1598 (character :tag "Selection Key")
1599 (string :tag "Template")
1600 (choice
1601 (file :tag "Destination file")
1602 (const :tag "Prompt for file" nil))
1603 (choice
1604 (string :tag "Destination headline")
1605 (const :tag "Selection interface for heading")))))
1607 (defcustom org-reverse-note-order nil
1608 "Non-nil means, store new notes at the beginning of a file or entry.
1609 When nil, new notes will be filed to the end of a file or entry.
1610 This can also be a list with cons cells of regular expressions that
1611 are matched against file names, and values."
1612 :group 'org-remember
1613 :type '(choice
1614 (const :tag "Reverse always" t)
1615 (const :tag "Reverse never" nil)
1616 (repeat :tag "By file name regexp"
1617 (cons regexp boolean))))
1619 (defcustom org-refile-targets nil
1620 "Targets for refiling entries with \\[org-refile].
1621 This is list of cons cells. Each cell contains:
1622 - a specification of the files to be considered, either a list of files,
1623 or a symbol whose function or value fields will be used to retrieve
1624 a file name or a list of file names. Nil means, refile to a different
1625 heading in the current buffer.
1626 - A specification of how to find candidate refile targets. This may be
1627 any of
1628 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
1629 This tag has to be present in all target headlines, inheritance will
1630 not be considered.
1631 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
1632 todo keyword.
1633 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1634 headlines that are refiling targets.
1635 - a cons cell (:level . N). Any headline of level N is considered a target.
1636 - a cons cell (:maxlevel . N). Any headline with level <= N is a target."
1637 ;; FIXME: what if there are a var and func with same name???
1638 :group 'org-remember
1639 :type '(repeat
1640 (cons
1641 (choice :value org-agenda-files
1642 (const :tag "All agenda files" org-agenda-files)
1643 (const :tag "Current buffer" nil)
1644 (function) (variable) (file))
1645 (choice :tag "Identify target headline by"
1646 (cons :tag "Specific tag" (const :tag) (string))
1647 (cons :tag "TODO keyword" (const :todo) (string))
1648 (cons :tag "Regular expression" (const :regexp) (regexp))
1649 (cons :tag "Level number" (const :level) (integer))
1650 (cons :tag "Max Level number" (const :maxlevel) (integer))))))
1652 (defcustom org-refile-use-outline-path nil
1653 "Non-nil means, provide refile targets as paths.
1654 So a level 3 headline will be available as level1/level2/level3.
1655 When the value is `file', also include the file name (without directory)
1656 into the path. When `full-file-path', include the full file path."
1657 :group 'org-remember
1658 :type '(choice
1659 (const :tag "Not" nil)
1660 (const :tag "Yes" t)
1661 (const :tag "Start with file name" file)
1662 (const :tag "Start with full file path" full-file-path)))
1664 (defgroup org-todo nil
1665 "Options concerning TODO items in Org-mode."
1666 :tag "Org TODO"
1667 :group 'org)
1669 (defgroup org-progress nil
1670 "Options concerning Progress logging in Org-mode."
1671 :tag "Org Progress"
1672 :group 'org-time)
1674 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
1675 "List of TODO entry keyword sequences and their interpretation.
1676 \\<org-mode-map>This is a list of sequences.
1678 Each sequence starts with a symbol, either `sequence' or `type',
1679 indicating if the keywords should be interpreted as a sequence of
1680 action steps, or as different types of TODO items. The first
1681 keywords are states requiring action - these states will select a headline
1682 for inclusion into the global TODO list Org-mode produces. If one of
1683 the \"keywords\" is the vertical bat \"|\" the remaining keywords
1684 signify that no further action is necessary. If \"|\" is not found,
1685 the last keyword is treated as the only DONE state of the sequence.
1687 The command \\[org-todo] cycles an entry through these states, and one
1688 additional state where no keyword is present. For details about this
1689 cycling, see the manual.
1691 TODO keywords and interpretation can also be set on a per-file basis with
1692 the special #+SEQ_TODO and #+TYP_TODO lines.
1694 Each keyword can optionally specify a character for fast state selection
1695 \(in combination with the variable `org-use-fast-todo-selection')
1696 and specifiers for state change logging, using the same syntax
1697 that is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says
1698 that the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
1699 indicates to record a time stamp each time this state is selected.
1700 \"WAIT(w@)\" says that the user should in addition be prompted for a
1701 note, and \"WAIT(w@/@)\" says that a note should be taken both when
1702 entering and when leaving this state.
1704 For backward compatibility, this variable may also be just a list
1705 of keywords - in this case the interptetation (sequence or type) will be
1706 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
1707 :group 'org-todo
1708 :group 'org-keywords
1709 :type '(choice
1710 (repeat :tag "Old syntax, just keywords"
1711 (string :tag "Keyword"))
1712 (repeat :tag "New syntax"
1713 (cons
1714 (choice
1715 :tag "Interpretation"
1716 (const :tag "Sequence (cycling hits every state)" sequence)
1717 (const :tag "Type (cycling directly to DONE)" type))
1718 (repeat
1719 (string :tag "Keyword"))))))
1721 (defvar org-todo-keywords-1 nil
1722 "All TODO and DONE keywords active in a buffer.")
1723 (make-variable-buffer-local 'org-todo-keywords-1)
1724 (defvar org-todo-keywords-for-agenda nil)
1725 (defvar org-done-keywords-for-agenda nil)
1726 (defvar org-not-done-keywords nil)
1727 (make-variable-buffer-local 'org-not-done-keywords)
1728 (defvar org-done-keywords nil)
1729 (make-variable-buffer-local 'org-done-keywords)
1730 (defvar org-todo-heads nil)
1731 (make-variable-buffer-local 'org-todo-heads)
1732 (defvar org-todo-sets nil)
1733 (make-variable-buffer-local 'org-todo-sets)
1734 (defvar org-todo-log-states nil)
1735 (make-variable-buffer-local 'org-todo-log-states)
1736 (defvar org-todo-kwd-alist nil)
1737 (make-variable-buffer-local 'org-todo-kwd-alist)
1738 (defvar org-todo-key-alist nil)
1739 (make-variable-buffer-local 'org-todo-key-alist)
1740 (defvar org-todo-key-trigger nil)
1741 (make-variable-buffer-local 'org-todo-key-trigger)
1743 (defcustom org-todo-interpretation 'sequence
1744 "Controls how TODO keywords are interpreted.
1745 This variable is in principle obsolete and is only used for
1746 backward compatibility, if the interpretation of todo keywords is
1747 not given already in `org-todo-keywords'. See that variable for
1748 more information."
1749 :group 'org-todo
1750 :group 'org-keywords
1751 :type '(choice (const sequence)
1752 (const type)))
1754 (defcustom org-use-fast-todo-selection 'prefix
1755 "Non-nil means, use the fast todo selection scheme with C-c C-t.
1756 This variable describes if and under what circumstances the cycling
1757 mechanism for TODO keywords will be replaced by a single-key, direct
1758 selection scheme.
1760 When nil, fast selection is never used.
1762 When the symbol `prefix', it will be used when `org-todo' is called with
1763 a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and `C-u t'
1764 in an agenda buffer.
1766 When t, fast selection is used by default. In this case, the prefix
1767 argument forces cycling instead.
1769 In all cases, the special interface is only used if access keys have actually
1770 been assigned by the user, i.e. if keywords in the configuration are followed
1771 by a letter in parenthesis, like TODO(t)."
1772 :group 'org-todo
1773 :type '(choice
1774 (const :tag "Never" nil)
1775 (const :tag "By default" t)
1776 (const :tag "Only with C-u C-c C-t" prefix)))
1778 (defcustom org-after-todo-state-change-hook nil
1779 "Hook which is run after the state of a TODO item was changed.
1780 The new state (a string with a TODO keyword, or nil) is available in the
1781 Lisp variable `state'."
1782 :group 'org-todo
1783 :type 'hook)
1785 (defcustom org-log-done nil
1786 "Non-nil means, record a CLOSED timestamp when moving an entry to DONE.
1787 When equal to the list (done), also prompt for a closing note.
1788 This can also be configured on a per-file basis by adding one of
1789 the following lines anywhere in the buffer:
1791 #+STARTUP: logdone
1792 #+STARTUP: lognotedone
1793 #+STARTUP: nologdone"
1794 :group 'org-todo
1795 :group 'org-progress
1796 :type '(choice
1797 (const :tag "No logging" nil)
1798 (const :tag "Record CLOSED timestamp" time)
1799 (const :tag "Record CLOSED timestamp with closing note." note)))
1801 ;; Normalize old uses of org-log-done.
1802 (cond
1803 ((eq org-log-done t) (setq org-log-done 'time))
1804 ((and (listp org-log-done) (memq 'done org-log-done))
1805 (setq org-log-done 'note)))
1807 ;; FIXME: document
1808 (defcustom org-log-note-clock-out nil
1809 "Non-nil means, recored a note when clocking out of an item.
1810 This can also be configured on a per-file basis by adding one of
1811 the following lines anywhere in the buffer:
1813 #+STARTUP: lognoteclock-out
1814 #+STARTUP: nolognoteclock-out"
1815 :group 'org-todo
1816 :group 'org-progress
1817 :type 'boolean)
1819 (defcustom org-log-done-with-time t
1820 "Non-nil means, the CLOSED time stamp will contain date and time.
1821 When nil, only the date will be recorded."
1822 :group 'org-progress
1823 :type 'boolean)
1825 (defcustom org-log-note-headings
1826 '((done . "CLOSING NOTE %t")
1827 (state . "State %-12s %t")
1828 (clock-out . ""))
1829 "Headings for notes added when clocking out or closing TODO items.
1830 The value is an alist, with the car being a symbol indicating the note
1831 context, and the cdr is the heading to be used. The heading may also be the
1832 empty string.
1833 %t in the heading will be replaced by a time stamp.
1834 %s will be replaced by the new TODO state, in double quotes.
1835 %u will be replaced by the user name.
1836 %U will be replaced by the full user name."
1837 :group 'org-todo
1838 :group 'org-progress
1839 :type '(list :greedy t
1840 (cons (const :tag "Heading when closing an item" done) string)
1841 (cons (const :tag
1842 "Heading when changing todo state (todo sequence only)"
1843 state) string)
1844 (cons (const :tag "Heading when clocking out" clock-out) string)))
1846 (defcustom org-log-states-order-reversed t
1847 "Non-nil means, the latest state change note will be directly after heading.
1848 When nil, the notes will be orderer according to time."
1849 :group 'org-todo
1850 :group 'org-progress
1851 :type 'boolean)
1853 (defcustom org-log-repeat 'time
1854 "Non-nil means, record moving through the DONE state when triggering repeat.
1855 An auto-repeating tasks is immediately switched back to TODO when marked
1856 done. If you are not logging state changes (by adding \"@\" or \"!\" to
1857 the TODO keyword definition, or recording a cloing note by setting
1858 `org-log-done', there will be no record of the task moving trhough DONE.
1859 This variable forces taking a note anyway. Possible values are:
1861 nil Don't force a record
1862 time Record a time stamp
1863 note Record a note
1865 This option can also be set with on a per-file-basis with
1867 #+STARTUP: logrepeat
1868 #+STARTUP: lognoterepeat
1869 #+STARTUP: nologrepeat
1871 You can have local logging settings for a subtree by setting the LOGGING
1872 property to one or more of these keywords."
1873 :group 'org-todo
1874 :group 'org-progress
1875 :type '(choice
1876 (const :tag "Don't force a record" nil)
1877 (const :tag "Force recording the DONE state" time)
1878 (const :tag "Force recording a note with the DONE state" note)))
1880 (defcustom org-clock-into-drawer 2
1881 "Should clocking info be wrapped into a drawer?
1882 When t, clocking info will always be inserted into a :CLOCK: drawer.
1883 If necessary, the drawer will be created.
1884 When nil, the drawer will not be created, but used when present.
1885 When an integer and the number of clocking entries in an item
1886 reaches or exceeds this number, a drawer will be created."
1887 :group 'org-todo
1888 :group 'org-progress
1889 :type '(choice
1890 (const :tag "Always" t)
1891 (const :tag "Only when drawer exists" nil)
1892 (integer :tag "When at least N clock entries")))
1894 (defcustom org-clock-out-when-done t
1895 "When t, the clock will be stopped when the relevant entry is marked DONE.
1896 Nil means, clock will keep running until stopped explicitly with
1897 `C-c C-x C-o', or until the clock is started in a different item."
1898 :group 'org-progress
1899 :type 'boolean)
1901 (defcustom org-clock-in-switch-to-state nil
1902 "Set task to a special todo state while clocking it.
1903 The value should be the state to which the entry should be switched."
1904 :group 'org-progress
1905 :group 'org-todo
1906 :type '(choice
1907 (const :tag "Don't force a state" nil)
1908 (string :tag "State")))
1910 (defgroup org-priorities nil
1911 "Priorities in Org-mode."
1912 :tag "Org Priorities"
1913 :group 'org-todo)
1915 (defcustom org-highest-priority ?A
1916 "The highest priority of TODO items. A character like ?A, ?B etc.
1917 Must have a smaller ASCII number than `org-lowest-priority'."
1918 :group 'org-priorities
1919 :type 'character)
1921 (defcustom org-lowest-priority ?C
1922 "The lowest priority of TODO items. A character like ?A, ?B etc.
1923 Must have a larger ASCII number than `org-highest-priority'."
1924 :group 'org-priorities
1925 :type 'character)
1927 (defcustom org-default-priority ?B
1928 "The default priority of TODO items.
1929 This is the priority an item get if no explicit priority is given."
1930 :group 'org-priorities
1931 :type 'character)
1933 (defcustom org-priority-start-cycle-with-default t
1934 "Non-nil means, start with default priority when starting to cycle.
1935 When this is nil, the first step in the cycle will be (depending on the
1936 command used) one higher or lower that the default priority."
1937 :group 'org-priorities
1938 :type 'boolean)
1940 (defgroup org-time nil
1941 "Options concerning time stamps and deadlines in Org-mode."
1942 :tag "Org Time"
1943 :group 'org)
1945 (defcustom org-insert-labeled-timestamps-at-point nil
1946 "Non-nil means, SCHEDULED and DEADLINE timestamps are inserted at point.
1947 When nil, these labeled time stamps are forces into the second line of an
1948 entry, just after the headline. When scheduling from the global TODO list,
1949 the time stamp will always be forced into the second line."
1950 :group 'org-time
1951 :type 'boolean)
1953 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
1954 "Formats for `format-time-string' which are used for time stamps.
1955 It is not recommended to change this constant.")
1957 (defcustom org-time-stamp-rounding-minutes 0
1958 "Number of minutes to round time stamps to upon insertion.
1959 When zero, insert the time unmodified. Useful rounding numbers
1960 should be factors of 60, so for example 5, 10, 15.
1961 When this is not zero, you can still force an exact time-stamp by using
1962 a double prefix argument to a time-stamp command like `C-c .' or `C-c !'."
1963 :group 'org-time
1964 :type 'integer)
1966 (defcustom org-display-custom-times nil
1967 "Non-nil means, overlay custom formats over all time stamps.
1968 The formats are defined through the variable `org-time-stamp-custom-formats'.
1969 To turn this on on a per-file basis, insert anywhere in the file:
1970 #+STARTUP: customtime"
1971 :group 'org-time
1972 :set 'set-default
1973 :type 'sexp)
1974 (make-variable-buffer-local 'org-display-custom-times)
1976 (defcustom org-time-stamp-custom-formats
1977 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
1978 "Custom formats for time stamps. See `format-time-string' for the syntax.
1979 These are overlayed over the default ISO format if the variable
1980 `org-display-custom-times' is set. Time like %H:%M should be at the
1981 end of the second format."
1982 :group 'org-time
1983 :type 'sexp)
1985 (defun org-time-stamp-format (&optional long inactive)
1986 "Get the right format for a time string."
1987 (let ((f (if long (cdr org-time-stamp-formats)
1988 (car org-time-stamp-formats))))
1989 (if inactive
1990 (concat "[" (substring f 1 -1) "]")
1991 f)))
1993 (defcustom org-read-date-prefer-future t
1994 "Non-nil means, assume future for incomplete date input from user.
1995 This affects the following situations:
1996 1. The user gives a day, but no month.
1997 For example, if today is the 15th, and you enter \"3\", Org-mode will
1998 read this as the third of *next* month. However, if you enter \"17\",
1999 it will be considered as *this* month.
2000 2. The user gives a month but not a year.
2001 For example, if it is april and you enter \"feb 2\", this will be read
2002 as feb 2, *next* year. \"May 5\", however, will be this year.
2004 When this option is nil, the current month and year will always be used
2005 as defaults."
2006 :group 'org-time
2007 :type 'boolean)
2009 (defcustom org-read-date-display-live t
2010 "Non-nil means, display current interpretation of date prompt live.
2011 This display will be in an overlay, in the minibuffer."
2012 :group 'org-time
2013 :type 'boolean)
2015 (defcustom org-read-date-popup-calendar t
2016 "Non-nil means, pop up a calendar when prompting for a date.
2017 In the calendar, the date can be selected with mouse-1. However, the
2018 minibuffer will also be active, and you can simply enter the date as well.
2019 When nil, only the minibuffer will be available."
2020 :group 'org-time
2021 :type 'boolean)
2022 (if (fboundp 'defvaralias)
2023 (defvaralias 'org-popup-calendar-for-date-prompt
2024 'org-read-date-popup-calendar))
2026 (defcustom org-extend-today-until 0
2027 "The hour when your day really ends.
2028 This has influence for the following applications:
2029 - When switching the agenda to \"today\". It it is still earlier than
2030 the time given here, the day recognized as TODAY is actually yesterday.
2031 - When a date is read from the user and it is still before the time given
2032 here, the current date and time will be assumed to be yesterday, 23:59.
2034 FIXME:
2035 IMPORTANT: This is still a very experimental feature, it may disappear
2036 again or it may be extended to mean more things."
2037 :group 'org-time
2038 :type 'number)
2040 (defcustom org-edit-timestamp-down-means-later nil
2041 "Non-nil means, S-down will increase the time in a time stamp.
2042 When nil, S-up will increase."
2043 :group 'org-time
2044 :type 'boolean)
2046 (defcustom org-calendar-follow-timestamp-change t
2047 "Non-nil means, make the calendar window follow timestamp changes.
2048 When a timestamp is modified and the calendar window is visible, it will be
2049 moved to the new date."
2050 :group 'org-time
2051 :type 'boolean)
2053 (defcustom org-clock-heading-function nil
2054 "When non-nil, should be a function to create `org-clock-heading'.
2055 This is the string shown in the mode line when a clock is running.
2056 The function is called with point at the beginning of the headline."
2057 :group 'org-time ; FIXME: Should we have a separate group????
2058 :type 'function)
2060 (defgroup org-tags nil
2061 "Options concerning tags in Org-mode."
2062 :tag "Org Tags"
2063 :group 'org)
2065 (defcustom org-tag-alist nil
2066 "List of tags allowed in Org-mode files.
2067 When this list is nil, Org-mode will base TAG input on what is already in the
2068 buffer.
2069 The value of this variable is an alist, the car of each entry must be a
2070 keyword as a string, the cdr may be a character that is used to select
2071 that tag through the fast-tag-selection interface.
2072 See the manual for details."
2073 :group 'org-tags
2074 :type '(repeat
2075 (choice
2076 (cons (string :tag "Tag name")
2077 (character :tag "Access char"))
2078 (const :tag "Start radio group" (:startgroup))
2079 (const :tag "End radio group" (:endgroup)))))
2081 (defcustom org-use-fast-tag-selection 'auto
2082 "Non-nil means, use fast tag selection scheme.
2083 This is a special interface to select and deselect tags with single keys.
2084 When nil, fast selection is never used.
2085 When the symbol `auto', fast selection is used if and only if selection
2086 characters for tags have been configured, either through the variable
2087 `org-tag-alist' or through a #+TAGS line in the buffer.
2088 When t, fast selection is always used and selection keys are assigned
2089 automatically if necessary."
2090 :group 'org-tags
2091 :type '(choice
2092 (const :tag "Always" t)
2093 (const :tag "Never" nil)
2094 (const :tag "When selection characters are configured" 'auto)))
2096 (defcustom org-fast-tag-selection-single-key nil
2097 "Non-nil means, fast tag selection exits after first change.
2098 When nil, you have to press RET to exit it.
2099 During fast tag selection, you can toggle this flag with `C-c'.
2100 This variable can also have the value `expert'. In this case, the window
2101 displaying the tags menu is not even shown, until you press C-c again."
2102 :group 'org-tags
2103 :type '(choice
2104 (const :tag "No" nil)
2105 (const :tag "Yes" t)
2106 (const :tag "Expert" expert)))
2108 (defvar org-fast-tag-selection-include-todo nil
2109 "Non-nil means, fast tags selection interface will also offer TODO states.
2110 This is an undocumented feature, you should not rely on it.")
2112 (defcustom org-tags-column -80
2113 "The column to which tags should be indented in a headline.
2114 If this number is positive, it specifies the column. If it is negative,
2115 it means that the tags should be flushright to that column. For example,
2116 -80 works well for a normal 80 character screen."
2117 :group 'org-tags
2118 :type 'integer)
2120 (defcustom org-auto-align-tags t
2121 "Non-nil means, realign tags after pro/demotion of TODO state change.
2122 These operations change the length of a headline and therefore shift
2123 the tags around. With this options turned on, after each such operation
2124 the tags are again aligned to `org-tags-column'."
2125 :group 'org-tags
2126 :type 'boolean)
2128 (defcustom org-use-tag-inheritance t
2129 "Non-nil means, tags in levels apply also for sublevels.
2130 When nil, only the tags directly given in a specific line apply there.
2131 If you turn off this option, you very likely want to turn on the
2132 companion option `org-tags-match-list-sublevels'."
2133 :group 'org-tags
2134 :type 'boolean)
2136 (defcustom org-tags-match-list-sublevels nil
2137 "Non-nil means list also sublevels of headlines matching tag search.
2138 Because of tag inheritance (see variable `org-use-tag-inheritance'),
2139 the sublevels of a headline matching a tag search often also match
2140 the same search. Listing all of them can create very long lists.
2141 Setting this variable to nil causes subtrees of a match to be skipped.
2142 This option is off by default, because inheritance in on. If you turn
2143 inheritance off, you very likely want to turn this option on.
2145 As a special case, if the tag search is restricted to TODO items, the
2146 value of this variable is ignored and sublevels are always checked, to
2147 make sure all corresponding TODO items find their way into the list."
2148 :group 'org-tags
2149 :type 'boolean)
2151 (defvar org-tags-history nil
2152 "History of minibuffer reads for tags.")
2153 (defvar org-last-tags-completion-table nil
2154 "The last used completion table for tags.")
2155 (defvar org-after-tags-change-hook nil
2156 "Hook that is run after the tags in a line have changed.")
2158 (defgroup org-properties nil
2159 "Options concerning properties in Org-mode."
2160 :tag "Org Properties"
2161 :group 'org)
2163 (defcustom org-property-format "%-10s %s"
2164 "How property key/value pairs should be formatted by `indent-line'.
2165 When `indent-line' hits a property definition, it will format the line
2166 according to this format, mainly to make sure that the values are
2167 lined-up with respect to each other."
2168 :group 'org-properties
2169 :type 'string)
2171 (defcustom org-use-property-inheritance nil
2172 "Non-nil means, properties apply also for sublevels.
2173 This setting is only relevant during property searches, not when querying
2174 an entry with `org-entry-get'. To retrieve a property with inheritance,
2175 you need to call `org-entry-get' with the inheritance flag.
2176 Turning this on can cause significant overhead when doing a search, so
2177 this is turned off by default.
2178 When nil, only the properties directly given in the current entry count.
2179 The value may also be a list of properties that shouldhave inheritance.
2181 However, note that some special properties use inheritance under special
2182 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
2183 and the properties ending in \"_ALL\" when they are used as descriptor
2184 for valid values of a property."
2185 :group 'org-properties
2186 :type '(choice
2187 (const :tag "Not" nil)
2188 (const :tag "Always" nil)
2189 (repeat :tag "Specific properties" (string :tag "Property"))))
2191 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
2192 "The default column format, if no other format has been defined.
2193 This variable can be set on the per-file basis by inserting a line
2195 #+COLUMNS: %25ITEM ....."
2196 :group 'org-properties
2197 :type 'string)
2199 (defcustom org-global-properties nil
2200 "List of property/value pairs that can be inherited by any entry.
2201 You can set buffer-local values for this by adding lines like
2203 #+PROPERTY: NAME VALUE"
2204 :group 'org-properties
2205 :type '(repeat
2206 (cons (string :tag "Property")
2207 (string :tag "Value"))))
2209 (defvar org-local-properties nil
2210 "List of property/value pairs that can be inherited by any entry.
2211 Valid for the current buffer.
2212 This variable is populated from #+PROPERTY lines.")
2214 (defgroup org-agenda nil
2215 "Options concerning agenda views in Org-mode."
2216 :tag "Org Agenda"
2217 :group 'org)
2219 (defvar org-category nil
2220 "Variable used by org files to set a category for agenda display.
2221 Such files should use a file variable to set it, for example
2223 # -*- mode: org; org-category: \"ELisp\"
2225 or contain a special line
2227 #+CATEGORY: ELisp
2229 If the file does not specify a category, then file's base name
2230 is used instead.")
2231 (make-variable-buffer-local 'org-category)
2233 (defcustom org-agenda-files nil
2234 "The files to be used for agenda display.
2235 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
2236 \\[org-remove-file]. You can also use customize to edit the list.
2238 If an entry is a directory, all files in that directory that are matched by
2239 `org-agenda-file-regexp' will be part of the file list.
2241 If the value of the variable is not a list but a single file name, then
2242 the list of agenda files is actually stored and maintained in that file, one
2243 agenda file per line."
2244 :group 'org-agenda
2245 :type '(choice
2246 (repeat :tag "List of files and directories" file)
2247 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
2249 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
2250 "Regular expression to match files for `org-agenda-files'.
2251 If any element in the list in that variable contains a directory instead
2252 of a normal file, all files in that directory that are matched by this
2253 regular expression will be included."
2254 :group 'org-agenda
2255 :type 'regexp)
2257 (defcustom org-agenda-skip-unavailable-files nil
2258 "t means to just skip non-reachable files in `org-agenda-files'.
2259 Nil means to remove them, after a query, from the list."
2260 :group 'org-agenda
2261 :type 'boolean)
2263 (defcustom org-agenda-text-search-extra-files nil
2264 "List of extra files to be searched by text search commands.
2265 These files will be search in addition to the agenda files bu the
2266 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
2267 Note that these files will only be searched for text search commands,
2268 not for the other agenda views like todo lists, tag earches or the weekly
2269 agenda. This variable is intended to list notes and possibly archive files
2270 that should also be searched by these two commands."
2271 :group 'org-agenda
2272 :type '(repeat file))
2274 (if (fboundp 'defvaralias)
2275 (defvaralias 'org-agenda-multi-occur-extra-files
2276 'org-agenda-text-search-extra-files))
2278 (defcustom org-agenda-confirm-kill 1
2279 "When set, remote killing from the agenda buffer needs confirmation.
2280 When t, a confirmation is always needed. When a number N, confirmation is
2281 only needed when the text to be killed contains more than N non-white lines."
2282 :group 'org-agenda
2283 :type '(choice
2284 (const :tag "Never" nil)
2285 (const :tag "Always" t)
2286 (number :tag "When more than N lines")))
2288 (defcustom org-calendar-to-agenda-key [?c]
2289 "The key to be installed in `calendar-mode-map' for switching to the agenda.
2290 The command `org-calendar-goto-agenda' will be bound to this key. The
2291 default is the character `c' because then `c' can be used to switch back and
2292 forth between agenda and calendar."
2293 :group 'org-agenda
2294 :type 'sexp)
2296 (defcustom org-agenda-compact-blocks nil
2297 "Non-nil means, make the block agenda more compact.
2298 This is done by leaving out unnecessary lines."
2299 :group 'org-agenda
2300 :type nil)
2302 (defgroup org-agenda-export nil
2303 "Options concerning exporting agenda views in Org-mode."
2304 :tag "Org Agenda Export"
2305 :group 'org-agenda)
2307 (defcustom org-agenda-with-colors t
2308 "Non-nil means, use colors in agenda views."
2309 :group 'org-agenda-export
2310 :type 'boolean)
2312 (defcustom org-agenda-exporter-settings nil
2313 "Alist of variable/value pairs that should be active during agenda export.
2314 This is a good place to set uptions for ps-print and for htmlize."
2315 :group 'org-agenda-export
2316 :type '(repeat
2317 (list
2318 (variable)
2319 (sexp :tag "Value"))))
2321 (defcustom org-agenda-export-html-style ""
2322 "The style specification for exported HTML Agenda files.
2323 If this variable contains a string, it will replace the default <style>
2324 section as produced by `htmlize'.
2325 Since there are different ways of setting style information, this variable
2326 needs to contain the full HTML structure to provide a style, including the
2327 surrounding HTML tags. The style specifications should include definitions
2328 the fonts used by the agenda, here is an example:
2330 <style type=\"text/css\">
2331 p { font-weight: normal; color: gray; }
2332 .org-agenda-structure {
2333 font-size: 110%;
2334 color: #003399;
2335 font-weight: 600;
2337 .org-todo {
2338 color: #cc6666;Week-agenda:
2339 font-weight: bold;
2341 .org-done {
2342 color: #339933;
2344 .title { text-align: center; }
2345 .todo, .deadline { color: red; }
2346 .done { color: green; }
2347 </style>
2349 or, if you want to keep the style in a file,
2351 <link rel=\"stylesheet\" type=\"text/css\" href=\"mystyles.css\">
2353 As the value of this option simply gets inserted into the HTML <head> header,
2354 you can \"misuse\" it to also add other text to the header. However,
2355 <style>...</style> is required, if not present the variable will be ignored."
2356 :group 'org-agenda-export
2357 :group 'org-export-html
2358 :type 'string)
2360 (defgroup org-agenda-custom-commands nil
2361 "Options concerning agenda views in Org-mode."
2362 :tag "Org Agenda Custom Commands"
2363 :group 'org-agenda)
2365 (defcustom org-agenda-custom-commands nil
2366 "Custom commands for the agenda.
2367 These commands will be offered on the splash screen displayed by the
2368 agenda dispatcher \\[org-agenda]. Each entry is a list like this:
2370 (key desc type match options files)
2372 key The key (one or more characters as a string) to be associated
2373 with the command.
2374 desc A description of the commend, when omitted or nil, a default
2375 description is built using MATCH.
2376 type The command type, any of the following symbols:
2377 agenda The daily/weekly agenda.
2378 todo Entries with a specific TODO keyword, in all agenda files.
2379 search Entries containing search words entry or headline.
2380 tags Tags/Property/TODO match in all agenda files.
2381 tags-todo Tags/P/T match in all agenda files, TODO entries only.
2382 todo-tree Sparse tree of specific TODO keyword in *current* file.
2383 tags-tree Sparse tree with all tags matches in *current* file.
2384 occur-tree Occur sparse tree for *current* file.
2385 ... A user-defined function.
2386 match What to search for:
2387 - a single keyword for TODO keyword searches
2388 - a tags match expression for tags searches
2389 - a regular expression for occur searches
2390 options A list of option settings, similar to that in a let form, so like
2391 this: ((opt1 val1) (opt2 val2) ...)
2392 files A list of files file to write the produced agenda buffer to
2393 with the command `org-store-agenda-views'.
2394 If a file name ends in \".html\", an HTML version of the buffer
2395 is written out. If it ends in \".ps\", a postscript version is
2396 produced. Otherwide, only the plain text is written to the file.
2398 You can also define a set of commands, to create a composite agenda buffer.
2399 In this case, an entry looks like this:
2401 (key desc (cmd1 cmd2 ...) general-options file)
2403 where
2405 desc A description string to be displayed in the dispatcher menu.
2406 cmd An agenda command, similar to the above. However, tree commands
2407 are no allowed, but instead you can get agenda and global todo list.
2408 So valid commands for a set are:
2409 (agenda)
2410 (alltodo)
2411 (stuck)
2412 (todo \"match\" options files)
2413 (search \"match\" options files)
2414 (tags \"match\" options files)
2415 (tags-todo \"match\" options files)
2417 Each command can carry a list of options, and another set of options can be
2418 given for the whole set of commands. Individual command options take
2419 precedence over the general options.
2421 When using several characters as key to a command, the first characters
2422 are prefix commands. For the dispatcher to display useful information, you
2423 should provide a description for the prefix, like
2425 (setq org-agenda-custom-commands
2426 '((\"h\" . \"HOME + Name tag searches\") ; describe prefix \"h\"
2427 (\"hl\" tags \"+HOME+Lisa\")
2428 (\"hp\" tags \"+HOME+Peter\")
2429 (\"hk\" tags \"+HOME+Kim\")))"
2430 :group 'org-agenda-custom-commands
2431 :type '(repeat
2432 (choice :value ("a" "" tags "" nil)
2433 (list :tag "Single command"
2434 (string :tag "Access Key(s) ")
2435 (option (string :tag "Description"))
2436 (choice
2437 (const :tag "Agenda" agenda)
2438 (const :tag "TODO list" alltodo)
2439 (const :tag "Search words" search)
2440 (const :tag "Stuck projects" stuck)
2441 (const :tag "Tags search (all agenda files)" tags)
2442 (const :tag "Tags search of TODO entries (all agenda files)" tags-todo)
2443 (const :tag "TODO keyword search (all agenda files)" todo)
2444 (const :tag "Tags sparse tree (current buffer)" tags-tree)
2445 (const :tag "TODO keyword tree (current buffer)" todo-tree)
2446 (const :tag "Occur tree (current buffer)" occur-tree)
2447 (sexp :tag "Other, user-defined function"))
2448 (string :tag "Match")
2449 (repeat :tag "Local options"
2450 (list (variable :tag "Option") (sexp :tag "Value")))
2451 (option (repeat :tag "Export" (file :tag "Export to"))))
2452 (list :tag "Command series, all agenda files"
2453 (string :tag "Access Key(s)")
2454 (string :tag "Description ")
2455 (repeat
2456 (choice
2457 (const :tag "Agenda" (agenda))
2458 (const :tag "TODO list" (alltodo))
2459 (list :tag "Search words"
2460 (const :format "" search)
2461 (string :tag "Match")
2462 (repeat :tag "Local options"
2463 (list (variable :tag "Option")
2464 (sexp :tag "Value"))))
2465 (const :tag "Stuck projects" (stuck))
2466 (list :tag "Tags search"
2467 (const :format "" tags)
2468 (string :tag "Match")
2469 (repeat :tag "Local options"
2470 (list (variable :tag "Option")
2471 (sexp :tag "Value"))))
2473 (list :tag "Tags search, TODO entries only"
2474 (const :format "" tags-todo)
2475 (string :tag "Match")
2476 (repeat :tag "Local options"
2477 (list (variable :tag "Option")
2478 (sexp :tag "Value"))))
2480 (list :tag "TODO keyword search"
2481 (const :format "" todo)
2482 (string :tag "Match")
2483 (repeat :tag "Local options"
2484 (list (variable :tag "Option")
2485 (sexp :tag "Value"))))
2487 (list :tag "Other, user-defined function"
2488 (symbol :tag "function")
2489 (string :tag "Match")
2490 (repeat :tag "Local options"
2491 (list (variable :tag "Option")
2492 (sexp :tag "Value"))))))
2494 (repeat :tag "General options"
2495 (list (variable :tag "Option")
2496 (sexp :tag "Value")))
2497 (option (repeat :tag "Export" (file :tag "Export to"))))
2498 (cons :tag "Prefix key documentation"
2499 (string :tag "Access Key(s)")
2500 (string :tag "Description ")))))
2502 (defcustom org-agenda-query-register ?o
2503 "The register holding the current query string.
2504 The prupose of this is that if you construct a query string interactively,
2505 you can then use it to define a custom command."
2506 :group 'org-agenda-custom-commands
2507 :type 'character)
2509 (defcustom org-stuck-projects
2510 '("+LEVEL=2/-DONE" ("TODO" "NEXT" "NEXTACTION") nil "")
2511 "How to identify stuck projects.
2512 This is a list of four items:
2513 1. A tags/todo matcher string that is used to identify a project.
2514 The entire tree below a headline matched by this is considered one project.
2515 2. A list of TODO keywords identifying non-stuck projects.
2516 If the project subtree contains any headline with one of these todo
2517 keywords, the project is considered to be not stuck. If you specify
2518 \"*\" as a keyword, any TODO keyword will mark the project unstuck.
2519 3. A list of tags identifying non-stuck projects.
2520 If the project subtree contains any headline with one of these tags,
2521 the project is considered to be not stuck. If you specify \"*\" as
2522 a tag, any tag will mark the project unstuck.
2523 4. An arbitrary regular expression matching non-stuck projects.
2525 After defining this variable, you may use \\[org-agenda-list-stuck-projects]
2526 or `C-c a #' to produce the list."
2527 :group 'org-agenda-custom-commands
2528 :type '(list
2529 (string :tag "Tags/TODO match to identify a project")
2530 (repeat :tag "Projects are *not* stuck if they have an entry with TODO keyword any of" (string))
2531 (repeat :tag "Projects are *not* stuck if they have an entry with TAG being any of" (string))
2532 (regexp :tag "Projects are *not* stuck if this regexp matches\ninside the subtree")))
2535 (defgroup org-agenda-skip nil
2536 "Options concerning skipping parts of agenda files."
2537 :tag "Org Agenda Skip"
2538 :group 'org-agenda)
2540 (defcustom org-agenda-todo-list-sublevels t
2541 "Non-nil means, check also the sublevels of a TODO entry for TODO entries.
2542 When nil, the sublevels of a TODO entry are not checked, resulting in
2543 potentially much shorter TODO lists."
2544 :group 'org-agenda-skip
2545 :group 'org-todo
2546 :type 'boolean)
2548 (defcustom org-agenda-todo-ignore-with-date nil
2549 "Non-nil means, don't show entries with a date in the global todo list.
2550 You can use this if you prefer to mark mere appointments with a TODO keyword,
2551 but don't want them to show up in the TODO list.
2552 When this is set, it also covers deadlines and scheduled items, the settings
2553 of `org-agenda-todo-ignore-scheduled' and `org-agenda-todo-ignore-deadlines'
2554 will be ignored."
2555 :group 'org-agenda-skip
2556 :group 'org-todo
2557 :type 'boolean)
2559 (defcustom org-agenda-todo-ignore-scheduled nil
2560 "Non-nil means, don't show scheduled entries in the global todo list.
2561 The idea behind this is that by scheduling it, you have already taken care
2562 of this item.
2563 See also `org-agenda-todo-ignore-with-date'."
2564 :group 'org-agenda-skip
2565 :group 'org-todo
2566 :type 'boolean)
2568 (defcustom org-agenda-todo-ignore-deadlines nil
2569 "Non-nil means, don't show near deadline entries in the global todo list.
2570 Near means closer than `org-deadline-warning-days' days.
2571 The idea behind this is that such items will appear in the agenda anyway.
2572 See also `org-agenda-todo-ignore-with-date'."
2573 :group 'org-agenda-skip
2574 :group 'org-todo
2575 :type 'boolean)
2577 (defcustom org-agenda-skip-scheduled-if-done nil
2578 "Non-nil means don't show scheduled items in agenda when they are done.
2579 This is relevant for the daily/weekly agenda, not for the TODO list. And
2580 it applies only to the actual date of the scheduling. Warnings about
2581 an item with a past scheduling dates are always turned off when the item
2582 is DONE."
2583 :group 'org-agenda-skip
2584 :type 'boolean)
2586 (defcustom org-agenda-skip-deadline-if-done nil
2587 "Non-nil means don't show deadines when the corresponding item is done.
2588 When nil, the deadline is still shown and should give you a happy feeling.
2589 This is relevant for the daily/weekly agenda. And it applied only to the
2590 actualy date of the deadline. Warnings about approching and past-due
2591 deadlines are always turned off when the item is DONE."
2592 :group 'org-agenda-skip
2593 :type 'boolean)
2595 (defcustom org-agenda-skip-timestamp-if-done nil
2596 "Non-nil means don't select item by timestamp or -range if it is DONE."
2597 :group 'org-agenda-skip
2598 :type 'boolean)
2600 (defcustom org-timeline-show-empty-dates 3
2601 "Non-nil means, `org-timeline' also shows dates without an entry.
2602 When nil, only the days which actually have entries are shown.
2603 When t, all days between the first and the last date are shown.
2604 When an integer, show also empty dates, but if there is a gap of more than
2605 N days, just insert a special line indicating the size of the gap."
2606 :group 'org-agenda-skip
2607 :type '(choice
2608 (const :tag "None" nil)
2609 (const :tag "All" t)
2610 (number :tag "at most")))
2613 (defgroup org-agenda-startup nil
2614 "Options concerning initial settings in the Agenda in Org Mode."
2615 :tag "Org Agenda Startup"
2616 :group 'org-agenda)
2618 (defcustom org-finalize-agenda-hook nil
2619 "Hook run just before displaying an agenda buffer."
2620 :group 'org-agenda-startup
2621 :type 'hook)
2623 (defcustom org-agenda-mouse-1-follows-link nil
2624 "Non-nil means, mouse-1 on a link will follow the link in the agenda.
2625 A longer mouse click will still set point. Does not work on XEmacs.
2626 Needs to be set before org.el is loaded."
2627 :group 'org-agenda-startup
2628 :type 'boolean)
2630 (defcustom org-agenda-start-with-follow-mode nil
2631 "The initial value of follow-mode in a newly created agenda window."
2632 :group 'org-agenda-startup
2633 :type 'boolean)
2635 (defgroup org-agenda-windows nil
2636 "Options concerning the windows used by the Agenda in Org Mode."
2637 :tag "Org Agenda Windows"
2638 :group 'org-agenda)
2640 (defcustom org-agenda-window-setup 'reorganize-frame
2641 "How the agenda buffer should be displayed.
2642 Possible values for this option are:
2644 current-window Show agenda in the current window, keeping all other windows.
2645 other-frame Use `switch-to-buffer-other-frame' to display agenda.
2646 other-window Use `switch-to-buffer-other-window' to display agenda.
2647 reorganize-frame Show only two windows on the current frame, the current
2648 window and the agenda.
2649 See also the variable `org-agenda-restore-windows-after-quit'."
2650 :group 'org-agenda-windows
2651 :type '(choice
2652 (const current-window)
2653 (const other-frame)
2654 (const other-window)
2655 (const reorganize-frame)))
2657 (defcustom org-agenda-window-frame-fractions '(0.5 . 0.75)
2658 "The min and max height of the agenda window as a fraction of frame height.
2659 The value of the variable is a cons cell with two numbers between 0 and 1.
2660 It only matters if `org-agenda-window-setup' is `reorganize-frame'."
2661 :group 'org-agenda-windows
2662 :type '(cons (number :tag "Minimum") (number :tag "Maximum")))
2664 (defcustom org-agenda-restore-windows-after-quit nil
2665 "Non-nil means, restore window configuration open exiting agenda.
2666 Before the window configuration is changed for displaying the agenda,
2667 the current status is recorded. When the agenda is exited with
2668 `q' or `x' and this option is set, the old state is restored. If
2669 `org-agenda-window-setup' is `other-frame', the value of this
2670 option will be ignored.."
2671 :group 'org-agenda-windows
2672 :type 'boolean)
2674 (defcustom org-indirect-buffer-display 'other-window
2675 "How should indirect tree buffers be displayed?
2676 This applies to indirect buffers created with the commands
2677 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
2678 Valid values are:
2679 current-window Display in the current window
2680 other-window Just display in another window.
2681 dedicated-frame Create one new frame, and re-use it each time.
2682 new-frame Make a new frame each time. Note that in this case
2683 previously-made indirect buffers are kept, and you need to
2684 kill these buffers yourself."
2685 :group 'org-structure
2686 :group 'org-agenda-windows
2687 :type '(choice
2688 (const :tag "In current window" current-window)
2689 (const :tag "In current frame, other window" other-window)
2690 (const :tag "Each time a new frame" new-frame)
2691 (const :tag "One dedicated frame" dedicated-frame)))
2693 (defgroup org-agenda-daily/weekly nil
2694 "Options concerning the daily/weekly agenda."
2695 :tag "Org Agenda Daily/Weekly"
2696 :group 'org-agenda)
2698 (defcustom org-agenda-ndays 7
2699 "Number of days to include in overview display.
2700 Should be 1 or 7."
2701 :group 'org-agenda-daily/weekly
2702 :type 'number)
2704 (defcustom org-agenda-start-on-weekday 1
2705 "Non-nil means, start the overview always on the specified weekday.
2706 0 denotes Sunday, 1 denotes Monday etc.
2707 When nil, always start on the current day."
2708 :group 'org-agenda-daily/weekly
2709 :type '(choice (const :tag "Today" nil)
2710 (number :tag "Weekday No.")))
2712 (defcustom org-agenda-show-all-dates t
2713 "Non-nil means, `org-agenda' shows every day in the selected range.
2714 When nil, only the days which actually have entries are shown."
2715 :group 'org-agenda-daily/weekly
2716 :type 'boolean)
2718 (defcustom org-agenda-format-date 'org-agenda-format-date-aligned
2719 "Format string for displaying dates in the agenda.
2720 Used by the daily/weekly agenda and by the timeline. This should be
2721 a format string understood by `format-time-string', or a function returning
2722 the formatted date as a string. The function must take a single argument,
2723 a calendar-style date list like (month day year)."
2724 :group 'org-agenda-daily/weekly
2725 :type '(choice
2726 (string :tag "Format string")
2727 (function :tag "Function")))
2729 (defun org-agenda-format-date-aligned (date)
2730 "Format a date string for display in the daily/weekly agenda, or timeline.
2731 This function makes sure that dates are aligned for easy reading."
2732 (format "%-9s %2d %s %4d"
2733 (calendar-day-name date)
2734 (extract-calendar-day date)
2735 (calendar-month-name (extract-calendar-month date))
2736 (extract-calendar-year date)))
2738 (defcustom org-agenda-include-diary nil
2739 "If non-nil, include in the agenda entries from the Emacs Calendar's diary."
2740 :group 'org-agenda-daily/weekly
2741 :type 'boolean)
2743 (defcustom org-agenda-include-all-todo nil
2744 "Set means weekly/daily agenda will always contain all TODO entries.
2745 The TODO entries will be listed at the top of the agenda, before
2746 the entries for specific days."
2747 :group 'org-agenda-daily/weekly
2748 :type 'boolean)
2750 (defcustom org-agenda-repeating-timestamp-show-all t
2751 "Non-nil means, show all occurences of a repeating stamp in the agenda.
2752 When nil, only one occurence is shown, either today or the
2753 nearest into the future."
2754 :group 'org-agenda-daily/weekly
2755 :type 'boolean)
2757 (defcustom org-deadline-warning-days 14
2758 "No. of days before expiration during which a deadline becomes active.
2759 This variable governs the display in sparse trees and in the agenda.
2760 When 0 or negative, it means use this number (the absolute value of it)
2761 even if a deadline has a different individual lead time specified."
2762 :group 'org-time
2763 :group 'org-agenda-daily/weekly
2764 :type 'number)
2766 (defcustom org-scheduled-past-days 10000
2767 "No. of days to continue listing scheduled items that are not marked DONE.
2768 When an item is scheduled on a date, it shows up in the agenda on this
2769 day and will be listed until it is marked done for the number of days
2770 given here."
2771 :group 'org-agenda-daily/weekly
2772 :type 'number)
2774 (defgroup org-agenda-time-grid nil
2775 "Options concerning the time grid in the Org-mode Agenda."
2776 :tag "Org Agenda Time Grid"
2777 :group 'org-agenda)
2779 (defcustom org-agenda-use-time-grid t
2780 "Non-nil means, show a time grid in the agenda schedule.
2781 A time grid is a set of lines for specific times (like every two hours between
2782 8:00 and 20:00). The items scheduled for a day at specific times are
2783 sorted in between these lines.
2784 For details about when the grid will be shown, and what it will look like, see
2785 the variable `org-agenda-time-grid'."
2786 :group 'org-agenda-time-grid
2787 :type 'boolean)
2789 (defcustom org-agenda-time-grid
2790 '((daily today require-timed)
2791 "----------------"
2792 (800 1000 1200 1400 1600 1800 2000))
2794 "The settings for time grid for agenda display.
2795 This is a list of three items. The first item is again a list. It contains
2796 symbols specifying conditions when the grid should be displayed:
2798 daily if the agenda shows a single day
2799 weekly if the agenda shows an entire week
2800 today show grid on current date, independent of daily/weekly display
2801 require-timed show grid only if at least one item has a time specification
2803 The second item is a string which will be places behing the grid time.
2805 The third item is a list of integers, indicating the times that should have
2806 a grid line."
2807 :group 'org-agenda-time-grid
2808 :type
2809 '(list
2810 (set :greedy t :tag "Grid Display Options"
2811 (const :tag "Show grid in single day agenda display" daily)
2812 (const :tag "Show grid in weekly agenda display" weekly)
2813 (const :tag "Always show grid for today" today)
2814 (const :tag "Show grid only if any timed entries are present"
2815 require-timed)
2816 (const :tag "Skip grid times already present in an entry"
2817 remove-match))
2818 (string :tag "Grid String")
2819 (repeat :tag "Grid Times" (integer :tag "Time"))))
2821 (defgroup org-agenda-sorting nil
2822 "Options concerning sorting in the Org-mode Agenda."
2823 :tag "Org Agenda Sorting"
2824 :group 'org-agenda)
2826 (defconst org-sorting-choice
2827 '(choice
2828 (const time-up) (const time-down)
2829 (const category-keep) (const category-up) (const category-down)
2830 (const tag-down) (const tag-up)
2831 (const priority-up) (const priority-down))
2832 "Sorting choices.")
2834 (defcustom org-agenda-sorting-strategy
2835 '((agenda time-up category-keep priority-down)
2836 (todo category-keep priority-down)
2837 (tags category-keep priority-down)
2838 (search category-keep))
2839 "Sorting structure for the agenda items of a single day.
2840 This is a list of symbols which will be used in sequence to determine
2841 if an entry should be listed before another entry. The following
2842 symbols are recognized:
2844 time-up Put entries with time-of-day indications first, early first
2845 time-down Put entries with time-of-day indications first, late first
2846 category-keep Keep the default order of categories, corresponding to the
2847 sequence in `org-agenda-files'.
2848 category-up Sort alphabetically by category, A-Z.
2849 category-down Sort alphabetically by category, Z-A.
2850 tag-up Sort alphabetically by last tag, A-Z.
2851 tag-down Sort alphabetically by last tag, Z-A.
2852 priority-up Sort numerically by priority, high priority last.
2853 priority-down Sort numerically by priority, high priority first.
2855 The different possibilities will be tried in sequence, and testing stops
2856 if one comparison returns a \"not-equal\". For example, the default
2857 '(time-up category-keep priority-down)
2858 means: Pull out all entries having a specified time of day and sort them,
2859 in order to make a time schedule for the current day the first thing in the
2860 agenda listing for the day. Of the entries without a time indication, keep
2861 the grouped in categories, don't sort the categories, but keep them in
2862 the sequence given in `org-agenda-files'. Within each category sort by
2863 priority.
2865 Leaving out `category-keep' would mean that items will be sorted across
2866 categories by priority.
2868 Instead of a single list, this can also be a set of list for specific
2869 contents, with a context symbol in the car of the list, any of
2870 `agenda', `todo', `tags' for the corresponding agenda views."
2871 :group 'org-agenda-sorting
2872 :type `(choice
2873 (repeat :tag "General" ,org-sorting-choice)
2874 (list :tag "Individually"
2875 (cons (const :tag "Strategy for Weekly/Daily agenda" agenda)
2876 (repeat ,org-sorting-choice))
2877 (cons (const :tag "Strategy for TODO lists" todo)
2878 (repeat ,org-sorting-choice))
2879 (cons (const :tag "Strategy for Tags matches" tags)
2880 (repeat ,org-sorting-choice)))))
2882 (defcustom org-sort-agenda-notime-is-late t
2883 "Non-nil means, items without time are considered late.
2884 This is only relevant for sorting. When t, items which have no explicit
2885 time like 15:30 will be considered as 99:01, i.e. later than any items which
2886 do have a time. When nil, the default time is before 0:00. You can use this
2887 option to decide if the schedule for today should come before or after timeless
2888 agenda entries."
2889 :group 'org-agenda-sorting
2890 :type 'boolean)
2892 (defgroup org-agenda-line-format nil
2893 "Options concerning the entry prefix in the Org-mode agenda display."
2894 :tag "Org Agenda Line Format"
2895 :group 'org-agenda)
2897 (defcustom org-agenda-prefix-format
2898 '((agenda . " %-12:c%?-12t% s")
2899 (timeline . " % s")
2900 (todo . " %-12:c")
2901 (tags . " %-12:c")
2902 (search . " %-12:c"))
2903 "Format specifications for the prefix of items in the agenda views.
2904 An alist with four entries, for the different agenda types. The keys to the
2905 sublists are `agenda', `timeline', `todo', and `tags'. The values
2906 are format strings.
2907 This format works similar to a printf format, with the following meaning:
2909 %c the category of the item, \"Diary\" for entries from the diary, or
2910 as given by the CATEGORY keyword or derived from the file name.
2911 %T the *last* tag of the item. Last because inherited tags come
2912 first in the list.
2913 %t the time-of-day specification if one applies to the entry, in the
2914 format HH:MM
2915 %s Scheduling/Deadline information, a short string
2917 All specifiers work basically like the standard `%s' of printf, but may
2918 contain two additional characters: A question mark just after the `%' and
2919 a whitespace/punctuation character just before the final letter.
2921 If the first character after `%' is a question mark, the entire field
2922 will only be included if the corresponding value applies to the
2923 current entry. This is useful for fields which should have fixed
2924 width when present, but zero width when absent. For example,
2925 \"%?-12t\" will result in a 12 character time field if a time of the
2926 day is specified, but will completely disappear in entries which do
2927 not contain a time.
2929 If there is punctuation or whitespace character just before the final
2930 format letter, this character will be appended to the field value if
2931 the value is not empty. For example, the format \"%-12:c\" leads to
2932 \"Diary: \" if the category is \"Diary\". If the category were be
2933 empty, no additional colon would be interted.
2935 The default value of this option is \" %-12:c%?-12t% s\", meaning:
2936 - Indent the line with two space characters
2937 - Give the category in a 12 chars wide field, padded with whitespace on
2938 the right (because of `-'). Append a colon if there is a category
2939 (because of `:').
2940 - If there is a time-of-day, put it into a 12 chars wide field. If no
2941 time, don't put in an empty field, just skip it (because of '?').
2942 - Finally, put the scheduling information and append a whitespace.
2944 As another example, if you don't want the time-of-day of entries in
2945 the prefix, you could use:
2947 (setq org-agenda-prefix-format \" %-11:c% s\")
2949 See also the variables `org-agenda-remove-times-when-in-prefix' and
2950 `org-agenda-remove-tags'."
2951 :type '(choice
2952 (string :tag "General format")
2953 (list :greedy t :tag "View dependent"
2954 (cons (const agenda) (string :tag "Format"))
2955 (cons (const timeline) (string :tag "Format"))
2956 (cons (const todo) (string :tag "Format"))
2957 (cons (const tags) (string :tag "Format"))
2958 (cons (const search) (string :tag "Format"))))
2959 :group 'org-agenda-line-format)
2961 (defvar org-prefix-format-compiled nil
2962 "The compiled version of the most recently used prefix format.
2963 See the variable `org-agenda-prefix-format'.")
2965 (defcustom org-agenda-todo-keyword-format "%-1s"
2966 "Format for the TODO keyword in agenda lines.
2967 Set this to something like \"%-12s\" if you want all TODO keywords
2968 to occupy a fixed space in the agenda display."
2969 :group 'org-agenda-line-format
2970 :type 'string)
2972 (defcustom org-agenda-scheduled-leaders '("Scheduled: " "Sched.%2dx: ")
2973 "Text preceeding scheduled items in the agenda view.
2974 This is a list with two strings. The first applies when the item is
2975 scheduled on the current day. The second applies when it has been scheduled
2976 previously, it may contain a %d to capture how many days ago the item was
2977 scheduled."
2978 :group 'org-agenda-line-format
2979 :type '(list
2980 (string :tag "Scheduled today ")
2981 (string :tag "Scheduled previously")))
2983 (defcustom org-agenda-deadline-leaders '("Deadline: " "In %3d d.: ")
2984 "Text preceeding deadline items in the agenda view.
2985 This is a list with two strings. The first applies when the item has its
2986 deadline on the current day. The second applies when it is in the past or
2987 in the future, it may contain %d to capture how many days away the deadline
2988 is (was)."
2989 :group 'org-agenda-line-format
2990 :type '(list
2991 (string :tag "Deadline today ")
2992 (string :tag "Deadline relative")))
2994 (defcustom org-agenda-remove-times-when-in-prefix t
2995 "Non-nil means, remove duplicate time specifications in agenda items.
2996 When the format `org-agenda-prefix-format' contains a `%t' specifier, a
2997 time-of-day specification in a headline or diary entry is extracted and
2998 placed into the prefix. If this option is non-nil, the original specification
2999 \(a timestamp or -range, or just a plain time(range) specification like
3000 11:30-4pm) will be removed for agenda display. This makes the agenda less
3001 cluttered.
3002 The option can be t or nil. It may also be the symbol `beg', indicating
3003 that the time should only be removed what it is located at the beginning of
3004 the headline/diary entry."
3005 :group 'org-agenda-line-format
3006 :type '(choice
3007 (const :tag "Always" t)
3008 (const :tag "Never" nil)
3009 (const :tag "When at beginning of entry" beg)))
3012 (defcustom org-agenda-default-appointment-duration nil
3013 "Default duration for appointments that only have a starting time.
3014 When nil, no duration is specified in such cases.
3015 When non-nil, this must be the number of minutes, e.g. 60 for one hour."
3016 :group 'org-agenda-line-format
3017 :type '(choice
3018 (integer :tag "Minutes")
3019 (const :tag "No default duration")))
3022 (defcustom org-agenda-remove-tags nil
3023 "Non-nil means, remove the tags from the headline copy in the agenda.
3024 When this is the symbol `prefix', only remove tags when
3025 `org-agenda-prefix-format' contains a `%T' specifier."
3026 :group 'org-agenda-line-format
3027 :type '(choice
3028 (const :tag "Always" t)
3029 (const :tag "Never" nil)
3030 (const :tag "When prefix format contains %T" prefix)))
3032 (if (fboundp 'defvaralias)
3033 (defvaralias 'org-agenda-remove-tags-when-in-prefix
3034 'org-agenda-remove-tags))
3036 (defcustom org-agenda-tags-column -80
3037 "Shift tags in agenda items to this column.
3038 If this number is positive, it specifies the column. If it is negative,
3039 it means that the tags should be flushright to that column. For example,
3040 -80 works well for a normal 80 character screen."
3041 :group 'org-agenda-line-format
3042 :type 'integer)
3044 (if (fboundp 'defvaralias)
3045 (defvaralias 'org-agenda-align-tags-to-column 'org-agenda-tags-column))
3047 (defcustom org-agenda-fontify-priorities t
3048 "Non-nil means, highlight low and high priorities in agenda.
3049 When t, the highest priority entries are bold, lowest priority italic.
3050 This may also be an association list of priority faces. The face may be
3051 a names face, or a list like `(:background \"Red\")'."
3052 :group 'org-agenda-line-format
3053 :type '(choice
3054 (const :tag "Never" nil)
3055 (const :tag "Defaults" t)
3056 (repeat :tag "Specify"
3057 (list (character :tag "Priority" :value ?A)
3058 (sexp :tag "face")))))
3060 (defgroup org-latex nil
3061 "Options for embedding LaTeX code into Org-mode"
3062 :tag "Org LaTeX"
3063 :group 'org)
3065 (defcustom org-format-latex-options
3066 '(:foreground default :background default :scale 1.0
3067 :html-foreground "Black" :html-background "Transparent" :html-scale 1.0
3068 :matchers ("begin" "$" "$$" "\\(" "\\["))
3069 "Options for creating images from LaTeX fragments.
3070 This is a property list with the following properties:
3071 :foreground the foreground color for images embedded in emacs, e.g. \"Black\".
3072 `default' means use the forground of the default face.
3073 :background the background color, or \"Transparent\".
3074 `default' means use the background of the default face.
3075 :scale a scaling factor for the size of the images
3076 :html-foreground, :html-background, :html-scale
3077 The same numbers for HTML export.
3078 :matchers a list indicating which matchers should be used to
3079 find LaTeX fragments. Valid members of this list are:
3080 \"begin\" find environments
3081 \"$\" find math expressions surrounded by $...$
3082 \"$$\" find math expressions surrounded by $$....$$
3083 \"\\(\" find math expressions surrounded by \\(...\\)
3084 \"\\ [\" find math expressions surrounded by \\ [...\\]"
3085 :group 'org-latex
3086 :type 'plist)
3088 (defcustom org-format-latex-header "\\documentclass{article}
3089 \\usepackage{fullpage} % do not remove
3090 \\usepackage{amssymb}
3091 \\usepackage[usenames]{color}
3092 \\usepackage{amsmath}
3093 \\usepackage{latexsym}
3094 \\usepackage[mathscr]{eucal}
3095 \\pagestyle{empty} % do not remove"
3096 "The document header used for processing LaTeX fragments."
3097 :group 'org-latex
3098 :type 'string)
3100 (defgroup org-export nil
3101 "Options for exporting org-listings."
3102 :tag "Org Export"
3103 :group 'org)
3105 (defgroup org-export-general nil
3106 "General options for exporting Org-mode files."
3107 :tag "Org Export General"
3108 :group 'org-export)
3110 ;; FIXME
3111 (defvar org-export-publishing-directory nil)
3113 (defcustom org-export-with-special-strings t
3114 "Non-nil means, interpret \"\-\", \"--\" and \"---\" for export.
3115 When this option is turned on, these strings will be exported as:
3117 Org HTML LaTeX
3118 -----+----------+--------
3119 \\- &shy; \\-
3120 -- &ndash; --
3121 --- &mdash; ---
3122 ... &hellip; \ldots
3124 This option can also be set with the +OPTIONS line, e.g. \"-:nil\"."
3125 :group 'org-export-translation
3126 :type 'boolean)
3128 (defcustom org-export-language-setup
3129 '(("en" "Author" "Date" "Table of Contents")
3130 ("cs" "Autor" "Datum" "Obsah")
3131 ("da" "Ophavsmand" "Dato" "Indhold")
3132 ("de" "Autor" "Datum" "Inhaltsverzeichnis")
3133 ("es" "Autor" "Fecha" "\xcdndice")
3134 ("fr" "Auteur" "Date" "Table des mati\xe8res")
3135 ("it" "Autore" "Data" "Indice")
3136 ("nl" "Auteur" "Datum" "Inhoudsopgave")
3137 ("nn" "Forfattar" "Dato" "Innhold") ;; nn = Norsk (nynorsk)
3138 ("sv" "F\xf6rfattarens" "Datum" "Inneh\xe5ll"))
3139 "Terms used in export text, translated to different languages.
3140 Use the variable `org-export-default-language' to set the language,
3141 or use the +OPTION lines for a per-file setting."
3142 :group 'org-export-general
3143 :type '(repeat
3144 (list
3145 (string :tag "HTML language tag")
3146 (string :tag "Author")
3147 (string :tag "Date")
3148 (string :tag "Table of Contents"))))
3150 (defcustom org-export-default-language "en"
3151 "The default language of HTML export, as a string.
3152 This should have an association in `org-export-language-setup'."
3153 :group 'org-export-general
3154 :type 'string)
3156 (defcustom org-export-skip-text-before-1st-heading t
3157 "Non-nil means, skip all text before the first headline when exporting.
3158 When nil, that text is exported as well."
3159 :group 'org-export-general
3160 :type 'boolean)
3162 (defcustom org-export-headline-levels 3
3163 "The last level which is still exported as a headline.
3164 Inferior levels will produce itemize lists when exported.
3165 Note that a numeric prefix argument to an exporter function overrides
3166 this setting.
3168 This option can also be set with the +OPTIONS line, e.g. \"H:2\"."
3169 :group 'org-export-general
3170 :type 'number)
3172 (defcustom org-export-with-section-numbers t
3173 "Non-nil means, add section numbers to headlines when exporting.
3175 This option can also be set with the +OPTIONS line, e.g. \"num:t\"."
3176 :group 'org-export-general
3177 :type 'boolean)
3179 (defcustom org-export-with-toc t
3180 "Non-nil means, create a table of contents in exported files.
3181 The TOC contains headlines with levels up to`org-export-headline-levels'.
3182 When an integer, include levels up to N in the toc, this may then be
3183 different from `org-export-headline-levels', but it will not be allowed
3184 to be larger than the number of headline levels.
3185 When nil, no table of contents is made.
3187 Headlines which contain any TODO items will be marked with \"(*)\" in
3188 ASCII export, and with red color in HTML output, if the option
3189 `org-export-mark-todo-in-toc' is set.
3191 In HTML output, the TOC will be clickable.
3193 This option can also be set with the +OPTIONS line, e.g. \"toc:nil\"
3194 or \"toc:3\"."
3195 :group 'org-export-general
3196 :type '(choice
3197 (const :tag "No Table of Contents" nil)
3198 (const :tag "Full Table of Contents" t)
3199 (integer :tag "TOC to level")))
3201 (defcustom org-export-mark-todo-in-toc nil
3202 "Non-nil means, mark TOC lines that contain any open TODO items."
3203 :group 'org-export-general
3204 :type 'boolean)
3206 (defcustom org-export-preserve-breaks nil
3207 "Non-nil means, preserve all line breaks when exporting.
3208 Normally, in HTML output paragraphs will be reformatted. In ASCII
3209 export, line breaks will always be preserved, regardless of this variable.
3211 This option can also be set with the +OPTIONS line, e.g. \"\\n:t\"."
3212 :group 'org-export-general
3213 :type 'boolean)
3215 (defcustom org-export-with-archived-trees 'headline
3216 "Whether subtrees with the ARCHIVE tag should be exported.
3217 This can have three different values
3218 nil Do not export, pretend this tree is not present
3219 t Do export the entire tree
3220 headline Only export the headline, but skip the tree below it."
3221 :group 'org-export-general
3222 :group 'org-archive
3223 :type '(choice
3224 (const :tag "not at all" nil)
3225 (const :tag "headline only" 'headline)
3226 (const :tag "entirely" t)))
3228 (defcustom org-export-author-info t
3229 "Non-nil means, insert author name and email into the exported file.
3231 This option can also be set with the +OPTIONS line,
3232 e.g. \"author-info:nil\"."
3233 :group 'org-export-general
3234 :type 'boolean)
3236 (defcustom org-export-time-stamp-file t
3237 "Non-nil means, insert a time stamp into the exported file.
3238 The time stamp shows when the file was created.
3240 This option can also be set with the +OPTIONS line,
3241 e.g. \"timestamp:nil\"."
3242 :group 'org-export-general
3243 :type 'boolean)
3245 (defcustom org-export-with-timestamps t
3246 "If nil, do not export time stamps and associated keywords."
3247 :group 'org-export-general
3248 :type 'boolean)
3250 (defcustom org-export-remove-timestamps-from-toc t
3251 "If nil, remove timestamps from the table of contents entries."
3252 :group 'org-export-general
3253 :type 'boolean)
3255 (defcustom org-export-with-tags 'not-in-toc
3256 "If nil, do not export tags, just remove them from headlines.
3257 If this is the symbol `not-in-toc', tags will be removed from table of
3258 contents entries, but still be shown in the headlines of the document.
3260 This option can also be set with the +OPTIONS line, e.g. \"tags:nil\"."
3261 :group 'org-export-general
3262 :type '(choice
3263 (const :tag "Off" nil)
3264 (const :tag "Not in TOC" not-in-toc)
3265 (const :tag "On" t)))
3267 (defcustom org-export-with-drawers nil
3268 "Non-nil means, export with drawers like the property drawer.
3269 When t, all drawers are exported. This may also be a list of
3270 drawer names to export."
3271 :group 'org-export-general
3272 :type '(choice
3273 (const :tag "All drawers" t)
3274 (const :tag "None" nil)
3275 (repeat :tag "Selected drawers"
3276 (string :tag "Drawer name"))))
3278 (defgroup org-export-translation nil
3279 "Options for translating special ascii sequences for the export backends."
3280 :tag "Org Export Translation"
3281 :group 'org-export)
3283 (defcustom org-export-with-emphasize t
3284 "Non-nil means, interpret *word*, /word/, and _word_ as emphasized text.
3285 If the export target supports emphasizing text, the word will be
3286 typeset in bold, italic, or underlined, respectively. Works only for
3287 single words, but you can say: I *really* *mean* *this*.
3288 Not all export backends support this.
3290 This option can also be set with the +OPTIONS line, e.g. \"*:nil\"."
3291 :group 'org-export-translation
3292 :type 'boolean)
3294 (defcustom org-export-with-footnotes t
3295 "If nil, export [1] as a footnote marker.
3296 Lines starting with [1] will be formatted as footnotes.
3298 This option can also be set with the +OPTIONS line, e.g. \"f:nil\"."
3299 :group 'org-export-translation
3300 :type 'boolean)
3302 (defcustom org-export-with-sub-superscripts t
3303 "Non-nil means, interpret \"_\" and \"^\" for export.
3304 When this option is turned on, you can use TeX-like syntax for sub- and
3305 superscripts. Several characters after \"_\" or \"^\" will be
3306 considered as a single item - so grouping with {} is normally not
3307 needed. For example, the following things will be parsed as single
3308 sub- or superscripts.
3310 10^24 or 10^tau several digits will be considered 1 item.
3311 10^-12 or 10^-tau a leading sign with digits or a word
3312 x^2-y^3 will be read as x^2 - y^3, because items are
3313 terminated by almost any nonword/nondigit char.
3314 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
3316 Still, ambiguity is possible - so when in doubt use {} to enclose the
3317 sub/superscript. If you set this variable to the symbol `{}',
3318 the braces are *required* in order to trigger interpretations as
3319 sub/superscript. This can be helpful in documents that need \"_\"
3320 frequently in plain text.
3322 Not all export backends support this, but HTML does.
3324 This option can also be set with the +OPTIONS line, e.g. \"^:nil\"."
3325 :group 'org-export-translation
3326 :type '(choice
3327 (const :tag "Always interpret" t)
3328 (const :tag "Only with braces" {})
3329 (const :tag "Never interpret" nil)))
3331 (defcustom org-export-with-special-strings t
3332 "Non-nil means, interpret \"\-\", \"--\" and \"---\" for export.
3333 When this option is turned on, these strings will be exported as:
3335 \\- : &shy;
3336 -- : &ndash;
3337 --- : &mdash;
3339 Not all export backends support this, but HTML does.
3341 This option can also be set with the +OPTIONS line, e.g. \"-:nil\"."
3342 :group 'org-export-translation
3343 :type 'boolean)
3345 (defcustom org-export-with-TeX-macros t
3346 "Non-nil means, interpret simple TeX-like macros when exporting.
3347 For example, HTML export converts \\alpha to &alpha; and \\AA to &Aring;.
3348 No only real TeX macros will work here, but the standard HTML entities
3349 for math can be used as macro names as well. For a list of supported
3350 names in HTML export, see the constant `org-html-entities'.
3351 Not all export backends support this.
3353 This option can also be set with the +OPTIONS line, e.g. \"TeX:nil\"."
3354 :group 'org-export-translation
3355 :group 'org-export-latex
3356 :type 'boolean)
3358 (defcustom org-export-with-LaTeX-fragments nil
3359 "Non-nil means, convert LaTeX fragments to images when exporting to HTML.
3360 When set, the exporter will find LaTeX environments if the \\begin line is
3361 the first non-white thing on a line. It will also find the math delimiters
3362 like $a=b$ and \\( a=b \\) for inline math, $$a=b$$ and \\[ a=b \\] for
3363 display math.
3365 This option can also be set with the +OPTIONS line, e.g. \"LaTeX:t\"."
3366 :group 'org-export-translation
3367 :group 'org-export-latex
3368 :type 'boolean)
3370 (defcustom org-export-with-fixed-width t
3371 "Non-nil means, lines starting with \":\" will be in fixed width font.
3372 This can be used to have pre-formatted text, fragments of code etc. For
3373 example:
3374 : ;; Some Lisp examples
3375 : (while (defc cnt)
3376 : (ding))
3377 will be looking just like this in also HTML. See also the QUOTE keyword.
3378 Not all export backends support this.
3380 This option can also be set with the +OPTIONS line, e.g. \"::nil\"."
3381 :group 'org-export-translation
3382 :type 'boolean)
3384 (defcustom org-match-sexp-depth 3
3385 "Number of stacked braces for sub/superscript matching.
3386 This has to be set before loading org.el to be effective."
3387 :group 'org-export-translation
3388 :type 'integer)
3390 (defgroup org-export-tables nil
3391 "Options for exporting tables in Org-mode."
3392 :tag "Org Export Tables"
3393 :group 'org-export)
3395 (defcustom org-export-with-tables t
3396 "If non-nil, lines starting with \"|\" define a table.
3397 For example:
3399 | Name | Address | Birthday |
3400 |-------------+----------+-----------|
3401 | Arthur Dent | England | 29.2.2100 |
3403 Not all export backends support this.
3405 This option can also be set with the +OPTIONS line, e.g. \"|:nil\"."
3406 :group 'org-export-tables
3407 :type 'boolean)
3409 (defcustom org-export-highlight-first-table-line t
3410 "Non-nil means, highlight the first table line.
3411 In HTML export, this means use <th> instead of <td>.
3412 In tables created with table.el, this applies to the first table line.
3413 In Org-mode tables, all lines before the first horizontal separator
3414 line will be formatted with <th> tags."
3415 :group 'org-export-tables
3416 :type 'boolean)
3418 (defcustom org-export-table-remove-special-lines t
3419 "Remove special lines and marking characters in calculating tables.
3420 This removes the special marking character column from tables that are set
3421 up for spreadsheet calculations. It also removes the entire lines
3422 marked with `!', `_', or `^'. The lines with `$' are kept, because
3423 the values of constants may be useful to have."
3424 :group 'org-export-tables
3425 :type 'boolean)
3427 (defcustom org-export-prefer-native-exporter-for-tables nil
3428 "Non-nil means, always export tables created with table.el natively.
3429 Natively means, use the HTML code generator in table.el.
3430 When nil, Org-mode's own HTML generator is used when possible (i.e. if
3431 the table does not use row- or column-spanning). This has the
3432 advantage, that the automatic HTML conversions for math symbols and
3433 sub/superscripts can be applied. Org-mode's HTML generator is also
3434 much faster."
3435 :group 'org-export-tables
3436 :type 'boolean)
3438 (defgroup org-export-ascii nil
3439 "Options specific for ASCII export of Org-mode files."
3440 :tag "Org Export ASCII"
3441 :group 'org-export)
3443 (defcustom org-export-ascii-underline '(?\$ ?\# ?^ ?\~ ?\= ?\-)
3444 "Characters for underlining headings in ASCII export.
3445 In the given sequence, these characters will be used for level 1, 2, ..."
3446 :group 'org-export-ascii
3447 :type '(repeat character))
3449 (defcustom org-export-ascii-bullets '(?* ?+ ?-)
3450 "Bullet characters for headlines converted to lists in ASCII export.
3451 The first character is used for the first lest level generated in this
3452 way, and so on. If there are more levels than characters given here,
3453 the list will be repeated.
3454 Note that plain lists will keep the same bullets as the have in the
3455 Org-mode file."
3456 :group 'org-export-ascii
3457 :type '(repeat character))
3459 (defgroup org-export-xml nil
3460 "Options specific for XML export of Org-mode files."
3461 :tag "Org Export XML"
3462 :group 'org-export)
3464 (defgroup org-export-html nil
3465 "Options specific for HTML export of Org-mode files."
3466 :tag "Org Export HTML"
3467 :group 'org-export)
3469 (defcustom org-export-html-coding-system nil
3471 :group 'org-export-html
3472 :type 'coding-system)
3474 (defcustom org-export-html-extension "html"
3475 "The extension for exported HTML files."
3476 :group 'org-export-html
3477 :type 'string)
3479 (defcustom org-export-html-style
3480 "<style type=\"text/css\">
3481 html {
3482 font-family: Times, serif;
3483 font-size: 12pt;
3485 .title { text-align: center; }
3486 .todo { color: red; }
3487 .done { color: green; }
3488 .timestamp { color: grey }
3489 .timestamp-kwd { color: CadetBlue }
3490 .tag { background-color:lightblue; font-weight:normal }
3491 .target { background-color: lavender; }
3492 pre {
3493 border: 1pt solid #AEBDCC;
3494 background-color: #F3F5F7;
3495 padding: 5pt;
3496 font-family: courier, monospace;
3498 table { border-collapse: collapse; }
3499 td, th {
3500 vertical-align: top;
3501 <!--border: 1pt solid #ADB9CC;-->
3503 </style>"
3504 "The default style specification for exported HTML files.
3505 Since there are different ways of setting style information, this variable
3506 needs to contain the full HTML structure to provide a style, including the
3507 surrounding HTML tags. The style specifications should include definitions
3508 for new classes todo, done, title, and deadline. For example, legal values
3509 would be:
3511 <style type=\"text/css\">
3512 p { font-weight: normal; color: gray; }
3513 h1 { color: black; }
3514 .title { text-align: center; }
3515 .todo, .deadline { color: red; }
3516 .done { color: green; }
3517 </style>
3519 or, if you want to keep the style in a file,
3521 <link rel=\"stylesheet\" type=\"text/css\" href=\"mystyles.css\">
3523 As the value of this option simply gets inserted into the HTML <head> header,
3524 you can \"misuse\" it to add arbitrary text to the header."
3525 :group 'org-export-html
3526 :type 'string)
3529 (defcustom org-export-html-title-format "<h1 class=\"title\">%s</h1>\n"
3530 "Format for typesetting the document title in HTML export."
3531 :group 'org-export-html
3532 :type 'string)
3534 (defcustom org-export-html-toplevel-hlevel 2
3535 "The <H> level for level 1 headings in HTML export."
3536 :group 'org-export-html
3537 :type 'string)
3539 (defcustom org-export-html-link-org-files-as-html t
3540 "Non-nil means, make file links to `file.org' point to `file.html'.
3541 When org-mode is exporting an org-mode file to HTML, links to
3542 non-html files are directly put into a href tag in HTML.
3543 However, links to other Org-mode files (recognized by the
3544 extension `.org.) should become links to the corresponding html
3545 file, assuming that the linked org-mode file will also be
3546 converted to HTML.
3547 When nil, the links still point to the plain `.org' file."
3548 :group 'org-export-html
3549 :type 'boolean)
3551 (defcustom org-export-html-inline-images 'maybe
3552 "Non-nil means, inline images into exported HTML pages.
3553 This is done using an <img> tag. When nil, an anchor with href is used to
3554 link to the image. If this option is `maybe', then images in links with
3555 an empty description will be inlined, while images with a description will
3556 be linked only."
3557 :group 'org-export-html
3558 :type '(choice (const :tag "Never" nil)
3559 (const :tag "Always" t)
3560 (const :tag "When there is no description" maybe)))
3562 ;; FIXME: rename
3563 (defcustom org-export-html-expand t
3564 "Non-nil means, for HTML export, treat @<...> as HTML tag.
3565 When nil, these tags will be exported as plain text and therefore
3566 not be interpreted by a browser.
3568 This option can also be set with the +OPTIONS line, e.g. \"@:nil\"."
3569 :group 'org-export-html
3570 :type 'boolean)
3572 (defcustom org-export-html-table-tag
3573 "<table border=\"2\" cellspacing=\"0\" cellpadding=\"6\" rules=\"groups\" frame=\"hsides\">"
3574 "The HTML tag that is used to start a table.
3575 This must be a <table> tag, but you may change the options like
3576 borders and spacing."
3577 :group 'org-export-html
3578 :type 'string)
3580 (defcustom org-export-table-header-tags '("<th>" . "</th>")
3581 "The opening tag for table header fields.
3582 This is customizable so that alignment options can be specified."
3583 :group 'org-export-tables
3584 :type '(cons (string :tag "Opening tag") (string :tag "Closing tag")))
3586 (defcustom org-export-table-data-tags '("<td>" . "</td>")
3587 "The opening tag for table data fields.
3588 This is customizable so that alignment options can be specified."
3589 :group 'org-export-tables
3590 :type '(cons (string :tag "Opening tag") (string :tag "Closing tag")))
3592 (defcustom org-export-html-with-timestamp nil
3593 "If non-nil, write `org-export-html-html-helper-timestamp'
3594 into the exported HTML text. Otherwise, the buffer will just be saved
3595 to a file."
3596 :group 'org-export-html
3597 :type 'boolean)
3599 (defcustom org-export-html-html-helper-timestamp
3600 "<br/><br/><hr><p><!-- hhmts start --> <!-- hhmts end --></p>\n"
3601 "The HTML tag used as timestamp delimiter for HTML-helper-mode."
3602 :group 'org-export-html
3603 :type 'string)
3605 (defgroup org-export-icalendar nil
3606 "Options specific for iCalendar export of Org-mode files."
3607 :tag "Org Export iCalendar"
3608 :group 'org-export)
3610 (defcustom org-combined-agenda-icalendar-file "~/org.ics"
3611 "The file name for the iCalendar file covering all agenda files.
3612 This file is created with the command \\[org-export-icalendar-all-agenda-files].
3613 The file name should be absolute, the file will be overwritten without warning."
3614 :group 'org-export-icalendar
3615 :type 'file)
3617 (defcustom org-icalendar-include-todo nil
3618 "Non-nil means, export to iCalendar files should also cover TODO items."
3619 :group 'org-export-icalendar
3620 :type '(choice
3621 (const :tag "None" nil)
3622 (const :tag "Unfinished" t)
3623 (const :tag "All" all)))
3625 (defcustom org-icalendar-include-sexps t
3626 "Non-nil means, export to iCalendar files should also cover sexp entries.
3627 These are entries like in the diary, but directly in an Org-mode file."
3628 :group 'org-export-icalendar
3629 :type 'boolean)
3631 (defcustom org-icalendar-include-body 100
3632 "Amount of text below headline to be included in iCalendar export.
3633 This is a number of characters that should maximally be included.
3634 Properties, scheduling and clocking lines will always be removed.
3635 The text will be inserted into the DESCRIPTION field."
3636 :group 'org-export-icalendar
3637 :type '(choice
3638 (const :tag "Nothing" nil)
3639 (const :tag "Everything" t)
3640 (integer :tag "Max characters")))
3642 (defcustom org-icalendar-combined-name "OrgMode"
3643 "Calendar name for the combined iCalendar representing all agenda files."
3644 :group 'org-export-icalendar
3645 :type 'string)
3647 (defgroup org-font-lock nil
3648 "Font-lock settings for highlighting in Org-mode."
3649 :tag "Org Font Lock"
3650 :group 'org)
3652 (defcustom org-level-color-stars-only nil
3653 "Non-nil means fontify only the stars in each headline.
3654 When nil, the entire headline is fontified.
3655 Changing it requires restart of `font-lock-mode' to become effective
3656 also in regions already fontified."
3657 :group 'org-font-lock
3658 :type 'boolean)
3660 (defcustom org-hide-leading-stars nil
3661 "Non-nil means, hide the first N-1 stars in a headline.
3662 This works by using the face `org-hide' for these stars. This
3663 face is white for a light background, and black for a dark
3664 background. You may have to customize the face `org-hide' to
3665 make this work.
3666 Changing it requires restart of `font-lock-mode' to become effective
3667 also in regions already fontified.
3668 You may also set this on a per-file basis by adding one of the following
3669 lines to the buffer:
3671 #+STARTUP: hidestars
3672 #+STARTUP: showstars"
3673 :group 'org-font-lock
3674 :type 'boolean)
3676 (defcustom org-fontify-done-headline nil
3677 "Non-nil means, change the face of a headline if it is marked DONE.
3678 Normally, only the TODO/DONE keyword indicates the state of a headline.
3679 When this is non-nil, the headline after the keyword is set to the
3680 `org-headline-done' as an additional indication."
3681 :group 'org-font-lock
3682 :type 'boolean)
3684 (defcustom org-fontify-emphasized-text t
3685 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
3686 Changing this variable requires a restart of Emacs to take effect."
3687 :group 'org-font-lock
3688 :type 'boolean)
3690 (defcustom org-highlight-latex-fragments-and-specials nil
3691 "Non-nil means, fontify what is treated specially by the exporters."
3692 :group 'org-font-lock
3693 :type 'boolean)
3695 (defcustom org-hide-emphasis-markers nil
3696 "Non-nil mean font-lock should hide the emphasis marker characters."
3697 :group 'org-font-lock
3698 :type 'boolean)
3700 (defvar org-emph-re nil
3701 "Regular expression for matching emphasis.")
3702 (defvar org-verbatim-re nil
3703 "Regular expression for matching verbatim text.")
3704 (defvar org-emphasis-regexp-components) ; defined just below
3705 (defvar org-emphasis-alist) ; defined just below
3706 (defun org-set-emph-re (var val)
3707 "Set variable and compute the emphasis regular expression."
3708 (set var val)
3709 (when (and (boundp 'org-emphasis-alist)
3710 (boundp 'org-emphasis-regexp-components)
3711 org-emphasis-alist org-emphasis-regexp-components)
3712 (let* ((e org-emphasis-regexp-components)
3713 (pre (car e))
3714 (post (nth 1 e))
3715 (border (nth 2 e))
3716 (body (nth 3 e))
3717 (nl (nth 4 e))
3718 (stacked (and nil (nth 5 e))) ; stacked is no longer allowed, forced to nil
3719 (body1 (concat body "*?"))
3720 (markers (mapconcat 'car org-emphasis-alist ""))
3721 (vmarkers (mapconcat
3722 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
3723 org-emphasis-alist "")))
3724 ;; make sure special characters appear at the right position in the class
3725 (if (string-match "\\^" markers)
3726 (setq markers (concat (replace-match "" t t markers) "^")))
3727 (if (string-match "-" markers)
3728 (setq markers (concat (replace-match "" t t markers) "-")))
3729 (if (string-match "\\^" vmarkers)
3730 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
3731 (if (string-match "-" vmarkers)
3732 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
3733 (if (> nl 0)
3734 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
3735 (int-to-string nl) "\\}")))
3736 ;; Make the regexp
3737 (setq org-emph-re
3738 (concat "\\([" pre (if (and nil stacked) markers) "]\\|^\\)"
3739 "\\("
3740 "\\([" markers "]\\)"
3741 "\\("
3742 "[^" border "]\\|"
3743 "[^" border (if (and nil stacked) markers) "]"
3744 body1
3745 "[^" border (if (and nil stacked) markers) "]"
3746 "\\)"
3747 "\\3\\)"
3748 "\\([" post (if (and nil stacked) markers) "]\\|$\\)"))
3749 (setq org-verbatim-re
3750 (concat "\\([" pre "]\\|^\\)"
3751 "\\("
3752 "\\([" vmarkers "]\\)"
3753 "\\("
3754 "[^" border "]\\|"
3755 "[^" border "]"
3756 body1
3757 "[^" border "]"
3758 "\\)"
3759 "\\3\\)"
3760 "\\([" post "]\\|$\\)")))))
3762 (defcustom org-emphasis-regexp-components
3763 '(" \t('\"" "- \t.,:?;'\")" " \t\r\n,\"'" "." 1)
3764 "Components used to build the regular expression for emphasis.
3765 This is a list with 6 entries. Terminology: In an emphasis string
3766 like \" *strong word* \", we call the initial space PREMATCH, the final
3767 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
3768 and \"trong wor\" is the body. The different components in this variable
3769 specify what is allowed/forbidden in each part:
3771 pre Chars allowed as prematch. Beginning of line will be allowed too.
3772 post Chars allowed as postmatch. End of line will be allowed too.
3773 border The chars *forbidden* as border characters.
3774 body-regexp A regexp like \".\" to match a body character. Don't use
3775 non-shy groups here, and don't allow newline here.
3776 newline The maximum number of newlines allowed in an emphasis exp.
3778 Use customize to modify this, or restart Emacs after changing it."
3779 :group 'org-font-lock
3780 :set 'org-set-emph-re
3781 :type '(list
3782 (sexp :tag "Allowed chars in pre ")
3783 (sexp :tag "Allowed chars in post ")
3784 (sexp :tag "Forbidden chars in border ")
3785 (sexp :tag "Regexp for body ")
3786 (integer :tag "number of newlines allowed")
3787 (option (boolean :tag "Stacking (DISABLED) "))))
3789 (defcustom org-emphasis-alist
3790 '(("*" bold "<b>" "</b>")
3791 ("/" italic "<i>" "</i>")
3792 ("_" underline "<u>" "</u>")
3793 ("=" org-code "<code>" "</code>" verbatim)
3794 ("~" org-verbatim "" "" verbatim)
3795 ("+" (:strike-through t) "<del>" "</del>")
3797 "Special syntax for emphasized text.
3798 Text starting and ending with a special character will be emphasized, for
3799 example *bold*, _underlined_ and /italic/. This variable sets the marker
3800 characters, the face to be used by font-lock for highlighting in Org-mode
3801 Emacs buffers, and the HTML tags to be used for this.
3802 Use customize to modify this, or restart Emacs after changing it."
3803 :group 'org-font-lock
3804 :set 'org-set-emph-re
3805 :type '(repeat
3806 (list
3807 (string :tag "Marker character")
3808 (choice
3809 (face :tag "Font-lock-face")
3810 (plist :tag "Face property list"))
3811 (string :tag "HTML start tag")
3812 (string :tag "HTML end tag")
3813 (option (const verbatim)))))
3815 ;;; The faces
3817 (defgroup org-faces nil
3818 "Faces in Org-mode."
3819 :tag "Org Faces"
3820 :group 'org-font-lock)
3822 (defun org-compatible-face (inherits specs)
3823 "Make a compatible face specification.
3824 If INHERITS is an existing face and if the Emacs version supports it,
3825 just inherit the face. If not, use SPECS to define the face.
3826 XEmacs and Emacs 21 do not know about the `min-colors' attribute.
3827 For them we convert a (min-colors 8) entry to a `tty' entry and move it
3828 to the top of the list. The `min-colors' attribute will be removed from
3829 any other entries, and any resulting duplicates will be removed entirely."
3830 (cond
3831 ((and inherits (facep inherits)
3832 (not (featurep 'xemacs)) (> emacs-major-version 22))
3833 ;; In Emacs 23, we use inheritance where possible.
3834 ;; We only do this in Emacs 23, because only there the outline
3835 ;; faces have been changed to the original org-mode-level-faces.
3836 (list (list t :inherit inherits)))
3837 ((or (featurep 'xemacs) (< emacs-major-version 22))
3838 ;; These do not understand the `min-colors' attribute.
3839 (let (r e a)
3840 (while (setq e (pop specs))
3841 (cond
3842 ((memq (car e) '(t default)) (push e r))
3843 ((setq a (member '(min-colors 8) (car e)))
3844 (nconc r (list (cons (cons '(type tty) (delq (car a) (car e)))
3845 (cdr e)))))
3846 ((setq a (assq 'min-colors (car e)))
3847 (setq e (cons (delq a (car e)) (cdr e)))
3848 (or (assoc (car e) r) (push e r)))
3849 (t (or (assoc (car e) r) (push e r)))))
3850 (nreverse r)))
3851 (t specs)))
3852 (put 'org-compatible-face 'lisp-indent-function 1)
3854 (defface org-hide
3855 '((((background light)) (:foreground "white"))
3856 (((background dark)) (:foreground "black")))
3857 "Face used to hide leading stars in headlines.
3858 The forground color of this face should be equal to the background
3859 color of the frame."
3860 :group 'org-faces)
3862 (defface org-level-1 ;; font-lock-function-name-face
3863 (org-compatible-face 'outline-1
3864 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
3865 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
3866 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
3867 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
3868 (((class color) (min-colors 8)) (:foreground "blue" :bold t))
3869 (t (:bold t))))
3870 "Face used for level 1 headlines."
3871 :group 'org-faces)
3873 (defface org-level-2 ;; font-lock-variable-name-face
3874 (org-compatible-face 'outline-2
3875 '((((class color) (min-colors 16) (background light)) (:foreground "DarkGoldenrod"))
3876 (((class color) (min-colors 16) (background dark)) (:foreground "LightGoldenrod"))
3877 (((class color) (min-colors 8) (background light)) (:foreground "yellow"))
3878 (((class color) (min-colors 8) (background dark)) (:foreground "yellow" :bold t))
3879 (t (:bold t))))
3880 "Face used for level 2 headlines."
3881 :group 'org-faces)
3883 (defface org-level-3 ;; font-lock-keyword-face
3884 (org-compatible-face 'outline-3
3885 '((((class color) (min-colors 88) (background light)) (:foreground "Purple"))
3886 (((class color) (min-colors 88) (background dark)) (:foreground "Cyan1"))
3887 (((class color) (min-colors 16) (background light)) (:foreground "Purple"))
3888 (((class color) (min-colors 16) (background dark)) (:foreground "Cyan"))
3889 (((class color) (min-colors 8) (background light)) (:foreground "purple" :bold t))
3890 (((class color) (min-colors 8) (background dark)) (:foreground "cyan" :bold t))
3891 (t (:bold t))))
3892 "Face used for level 3 headlines."
3893 :group 'org-faces)
3895 (defface org-level-4 ;; font-lock-comment-face
3896 (org-compatible-face 'outline-4
3897 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
3898 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
3899 (((class color) (min-colors 16) (background light)) (:foreground "red"))
3900 (((class color) (min-colors 16) (background dark)) (:foreground "red1"))
3901 (((class color) (min-colors 8) (background light)) (:foreground "red" :bold t))
3902 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
3903 (t (:bold t))))
3904 "Face used for level 4 headlines."
3905 :group 'org-faces)
3907 (defface org-level-5 ;; font-lock-type-face
3908 (org-compatible-face 'outline-5
3909 '((((class color) (min-colors 16) (background light)) (:foreground "ForestGreen"))
3910 (((class color) (min-colors 16) (background dark)) (:foreground "PaleGreen"))
3911 (((class color) (min-colors 8)) (:foreground "green"))))
3912 "Face used for level 5 headlines."
3913 :group 'org-faces)
3915 (defface org-level-6 ;; font-lock-constant-face
3916 (org-compatible-face 'outline-6
3917 '((((class color) (min-colors 16) (background light)) (:foreground "CadetBlue"))
3918 (((class color) (min-colors 16) (background dark)) (:foreground "Aquamarine"))
3919 (((class color) (min-colors 8)) (:foreground "magenta"))))
3920 "Face used for level 6 headlines."
3921 :group 'org-faces)
3923 (defface org-level-7 ;; font-lock-builtin-face
3924 (org-compatible-face 'outline-7
3925 '((((class color) (min-colors 16) (background light)) (:foreground "Orchid"))
3926 (((class color) (min-colors 16) (background dark)) (:foreground "LightSteelBlue"))
3927 (((class color) (min-colors 8)) (:foreground "blue"))))
3928 "Face used for level 7 headlines."
3929 :group 'org-faces)
3931 (defface org-level-8 ;; font-lock-string-face
3932 (org-compatible-face 'outline-8
3933 '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
3934 (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
3935 (((class color) (min-colors 8)) (:foreground "green"))))
3936 "Face used for level 8 headlines."
3937 :group 'org-faces)
3939 (defface org-special-keyword ;; font-lock-string-face
3940 (org-compatible-face nil
3941 '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
3942 (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
3943 (t (:italic t))))
3944 "Face used for special keywords."
3945 :group 'org-faces)
3947 (defface org-drawer ;; font-lock-function-name-face
3948 (org-compatible-face nil
3949 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
3950 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
3951 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
3952 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
3953 (((class color) (min-colors 8)) (:foreground "blue" :bold t))
3954 (t (:bold t))))
3955 "Face used for drawers."
3956 :group 'org-faces)
3958 (defface org-property-value nil
3959 "Face used for the value of a property."
3960 :group 'org-faces)
3962 (defface org-column
3963 (org-compatible-face nil
3964 '((((class color) (min-colors 16) (background light))
3965 (:background "grey90"))
3966 (((class color) (min-colors 16) (background dark))
3967 (:background "grey30"))
3968 (((class color) (min-colors 8))
3969 (:background "cyan" :foreground "black"))
3970 (t (:inverse-video t))))
3971 "Face for column display of entry properties."
3972 :group 'org-faces)
3974 (when (fboundp 'set-face-attribute)
3975 ;; Make sure that a fixed-width face is used when we have a column table.
3976 (set-face-attribute 'org-column nil
3977 :height (face-attribute 'default :height)
3978 :family (face-attribute 'default :family)))
3980 (defface org-warning
3981 (org-compatible-face 'font-lock-warning-face
3982 '((((class color) (min-colors 16) (background light)) (:foreground "Red1" :bold t))
3983 (((class color) (min-colors 16) (background dark)) (:foreground "Pink" :bold t))
3984 (((class color) (min-colors 8) (background light)) (:foreground "red" :bold t))
3985 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
3986 (t (:bold t))))
3987 "Face for deadlines and TODO keywords."
3988 :group 'org-faces)
3990 (defface org-archived ; similar to shadow
3991 (org-compatible-face 'shadow
3992 '((((class color grayscale) (min-colors 88) (background light))
3993 (:foreground "grey50"))
3994 (((class color grayscale) (min-colors 88) (background dark))
3995 (:foreground "grey70"))
3996 (((class color) (min-colors 8) (background light))
3997 (:foreground "green"))
3998 (((class color) (min-colors 8) (background dark))
3999 (:foreground "yellow"))))
4000 "Face for headline with the ARCHIVE tag."
4001 :group 'org-faces)
4003 (defface org-link
4004 '((((class color) (background light)) (:foreground "Purple" :underline t))
4005 (((class color) (background dark)) (:foreground "Cyan" :underline t))
4006 (t (:underline t)))
4007 "Face for links."
4008 :group 'org-faces)
4010 (defface org-ellipsis
4011 '((((class color) (background light)) (:foreground "DarkGoldenrod" :underline t))
4012 (((class color) (background dark)) (:foreground "LightGoldenrod" :underline t))
4013 (t (:strike-through t)))
4014 "Face for the ellipsis in folded text."
4015 :group 'org-faces)
4017 (defface org-target
4018 '((((class color) (background light)) (:underline t))
4019 (((class color) (background dark)) (:underline t))
4020 (t (:underline t)))
4021 "Face for links."
4022 :group 'org-faces)
4024 (defface org-date
4025 '((((class color) (background light)) (:foreground "Purple" :underline t))
4026 (((class color) (background dark)) (:foreground "Cyan" :underline t))
4027 (t (:underline t)))
4028 "Face for links."
4029 :group 'org-faces)
4031 (defface org-sexp-date
4032 '((((class color) (background light)) (:foreground "Purple"))
4033 (((class color) (background dark)) (:foreground "Cyan"))
4034 (t (:underline t)))
4035 "Face for links."
4036 :group 'org-faces)
4038 (defface org-tag
4039 '((t (:bold t)))
4040 "Face for tags."
4041 :group 'org-faces)
4043 (defface org-todo ; font-lock-warning-face
4044 (org-compatible-face nil
4045 '((((class color) (min-colors 16) (background light)) (:foreground "Red1" :bold t))
4046 (((class color) (min-colors 16) (background dark)) (:foreground "Pink" :bold t))
4047 (((class color) (min-colors 8) (background light)) (:foreground "red" :bold t))
4048 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
4049 (t (:inverse-video t :bold t))))
4050 "Face for TODO keywords."
4051 :group 'org-faces)
4053 (defface org-done ;; font-lock-type-face
4054 (org-compatible-face nil
4055 '((((class color) (min-colors 16) (background light)) (:foreground "ForestGreen" :bold t))
4056 (((class color) (min-colors 16) (background dark)) (:foreground "PaleGreen" :bold t))
4057 (((class color) (min-colors 8)) (:foreground "green"))
4058 (t (:bold t))))
4059 "Face used for todo keywords that indicate DONE items."
4060 :group 'org-faces)
4062 (defface org-headline-done ;; font-lock-string-face
4063 (org-compatible-face nil
4064 '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
4065 (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
4066 (((class color) (min-colors 8) (background light)) (:bold nil))))
4067 "Face used to indicate that a headline is DONE.
4068 This face is only used if `org-fontify-done-headline' is set. If applies
4069 to the part of the headline after the DONE keyword."
4070 :group 'org-faces)
4072 (defcustom org-todo-keyword-faces nil
4073 "Faces for specific TODO keywords.
4074 This is a list of cons cells, with TODO keywords in the car
4075 and faces in the cdr. The face can be a symbol, or a property
4076 list of attributes, like (:foreground \"blue\" :weight bold :underline t)."
4077 :group 'org-faces
4078 :group 'org-todo
4079 :type '(repeat
4080 (cons
4081 (string :tag "keyword")
4082 (sexp :tag "face"))))
4084 (defface org-table ;; font-lock-function-name-face
4085 (org-compatible-face nil
4086 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
4087 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
4088 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
4089 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
4090 (((class color) (min-colors 8) (background light)) (:foreground "blue"))
4091 (((class color) (min-colors 8) (background dark)))))
4092 "Face used for tables."
4093 :group 'org-faces)
4095 (defface org-formula
4096 (org-compatible-face nil
4097 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
4098 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
4099 (((class color) (min-colors 8) (background light)) (:foreground "red"))
4100 (((class color) (min-colors 8) (background dark)) (:foreground "red"))
4101 (t (:bold t :italic t))))
4102 "Face for formulas."
4103 :group 'org-faces)
4105 (defface org-code
4106 (org-compatible-face nil
4107 '((((class color grayscale) (min-colors 88) (background light))
4108 (:foreground "grey50"))
4109 (((class color grayscale) (min-colors 88) (background dark))
4110 (:foreground "grey70"))
4111 (((class color) (min-colors 8) (background light))
4112 (:foreground "green"))
4113 (((class color) (min-colors 8) (background dark))
4114 (:foreground "yellow"))))
4115 "Face for fixed-with text like code snippets."
4116 :group 'org-faces
4117 :version "22.1")
4119 (defface org-verbatim
4120 (org-compatible-face nil
4121 '((((class color grayscale) (min-colors 88) (background light))
4122 (:foreground "grey50" :underline t))
4123 (((class color grayscale) (min-colors 88) (background dark))
4124 (:foreground "grey70" :underline t))
4125 (((class color) (min-colors 8) (background light))
4126 (:foreground "green" :underline t))
4127 (((class color) (min-colors 8) (background dark))
4128 (:foreground "yellow" :underline t))))
4129 "Face for fixed-with text like code snippets."
4130 :group 'org-faces
4131 :version "22.1")
4133 (defface org-agenda-structure ;; font-lock-function-name-face
4134 (org-compatible-face nil
4135 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
4136 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
4137 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
4138 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
4139 (((class color) (min-colors 8)) (:foreground "blue" :bold t))
4140 (t (:bold t))))
4141 "Face used in agenda for captions and dates."
4142 :group 'org-faces)
4144 (defface org-scheduled-today
4145 (org-compatible-face nil
4146 '((((class color) (min-colors 88) (background light)) (:foreground "DarkGreen"))
4147 (((class color) (min-colors 88) (background dark)) (:foreground "PaleGreen"))
4148 (((class color) (min-colors 8)) (:foreground "green"))
4149 (t (:bold t :italic t))))
4150 "Face for items scheduled for a certain day."
4151 :group 'org-faces)
4153 (defface org-scheduled-previously
4154 (org-compatible-face nil
4155 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
4156 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
4157 (((class color) (min-colors 8) (background light)) (:foreground "red"))
4158 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
4159 (t (:bold t))))
4160 "Face for items scheduled previously, and not yet done."
4161 :group 'org-faces)
4163 (defface org-upcoming-deadline
4164 (org-compatible-face nil
4165 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
4166 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
4167 (((class color) (min-colors 8) (background light)) (:foreground "red"))
4168 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
4169 (t (:bold t))))
4170 "Face for items scheduled previously, and not yet done."
4171 :group 'org-faces)
4173 (defcustom org-agenda-deadline-faces
4174 '((1.0 . org-warning)
4175 (0.5 . org-upcoming-deadline)
4176 (0.0 . default))
4177 "Faces for showing deadlines in the agenda.
4178 This is a list of cons cells. The cdr of each cell is a face to be used,
4179 and it can also just be like '(:foreground \"yellow\").
4180 Each car is a fraction of the head-warning time that must have passed for
4181 this the face in the cdr to be used for display. The numbers must be
4182 given in descending order. The head-warning time is normally taken
4183 from `org-deadline-warning-days', but can also be specified in the deadline
4184 timestamp itself, like this:
4186 DEADLINE: <2007-08-13 Mon -8d>
4188 You may use d for days, w for weeks, m for months and y for years. Months
4189 and years will only be treated in an approximate fashion (30.4 days for a
4190 month and 365.24 days for a year)."
4191 :group 'org-faces
4192 :group 'org-agenda-daily/weekly
4193 :type '(repeat
4194 (cons
4195 (number :tag "Fraction of head-warning time passed")
4196 (sexp :tag "Face"))))
4198 ;; FIXME: this is not a good face yet.
4199 (defface org-agenda-restriction-lock
4200 (org-compatible-face nil
4201 '((((class color) (min-colors 88) (background light)) (:background "yellow1"))
4202 (((class color) (min-colors 88) (background dark)) (:background "skyblue4"))
4203 (((class color) (min-colors 16) (background light)) (:background "yellow1"))
4204 (((class color) (min-colors 16) (background dark)) (:background "skyblue4"))
4205 (((class color) (min-colors 8)) (:background "cyan" :foreground "black"))
4206 (t (:inverse-video t))))
4207 "Face for showing the agenda restriction lock."
4208 :group 'org-faces)
4210 (defface org-time-grid ;; font-lock-variable-name-face
4211 (org-compatible-face nil
4212 '((((class color) (min-colors 16) (background light)) (:foreground "DarkGoldenrod"))
4213 (((class color) (min-colors 16) (background dark)) (:foreground "LightGoldenrod"))
4214 (((class color) (min-colors 8)) (:foreground "yellow" :weight light))))
4215 "Face used for time grids."
4216 :group 'org-faces)
4218 (defconst org-level-faces
4219 '(org-level-1 org-level-2 org-level-3 org-level-4
4220 org-level-5 org-level-6 org-level-7 org-level-8
4223 (defcustom org-n-level-faces (length org-level-faces)
4224 "The number of different faces to be used for headlines.
4225 Org-mode defines 8 different headline faces, so this can be at most 8.
4226 If it is less than 8, the level-1 face gets re-used for level N+1 etc."
4227 :type 'number
4228 :group 'org-faces)
4230 ;;; Functions and variables from ther packages
4231 ;; Declared here to avoid compiler warnings
4233 (eval-and-compile
4234 (unless (fboundp 'declare-function)
4235 (defmacro declare-function (fn file &optional arglist fileonly))))
4237 ;; XEmacs only
4238 (defvar outline-mode-menu-heading)
4239 (defvar outline-mode-menu-show)
4240 (defvar outline-mode-menu-hide)
4241 (defvar zmacs-regions) ; XEmacs regions
4243 ;; Emacs only
4244 (defvar mark-active)
4246 ;; Various packages
4247 ;; FIXME: get the argument lists for the UNKNOWN stuff
4248 (declare-function add-to-diary-list "diary-lib"
4249 (date string specifier &optional marker globcolor literal))
4250 (declare-function table--at-cell-p "table" (position &optional object at-column))
4251 (declare-function Info-find-node "info" (filename nodename &optional no-going-back))
4252 (declare-function bbdb "ext:bbdb-com" (string elidep))
4253 (declare-function bbdb-company "ext:bbdb-com" (string elidep))
4254 (declare-function bbdb-current-record "ext:bbdb-com" (&optional planning-on-modifying))
4255 (declare-function bbdb-name "ext:bbdb-com" (string elidep))
4256 (declare-function bbdb-record-getprop "ext:bbdb" (record property))
4257 (declare-function bbdb-record-name "ext:bbdb" (record))
4258 (declare-function bibtex-beginning-of-entry "bibtex" ())
4259 (declare-function bibtex-generate-autokey "bibtex" ())
4260 (declare-function bibtex-parse-entry "bibtex" (&optional content))
4261 (declare-function bibtex-url "bibtex" (&optional pos no-browse))
4262 (defvar calc-embedded-close-formula)
4263 (defvar calc-embedded-open-formula)
4264 (declare-function calendar-astro-date-string "cal-julian" (&optional date))
4265 (declare-function calendar-bahai-date-string "cal-bahai" (&optional date))
4266 (declare-function calendar-check-holidays "holidays" (date))
4267 (declare-function calendar-chinese-date-string "cal-china" (&optional date))
4268 (declare-function calendar-coptic-date-string "cal-coptic" (&optional date))
4269 (declare-function calendar-ethiopic-date-string "cal-coptic" (&optional date))
4270 (declare-function calendar-forward-day "cal-move" (arg))
4271 (declare-function calendar-french-date-string "cal-french" (&optional date))
4272 (declare-function calendar-goto-date "cal-move" (date))
4273 (declare-function calendar-goto-today "cal-move" ())
4274 (declare-function calendar-hebrew-date-string "cal-hebrew" (&optional date))
4275 (declare-function calendar-islamic-date-string "cal-islam" (&optional date))
4276 (declare-function calendar-iso-date-string "cal-iso" (&optional date))
4277 (declare-function calendar-julian-date-string "cal-julian" (&optional date))
4278 (declare-function calendar-mayan-date-string "cal-mayan" (&optional date))
4279 (declare-function calendar-persian-date-string "cal-persia" (&optional date))
4280 (defvar calendar-mode-map)
4281 (defvar original-date) ; dynamically scoped in calendar.el does scope this
4282 (declare-function cdlatex-tab "ext:cdlatex" ())
4283 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
4284 (declare-function elmo-folder-exists-p "ext:elmo" (folder) t)
4285 (declare-function elmo-message-entity-field "ext:elmo-msgdb" (entity field &optional type))
4286 (declare-function elmo-message-field "ext:elmo" (folder number field &optional type) t)
4287 (declare-function elmo-msgdb-overview-get-entity "ext:elmo" (&rest unknown) t)
4288 (defvar font-lock-unfontify-region-function)
4289 (declare-function gnus-article-show-summary "gnus-art" ())
4290 (declare-function gnus-summary-last-subject "gnus-sum" ())
4291 (defvar gnus-other-frame-object)
4292 (defvar gnus-group-name)
4293 (defvar gnus-article-current)
4294 (defvar Info-current-file)
4295 (defvar Info-current-node)
4296 (declare-function mh-display-msg "mh-show" (msg-num folder-name))
4297 (declare-function mh-find-path "mh-utils" ())
4298 (declare-function mh-get-header-field "mh-utils" (field))
4299 (declare-function mh-get-msg-num "mh-utils" (error-if-no-message))
4300 (declare-function mh-header-display "mh-show" ())
4301 (declare-function mh-index-previous-folder "mh-search" ())
4302 (declare-function mh-normalize-folder-name "mh-utils" (folder &optional empty-string-okay dont-remove-trailing-slash return-nil-if-folder-empty))
4303 (declare-function mh-search "mh-search" (folder search-regexp &optional redo-search-flag window-config))
4304 (declare-function mh-search-choose "mh-search" (&optional searcher))
4305 (declare-function mh-show "mh-show" (&optional message redisplay-flag))
4306 (declare-function mh-show-buffer-message-number "mh-comp" (&optional buffer))
4307 (declare-function mh-show-header-display "mh-show" t t)
4308 (declare-function mh-show-msg "mh-show" (msg))
4309 (declare-function mh-show-show "mh-show" t t)
4310 (declare-function mh-visit-folder "mh-folder" (folder &optional range index-data))
4311 (defvar mh-progs)
4312 (defvar mh-current-folder)
4313 (defvar mh-show-folder-buffer)
4314 (defvar mh-index-folder)
4315 (defvar mh-searcher)
4316 (declare-function org-export-latex-cleaned-string "org-export-latex" ())
4317 (declare-function parse-time-string "parse-time" (string))
4318 (declare-function remember "remember" (&optional initial))
4319 (declare-function remember-buffer-desc "remember" ())
4320 (declare-function remember-finalize "remember" ())
4321 (defvar remember-save-after-remembering)
4322 (defvar remember-data-file)
4323 (defvar remember-register)
4324 (defvar remember-buffer)
4325 (defvar remember-handler-functions)
4326 (defvar remember-annotation-functions)
4327 (declare-function rmail-narrow-to-non-pruned-header "rmail" ())
4328 (declare-function rmail-show-message "rmail" (&optional n no-summary))
4329 (declare-function rmail-what-message "rmail" ())
4330 (defvar rmail-current-message)
4331 (defvar texmathp-why)
4332 (declare-function vm-beginning-of-message "ext:vm-page" ())
4333 (declare-function vm-follow-summary-cursor "ext:vm-motion" ())
4334 (declare-function vm-get-header-contents "ext:vm-summary" (message header-name-regexp &optional clump-sep))
4335 (declare-function vm-isearch-narrow "ext:vm-search" ())
4336 (declare-function vm-isearch-update "ext:vm-search" ())
4337 (declare-function vm-select-folder-buffer "ext:vm-macro" ())
4338 (declare-function vm-su-message-id "ext:vm-summary" (m))
4339 (declare-function vm-su-subject "ext:vm-summary" (m))
4340 (declare-function vm-summarize "ext:vm-summary" (&optional display raise))
4341 (defvar vm-message-pointer)
4342 (defvar vm-folder-directory)
4343 (defvar w3m-current-url)
4344 (defvar w3m-current-title)
4345 ;; backward compatibility to old version of wl
4346 (declare-function wl-summary-buffer-msgdb "ext:wl-folder" (&rest unknown) t)
4347 (declare-function wl-folder-get-elmo-folder "ext:wl-folder" (entity &optional no-cache))
4348 (declare-function wl-summary-goto-folder-subr "ext:wl-summary" (&optional name scan-type other-window sticky interactive scoring force-exit))
4349 (declare-function wl-summary-jump-to-msg-by-message-id "ext:wl-summary" (&optional id))
4350 (declare-function wl-summary-line-from "ext:wl-summary" ())
4351 (declare-function wl-summary-line-subject "ext:wl-summary" ())
4352 (declare-function wl-summary-message-number "ext:wl-summary" ())
4353 (declare-function wl-summary-redisplay "ext:wl-summary" (&optional arg))
4354 (defvar wl-summary-buffer-elmo-folder)
4355 (defvar wl-summary-buffer-folder-name)
4356 (declare-function speedbar-line-directory "speedbar" (&optional depth))
4358 (defvar org-latex-regexps)
4359 (defvar constants-unit-system)
4361 ;;; Variables for pre-computed regular expressions, all buffer local
4363 (defvar org-drawer-regexp nil
4364 "Matches first line of a hidden block.")
4365 (make-variable-buffer-local 'org-drawer-regexp)
4366 (defvar org-todo-regexp nil
4367 "Matches any of the TODO state keywords.")
4368 (make-variable-buffer-local 'org-todo-regexp)
4369 (defvar org-not-done-regexp nil
4370 "Matches any of the TODO state keywords except the last one.")
4371 (make-variable-buffer-local 'org-not-done-regexp)
4372 (defvar org-todo-line-regexp nil
4373 "Matches a headline and puts TODO state into group 2 if present.")
4374 (make-variable-buffer-local 'org-todo-line-regexp)
4375 (defvar org-complex-heading-regexp nil
4376 "Matches a headline and puts everything into groups:
4377 group 1: the stars
4378 group 2: The todo keyword, maybe
4379 group 3: Priority cookie
4380 group 4: True headline
4381 group 5: Tags")
4382 (make-variable-buffer-local 'org-complex-heading-regexp)
4383 (defvar org-todo-line-tags-regexp nil
4384 "Matches a headline and puts TODO state into group 2 if present.
4385 Also put tags into group 4 if tags are present.")
4386 (make-variable-buffer-local 'org-todo-line-tags-regexp)
4387 (defvar org-nl-done-regexp nil
4388 "Matches newline followed by a headline with the DONE keyword.")
4389 (make-variable-buffer-local 'org-nl-done-regexp)
4390 (defvar org-looking-at-done-regexp nil
4391 "Matches the DONE keyword a point.")
4392 (make-variable-buffer-local 'org-looking-at-done-regexp)
4393 (defvar org-ds-keyword-length 12
4394 "Maximum length of the Deadline and SCHEDULED keywords.")
4395 (make-variable-buffer-local 'org-ds-keyword-length)
4396 (defvar org-deadline-regexp nil
4397 "Matches the DEADLINE keyword.")
4398 (make-variable-buffer-local 'org-deadline-regexp)
4399 (defvar org-deadline-time-regexp nil
4400 "Matches the DEADLINE keyword together with a time stamp.")
4401 (make-variable-buffer-local 'org-deadline-time-regexp)
4402 (defvar org-deadline-line-regexp nil
4403 "Matches the DEADLINE keyword and the rest of the line.")
4404 (make-variable-buffer-local 'org-deadline-line-regexp)
4405 (defvar org-scheduled-regexp nil
4406 "Matches the SCHEDULED keyword.")
4407 (make-variable-buffer-local 'org-scheduled-regexp)
4408 (defvar org-scheduled-time-regexp nil
4409 "Matches the SCHEDULED keyword together with a time stamp.")
4410 (make-variable-buffer-local 'org-scheduled-time-regexp)
4411 (defvar org-closed-time-regexp nil
4412 "Matches the CLOSED keyword together with a time stamp.")
4413 (make-variable-buffer-local 'org-closed-time-regexp)
4415 (defvar org-keyword-time-regexp nil
4416 "Matches any of the 4 keywords, together with the time stamp.")
4417 (make-variable-buffer-local 'org-keyword-time-regexp)
4418 (defvar org-keyword-time-not-clock-regexp nil
4419 "Matches any of the 3 keywords, together with the time stamp.")
4420 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
4421 (defvar org-maybe-keyword-time-regexp nil
4422 "Matches a timestamp, possibly preceeded by a keyword.")
4423 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
4424 (defvar org-planning-or-clock-line-re nil
4425 "Matches a line with planning or clock info.")
4426 (make-variable-buffer-local 'org-planning-or-clock-line-re)
4428 (defconst org-rm-props '(invisible t face t keymap t intangible t mouse-face t
4429 rear-nonsticky t mouse-map t fontified t)
4430 "Properties to remove when a string without properties is wanted.")
4432 (defsubst org-match-string-no-properties (num &optional string)
4433 (if (featurep 'xemacs)
4434 (let ((s (match-string num string)))
4435 (remove-text-properties 0 (length s) org-rm-props s)
4437 (match-string-no-properties num string)))
4439 (defsubst org-no-properties (s)
4440 (if (fboundp 'set-text-properties)
4441 (set-text-properties 0 (length s) nil s)
4442 (remove-text-properties 0 (length s) org-rm-props s))
4445 (defsubst org-get-alist-option (option key)
4446 (cond ((eq key t) t)
4447 ((eq option t) t)
4448 ((assoc key option) (cdr (assoc key option)))
4449 (t (cdr (assq 'default option)))))
4451 (defsubst org-inhibit-invisibility ()
4452 "Modified `buffer-invisibility-spec' for Emacs 21.
4453 Some ops with invisible text do not work correctly on Emacs 21. For these
4454 we turn off invisibility temporarily. Use this in a `let' form."
4455 (if (< emacs-major-version 22) nil buffer-invisibility-spec))
4457 (defsubst org-set-local (var value)
4458 "Make VAR local in current buffer and set it to VALUE."
4459 (set (make-variable-buffer-local var) value))
4461 (defsubst org-mode-p ()
4462 "Check if the current buffer is in Org-mode."
4463 (eq major-mode 'org-mode))
4465 (defsubst org-last (list)
4466 "Return the last element of LIST."
4467 (car (last list)))
4469 (defun org-let (list &rest body)
4470 (eval (cons 'let (cons list body))))
4471 (put 'org-let 'lisp-indent-function 1)
4473 (defun org-let2 (list1 list2 &rest body)
4474 (eval (cons 'let (cons list1 (list (cons 'let (cons list2 body)))))))
4475 (put 'org-let2 'lisp-indent-function 2)
4476 (defconst org-startup-options
4477 '(("fold" org-startup-folded t)
4478 ("overview" org-startup-folded t)
4479 ("nofold" org-startup-folded nil)
4480 ("showall" org-startup-folded nil)
4481 ("content" org-startup-folded content)
4482 ("hidestars" org-hide-leading-stars t)
4483 ("showstars" org-hide-leading-stars nil)
4484 ("odd" org-odd-levels-only t)
4485 ("oddeven" org-odd-levels-only nil)
4486 ("align" org-startup-align-all-tables t)
4487 ("noalign" org-startup-align-all-tables nil)
4488 ("customtime" org-display-custom-times t)
4489 ("logdone" org-log-done time)
4490 ("lognotedone" org-log-done note)
4491 ("nologdone" org-log-done nil)
4492 ("lognoteclock-out" org-log-note-clock-out t)
4493 ("nolognoteclock-out" org-log-note-clock-out nil)
4494 ("logrepeat" org-log-repeat state)
4495 ("lognoterepeat" org-log-repeat note)
4496 ("nologrepeat" org-log-repeat nil)
4497 ("constcgs" constants-unit-system cgs)
4498 ("constSI" constants-unit-system SI))
4499 "Variable associated with STARTUP options for org-mode.
4500 Each element is a list of three items: The startup options as written
4501 in the #+STARTUP line, the corresponding variable, and the value to
4502 set this variable to if the option is found. An optional forth element PUSH
4503 means to push this value onto the list in the variable.")
4505 (defun org-set-regexps-and-options ()
4506 "Precompute regular expressions for current buffer."
4507 (when (org-mode-p)
4508 (org-set-local 'org-todo-kwd-alist nil)
4509 (org-set-local 'org-todo-key-alist nil)
4510 (org-set-local 'org-todo-key-trigger nil)
4511 (org-set-local 'org-todo-keywords-1 nil)
4512 (org-set-local 'org-done-keywords nil)
4513 (org-set-local 'org-todo-heads nil)
4514 (org-set-local 'org-todo-sets nil)
4515 (org-set-local 'org-todo-log-states nil)
4516 (let ((re (org-make-options-regexp
4517 '("CATEGORY" "SEQ_TODO" "TYP_TODO" "TODO" "COLUMNS"
4518 "STARTUP" "ARCHIVE" "TAGS" "LINK" "PRIORITIES"
4519 "CONSTANTS" "PROPERTY" "DRAWERS")))
4520 (splitre "[ \t]+")
4521 kwds kws0 kwsa key log value cat arch tags const links hw dws
4522 tail sep kws1 prio props drawers)
4523 (save-excursion
4524 (save-restriction
4525 (widen)
4526 (goto-char (point-min))
4527 (while (re-search-forward re nil t)
4528 (setq key (match-string 1) value (org-match-string-no-properties 2))
4529 (cond
4530 ((equal key "CATEGORY")
4531 (if (string-match "[ \t]+$" value)
4532 (setq value (replace-match "" t t value)))
4533 (setq cat value))
4534 ((member key '("SEQ_TODO" "TODO"))
4535 (push (cons 'sequence (org-split-string value splitre)) kwds))
4536 ((equal key "TYP_TODO")
4537 (push (cons 'type (org-split-string value splitre)) kwds))
4538 ((equal key "TAGS")
4539 (setq tags (append tags (org-split-string value splitre))))
4540 ((equal key "COLUMNS")
4541 (org-set-local 'org-columns-default-format value))
4542 ((equal key "LINK")
4543 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
4544 (push (cons (match-string 1 value)
4545 (org-trim (match-string 2 value)))
4546 links)))
4547 ((equal key "PRIORITIES")
4548 (setq prio (org-split-string value " +")))
4549 ((equal key "PROPERTY")
4550 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4551 (push (cons (match-string 1 value) (match-string 2 value))
4552 props)))
4553 ((equal key "DRAWERS")
4554 (setq drawers (org-split-string value splitre)))
4555 ((equal key "CONSTANTS")
4556 (setq const (append const (org-split-string value splitre))))
4557 ((equal key "STARTUP")
4558 (let ((opts (org-split-string value splitre))
4559 l var val)
4560 (while (setq l (pop opts))
4561 (when (setq l (assoc l org-startup-options))
4562 (setq var (nth 1 l) val (nth 2 l))
4563 (if (not (nth 3 l))
4564 (set (make-local-variable var) val)
4565 (if (not (listp (symbol-value var)))
4566 (set (make-local-variable var) nil))
4567 (set (make-local-variable var) (symbol-value var))
4568 (add-to-list var val))))))
4569 ((equal key "ARCHIVE")
4570 (string-match " *$" value)
4571 (setq arch (replace-match "" t t value))
4572 (remove-text-properties 0 (length arch)
4573 '(face t fontified t) arch)))
4575 (when cat
4576 (org-set-local 'org-category (intern cat))
4577 (push (cons "CATEGORY" cat) props))
4578 (when prio
4579 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
4580 (setq prio (mapcar 'string-to-char prio))
4581 (org-set-local 'org-highest-priority (nth 0 prio))
4582 (org-set-local 'org-lowest-priority (nth 1 prio))
4583 (org-set-local 'org-default-priority (nth 2 prio)))
4584 (and props (org-set-local 'org-local-properties (nreverse props)))
4585 (and drawers (org-set-local 'org-drawers drawers))
4586 (and arch (org-set-local 'org-archive-location arch))
4587 (and links (setq org-link-abbrev-alist-local (nreverse links)))
4588 ;; Process the TODO keywords
4589 (unless kwds
4590 ;; Use the global values as if they had been given locally.
4591 (setq kwds (default-value 'org-todo-keywords))
4592 (if (stringp (car kwds))
4593 (setq kwds (list (cons org-todo-interpretation
4594 (default-value 'org-todo-keywords)))))
4595 (setq kwds (reverse kwds)))
4596 (setq kwds (nreverse kwds))
4597 (let (inter kws kw)
4598 (while (setq kws (pop kwds))
4599 (setq inter (pop kws) sep (member "|" kws)
4600 kws0 (delete "|" (copy-sequence kws))
4601 kwsa nil
4602 kws1 (mapcar
4603 (lambda (x)
4604 ;; 1 2
4605 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
4606 (progn
4607 (setq kw (match-string 1 x)
4608 key (and (match-end 2) (match-string 2 x))
4609 log (org-extract-log-state-settings x))
4610 (push (cons kw (and key (string-to-char key))) kwsa)
4611 (and log (push log org-todo-log-states))
4613 (error "Invalid TODO keyword %s" x)))
4614 kws0)
4615 kwsa (if kwsa (append '((:startgroup))
4616 (nreverse kwsa)
4617 '((:endgroup))))
4618 hw (car kws1)
4619 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
4620 tail (list inter hw (car dws) (org-last dws)))
4621 (add-to-list 'org-todo-heads hw 'append)
4622 (push kws1 org-todo-sets)
4623 (setq org-done-keywords (append org-done-keywords dws nil))
4624 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
4625 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
4626 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
4627 (setq org-todo-sets (nreverse org-todo-sets)
4628 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
4629 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
4630 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
4631 ;; Process the constants
4632 (when const
4633 (let (e cst)
4634 (while (setq e (pop const))
4635 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
4636 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
4637 (setq org-table-formula-constants-local cst)))
4639 ;; Process the tags.
4640 (when tags
4641 (let (e tgs)
4642 (while (setq e (pop tags))
4643 (cond
4644 ((equal e "{") (push '(:startgroup) tgs))
4645 ((equal e "}") (push '(:endgroup) tgs))
4646 ((string-match (org-re "^\\([[:alnum:]_@]+\\)(\\(.\\))$") e)
4647 (push (cons (match-string 1 e)
4648 (string-to-char (match-string 2 e)))
4649 tgs))
4650 (t (push (list e) tgs))))
4651 (org-set-local 'org-tag-alist nil)
4652 (while (setq e (pop tgs))
4653 (or (and (stringp (car e))
4654 (assoc (car e) org-tag-alist))
4655 (push e org-tag-alist))))))
4657 ;; Compute the regular expressions and other local variables
4658 (if (not org-done-keywords)
4659 (setq org-done-keywords (list (org-last org-todo-keywords-1))))
4660 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
4661 (length org-scheduled-string)))
4662 org-drawer-regexp
4663 (concat "^[ \t]*:\\("
4664 (mapconcat 'regexp-quote org-drawers "\\|")
4665 "\\):[ \t]*$")
4666 org-not-done-keywords
4667 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
4668 org-todo-regexp
4669 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords-1
4670 "\\|") "\\)\\>")
4671 org-not-done-regexp
4672 (concat "\\<\\("
4673 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
4674 "\\)\\>")
4675 org-todo-line-regexp
4676 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
4677 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4678 "\\)\\>\\)?[ \t]*\\(.*\\)")
4679 org-complex-heading-regexp
4680 (concat "^\\(\\*+\\)\\(?:[ \t]+\\("
4681 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4682 "\\)\\>\\)?\\(?:[ \t]*\\(\\[#.\\]\\)\\)?[ \t]*\\(.*?\\)"
4683 "\\(?:[ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
4684 org-nl-done-regexp
4685 (concat "\n\\*+[ \t]+"
4686 "\\(?:" (mapconcat 'regexp-quote org-done-keywords "\\|")
4687 "\\)" "\\>")
4688 org-todo-line-tags-regexp
4689 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
4690 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4691 (org-re
4692 "\\)\\>\\)? *\\(.*?\\([ \t]:[[:alnum:]:_@]+:[ \t]*\\)?$\\)"))
4693 org-looking-at-done-regexp
4694 (concat "^" "\\(?:"
4695 (mapconcat 'regexp-quote org-done-keywords "\\|") "\\)"
4696 "\\>")
4697 org-deadline-regexp (concat "\\<" org-deadline-string)
4698 org-deadline-time-regexp
4699 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
4700 org-deadline-line-regexp
4701 (concat "\\<\\(" org-deadline-string "\\).*")
4702 org-scheduled-regexp
4703 (concat "\\<" org-scheduled-string)
4704 org-scheduled-time-regexp
4705 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
4706 org-closed-time-regexp
4707 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
4708 org-keyword-time-regexp
4709 (concat "\\<\\(" org-scheduled-string
4710 "\\|" org-deadline-string
4711 "\\|" org-closed-string
4712 "\\|" org-clock-string "\\)"
4713 " *[[<]\\([^]>]+\\)[]>]")
4714 org-keyword-time-not-clock-regexp
4715 (concat "\\<\\(" org-scheduled-string
4716 "\\|" org-deadline-string
4717 "\\|" org-closed-string
4718 "\\)"
4719 " *[[<]\\([^]>]+\\)[]>]")
4720 org-maybe-keyword-time-regexp
4721 (concat "\\(\\<\\(" org-scheduled-string
4722 "\\|" org-deadline-string
4723 "\\|" org-closed-string
4724 "\\|" org-clock-string "\\)\\)?"
4725 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
4726 org-planning-or-clock-line-re
4727 (concat "\\(?:^[ \t]*\\(" org-scheduled-string
4728 "\\|" org-deadline-string
4729 "\\|" org-closed-string "\\|" org-clock-string
4730 "\\)\\>\\)")
4732 (org-compute-latex-and-specials-regexp)
4733 (org-set-font-lock-defaults)))
4735 (defun org-extract-log-state-settings (x)
4736 "Extract the log state setting from a TODO keyword string.
4737 This will extract info from a string like \"WAIT(w@/!)\"."
4738 (let (kw key log1 log2)
4739 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
4740 (setq kw (match-string 1 x)
4741 key (and (match-end 2) (match-string 2 x))
4742 log1 (and (match-end 3) (match-string 3 x))
4743 log2 (and (match-end 4) (match-string 4 x)))
4744 (and (or log1 log2)
4745 (list kw
4746 (and log1 (if (equal log1 "!") 'time 'note))
4747 (and log2 (if (equal log2 "!") 'time 'note)))))))
4749 (defun org-remove-keyword-keys (list)
4750 "Remove a pair of parenthesis at the end of each string in LIST."
4751 (mapcar (lambda (x)
4752 (if (string-match "(.*)$" x)
4753 (substring x 0 (match-beginning 0))
4755 list))
4757 ;; FIXME: this could be done much better, using second characters etc.
4758 (defun org-assign-fast-keys (alist)
4759 "Assign fast keys to a keyword-key alist.
4760 Respect keys that are already there."
4761 (let (new e k c c1 c2 (char ?a))
4762 (while (setq e (pop alist))
4763 (cond
4764 ((equal e '(:startgroup)) (push e new))
4765 ((equal e '(:endgroup)) (push e new))
4767 (setq k (car e) c2 nil)
4768 (if (cdr e)
4769 (setq c (cdr e))
4770 ;; automatically assign a character.
4771 (setq c1 (string-to-char
4772 (downcase (substring
4773 k (if (= (string-to-char k) ?@) 1 0)))))
4774 (if (or (rassoc c1 new) (rassoc c1 alist))
4775 (while (or (rassoc char new) (rassoc char alist))
4776 (setq char (1+ char)))
4777 (setq c2 c1))
4778 (setq c (or c2 char)))
4779 (push (cons k c) new))))
4780 (nreverse new)))
4782 ;;; Some variables ujsed in various places
4784 (defvar org-window-configuration nil
4785 "Used in various places to store a window configuration.")
4786 (defvar org-finish-function nil
4787 "Function to be called when `C-c C-c' is used.
4788 This is for getting out of special buffers like remember.")
4791 ;; FIXME: Occasionally check by commenting these, to make sure
4792 ;; no other functions uses these, forgetting to let-bind them.
4793 (defvar entry)
4794 (defvar state)
4795 (defvar last-state)
4796 (defvar date)
4797 (defvar description)
4799 ;; Defined somewhere in this file, but used before definition.
4800 (defvar orgtbl-mode-menu) ; defined when orgtbl mode get initialized
4801 (defvar org-agenda-buffer-name)
4802 (defvar org-agenda-undo-list)
4803 (defvar org-agenda-pending-undo-list)
4804 (defvar org-agenda-overriding-header)
4805 (defvar orgtbl-mode)
4806 (defvar org-html-entities)
4807 (defvar org-struct-menu)
4808 (defvar org-org-menu)
4809 (defvar org-tbl-menu)
4810 (defvar org-agenda-keymap)
4812 ;;;; Emacs/XEmacs compatibility
4814 ;; Overlay compatibility functions
4815 (defun org-make-overlay (beg end &optional buffer)
4816 (if (featurep 'xemacs)
4817 (make-extent beg end buffer)
4818 (make-overlay beg end buffer)))
4819 (defun org-delete-overlay (ovl)
4820 (if (featurep 'xemacs) (delete-extent ovl) (delete-overlay ovl)))
4821 (defun org-detach-overlay (ovl)
4822 (if (featurep 'xemacs) (detach-extent ovl) (delete-overlay ovl)))
4823 (defun org-move-overlay (ovl beg end &optional buffer)
4824 (if (featurep 'xemacs)
4825 (set-extent-endpoints ovl beg end (or buffer (current-buffer)))
4826 (move-overlay ovl beg end buffer)))
4827 (defun org-overlay-put (ovl prop value)
4828 (if (featurep 'xemacs)
4829 (set-extent-property ovl prop value)
4830 (overlay-put ovl prop value)))
4831 (defun org-overlay-display (ovl text &optional face evap)
4832 "Make overlay OVL display TEXT with face FACE."
4833 (if (featurep 'xemacs)
4834 (let ((gl (make-glyph text)))
4835 (and face (set-glyph-face gl face))
4836 (set-extent-property ovl 'invisible t)
4837 (set-extent-property ovl 'end-glyph gl))
4838 (overlay-put ovl 'display text)
4839 (if face (overlay-put ovl 'face face))
4840 (if evap (overlay-put ovl 'evaporate t))))
4841 (defun org-overlay-before-string (ovl text &optional face evap)
4842 "Make overlay OVL display TEXT with face FACE."
4843 (if (featurep 'xemacs)
4844 (let ((gl (make-glyph text)))
4845 (and face (set-glyph-face gl face))
4846 (set-extent-property ovl 'begin-glyph gl))
4847 (if face (org-add-props text nil 'face face))
4848 (overlay-put ovl 'before-string text)
4849 (if evap (overlay-put ovl 'evaporate t))))
4850 (defun org-overlay-get (ovl prop)
4851 (if (featurep 'xemacs)
4852 (extent-property ovl prop)
4853 (overlay-get ovl prop)))
4854 (defun org-overlays-at (pos)
4855 (if (featurep 'xemacs) (extents-at pos) (overlays-at pos)))
4856 (defun org-overlays-in (&optional start end)
4857 (if (featurep 'xemacs)
4858 (extent-list nil start end)
4859 (overlays-in start end)))
4860 (defun org-overlay-start (o)
4861 (if (featurep 'xemacs) (extent-start-position o) (overlay-start o)))
4862 (defun org-overlay-end (o)
4863 (if (featurep 'xemacs) (extent-end-position o) (overlay-end o)))
4864 (defun org-find-overlays (prop &optional pos delete)
4865 "Find all overlays specifying PROP at POS or point.
4866 If DELETE is non-nil, delete all those overlays."
4867 (let ((overlays (org-overlays-at (or pos (point))))
4868 ov found)
4869 (while (setq ov (pop overlays))
4870 (if (org-overlay-get ov prop)
4871 (if delete (org-delete-overlay ov) (push ov found))))
4872 found))
4874 ;; Region compatibility
4876 (defun org-add-hook (hook function &optional append local)
4877 "Add-hook, compatible with both Emacsen."
4878 (if (and local (featurep 'xemacs))
4879 (add-local-hook hook function append)
4880 (add-hook hook function append local)))
4882 (defvar org-ignore-region nil
4883 "To temporarily disable the active region.")
4885 (defun org-region-active-p ()
4886 "Is `transient-mark-mode' on and the region active?
4887 Works on both Emacs and XEmacs."
4888 (if org-ignore-region
4890 (if (featurep 'xemacs)
4891 (and zmacs-regions (region-active-p))
4892 (if (fboundp 'use-region-p)
4893 (use-region-p)
4894 (and transient-mark-mode mark-active))))) ; Emacs 22 and before
4896 ;; Invisibility compatibility
4898 (defun org-add-to-invisibility-spec (arg)
4899 "Add elements to `buffer-invisibility-spec'.
4900 See documentation for `buffer-invisibility-spec' for the kind of elements
4901 that can be added."
4902 (cond
4903 ((fboundp 'add-to-invisibility-spec)
4904 (add-to-invisibility-spec arg))
4905 ((or (null buffer-invisibility-spec) (eq buffer-invisibility-spec t))
4906 (setq buffer-invisibility-spec (list arg)))
4908 (setq buffer-invisibility-spec
4909 (cons arg buffer-invisibility-spec)))))
4911 (defun org-remove-from-invisibility-spec (arg)
4912 "Remove elements from `buffer-invisibility-spec'."
4913 (if (fboundp 'remove-from-invisibility-spec)
4914 (remove-from-invisibility-spec arg)
4915 (if (consp buffer-invisibility-spec)
4916 (setq buffer-invisibility-spec
4917 (delete arg buffer-invisibility-spec)))))
4919 (defun org-in-invisibility-spec-p (arg)
4920 "Is ARG a member of `buffer-invisibility-spec'?"
4921 (if (consp buffer-invisibility-spec)
4922 (member arg buffer-invisibility-spec)
4923 nil))
4925 ;;;; Define the Org-mode
4927 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
4928 (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."))
4931 ;; We use a before-change function to check if a table might need
4932 ;; an update.
4933 (defvar org-table-may-need-update t
4934 "Indicates that a table might need an update.
4935 This variable is set by `org-before-change-function'.
4936 `org-table-align' sets it back to nil.")
4937 (defvar org-mode-map)
4938 (defvar org-mode-hook nil)
4939 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4940 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
4941 (defvar org-table-buffer-is-an nil)
4942 (defconst org-outline-regexp "\\*+ ")
4944 ;;;###autoload
4945 (define-derived-mode org-mode outline-mode "Org"
4946 "Outline-based notes management and organizer, alias
4947 \"Carsten's outline-mode for keeping track of everything.\"
4949 Org-mode develops organizational tasks around a NOTES file which
4950 contains information about projects as plain text. Org-mode is
4951 implemented on top of outline-mode, which is ideal to keep the content
4952 of large files well structured. It supports ToDo items, deadlines and
4953 time stamps, which magically appear in the diary listing of the Emacs
4954 calendar. Tables are easily created with a built-in table editor.
4955 Plain text URL-like links connect to websites, emails (VM), Usenet
4956 messages (Gnus), BBDB entries, and any files related to the project.
4957 For printing and sharing of notes, an Org-mode file (or a part of it)
4958 can be exported as a structured ASCII or HTML file.
4960 The following commands are available:
4962 \\{org-mode-map}"
4964 ;; Get rid of Outline menus, they are not needed
4965 ;; Need to do this here because define-derived-mode sets up
4966 ;; the keymap so late. Still, it is a waste to call this each time
4967 ;; we switch another buffer into org-mode.
4968 (if (featurep 'xemacs)
4969 (when (boundp 'outline-mode-menu-heading)
4970 ;; Assume this is Greg's port, it used easymenu
4971 (easy-menu-remove outline-mode-menu-heading)
4972 (easy-menu-remove outline-mode-menu-show)
4973 (easy-menu-remove outline-mode-menu-hide))
4974 (define-key org-mode-map [menu-bar headings] 'undefined)
4975 (define-key org-mode-map [menu-bar hide] 'undefined)
4976 (define-key org-mode-map [menu-bar show] 'undefined))
4978 (easy-menu-add org-org-menu)
4979 (easy-menu-add org-tbl-menu)
4980 (org-install-agenda-files-menu)
4981 (if org-descriptive-links (org-add-to-invisibility-spec '(org-link)))
4982 (org-add-to-invisibility-spec '(org-cwidth))
4983 (when (featurep 'xemacs)
4984 (org-set-local 'line-move-ignore-invisible t))
4985 (org-set-local 'outline-regexp org-outline-regexp)
4986 (org-set-local 'outline-level 'org-outline-level)
4987 (when (and org-ellipsis
4988 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
4989 (fboundp 'make-glyph-code))
4990 (unless org-display-table
4991 (setq org-display-table (make-display-table)))
4992 (set-display-table-slot
4993 org-display-table 4
4994 (vconcat (mapcar
4995 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
4996 org-ellipsis)))
4997 (if (stringp org-ellipsis) org-ellipsis "..."))))
4998 (setq buffer-display-table org-display-table))
4999 (org-set-regexps-and-options)
5000 ;; Calc embedded
5001 (org-set-local 'calc-embedded-open-mode "# ")
5002 (modify-syntax-entry ?# "<")
5003 (modify-syntax-entry ?@ "w")
5004 (if org-startup-truncated (setq truncate-lines t))
5005 (org-set-local 'font-lock-unfontify-region-function
5006 'org-unfontify-region)
5007 ;; Activate before-change-function
5008 (org-set-local 'org-table-may-need-update t)
5009 (org-add-hook 'before-change-functions 'org-before-change-function nil
5010 'local)
5011 ;; Check for running clock before killing a buffer
5012 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
5013 ;; Paragraphs and auto-filling
5014 (org-set-autofill-regexps)
5015 (setq indent-line-function 'org-indent-line-function)
5016 (org-update-radio-target-regexp)
5018 ;; Comment characters
5019 ; (org-set-local 'comment-start "#") ;; FIXME: this breaks wrapping
5020 (org-set-local 'comment-padding " ")
5022 ;; Align options lines
5023 (org-set-local
5024 'align-mode-rules-list
5025 '((org-in-buffer-settings
5026 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5027 (modes . '(org-mode)))))
5029 ;; Imenu
5030 (org-set-local 'imenu-create-index-function
5031 'org-imenu-get-tree)
5033 ;; Make isearch reveal context
5034 (if (or (featurep 'xemacs)
5035 (not (boundp 'outline-isearch-open-invisible-function)))
5036 ;; Emacs 21 and XEmacs make use of the hook
5037 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
5038 ;; Emacs 22 deals with this through a special variable
5039 (org-set-local 'outline-isearch-open-invisible-function
5040 (lambda (&rest ignore) (org-show-context 'isearch))))
5042 ;; If empty file that did not turn on org-mode automatically, make it to.
5043 (if (and org-insert-mode-line-in-empty-file
5044 (interactive-p)
5045 (= (point-min) (point-max)))
5046 (insert "# -*- mode: org -*-\n\n"))
5048 (unless org-inhibit-startup
5049 (when org-startup-align-all-tables
5050 (let ((bmp (buffer-modified-p)))
5051 (org-table-map-tables 'org-table-align)
5052 (set-buffer-modified-p bmp)))
5053 (org-cycle-hide-drawers 'all)
5054 (cond
5055 ((eq org-startup-folded t)
5056 (org-cycle '(4)))
5057 ((eq org-startup-folded 'content)
5058 (let ((this-command 'org-cycle) (last-command 'org-cycle))
5059 (org-cycle '(4)) (org-cycle '(4)))))))
5061 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
5063 (defsubst org-call-with-arg (command arg)
5064 "Call COMMAND interactively, but pretend prefix are was ARG."
5065 (let ((current-prefix-arg arg)) (call-interactively command)))
5067 (defsubst org-current-line (&optional pos)
5068 (save-excursion
5069 (and pos (goto-char pos))
5070 ;; works also in narrowed buffer, because we start at 1, not point-min
5071 (+ (if (bolp) 1 0) (count-lines 1 (point)))))
5073 (defun org-current-time ()
5074 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
5075 (if (> org-time-stamp-rounding-minutes 0)
5076 (let ((r org-time-stamp-rounding-minutes)
5077 (time (decode-time)))
5078 (apply 'encode-time
5079 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5080 (nthcdr 2 time))))
5081 (current-time)))
5083 (defun org-add-props (string plist &rest props)
5084 "Add text properties to entire string, from beginning to end.
5085 PLIST may be a list of properties, PROPS are individual properties and values
5086 that will be added to PLIST. Returns the string that was modified."
5087 (add-text-properties
5088 0 (length string) (if props (append plist props) plist) string)
5089 string)
5090 (put 'org-add-props 'lisp-indent-function 2)
5093 ;;;; Font-Lock stuff, including the activators
5095 (defvar org-mouse-map (make-sparse-keymap))
5096 (org-defkey org-mouse-map
5097 (if (featurep 'xemacs) [button2] [mouse-2]) 'org-open-at-mouse)
5098 (org-defkey org-mouse-map
5099 (if (featurep 'xemacs) [button3] [mouse-3]) 'org-find-file-at-mouse)
5100 (when org-mouse-1-follows-link
5101 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5102 (when org-tab-follows-link
5103 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5104 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5105 (when org-return-follows-link
5106 (org-defkey org-mouse-map [(return)] 'org-open-at-point)
5107 (org-defkey org-mouse-map "\C-m" 'org-open-at-point))
5109 (require 'font-lock)
5111 (defconst org-non-link-chars "]\t\n\r<>")
5112 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news" "bbdb" "vm"
5113 "wl" "mhe" "rmail" "gnus" "shell" "info" "elisp" "message"))
5114 (defvar org-link-re-with-space nil
5115 "Matches a link with spaces, optional angular brackets around it.")
5116 (defvar org-link-re-with-space2 nil
5117 "Matches a link with spaces, optional angular brackets around it.")
5118 (defvar org-angle-link-re nil
5119 "Matches link with angular brackets, spaces are allowed.")
5120 (defvar org-plain-link-re nil
5121 "Matches plain link, without spaces.")
5122 (defvar org-bracket-link-regexp nil
5123 "Matches a link in double brackets.")
5124 (defvar org-bracket-link-analytic-regexp nil
5125 "Regular expression used to analyze links.
5126 Here is what the match groups contain after a match:
5127 1: http:
5128 2: http
5129 3: path
5130 4: [desc]
5131 5: desc")
5132 (defvar org-any-link-re nil
5133 "Regular expression matching any link.")
5135 (defun org-make-link-regexps ()
5136 "Update the link regular expressions.
5137 This should be called after the variable `org-link-types' has changed."
5138 (setq org-link-re-with-space
5139 (concat
5140 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
5141 "\\([^" org-non-link-chars " ]"
5142 "[^" org-non-link-chars "]*"
5143 "[^" org-non-link-chars " ]\\)>?")
5144 org-link-re-with-space2
5145 (concat
5146 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
5147 "\\([^" org-non-link-chars " ]"
5148 "[^]\t\n\r]*"
5149 "[^" org-non-link-chars " ]\\)>?")
5150 org-angle-link-re
5151 (concat
5152 "<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
5153 "\\([^" org-non-link-chars " ]"
5154 "[^" org-non-link-chars "]*"
5155 "\\)>")
5156 org-plain-link-re
5157 (concat
5158 "\\<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
5159 "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5160 org-bracket-link-regexp
5161 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5162 org-bracket-link-analytic-regexp
5163 (concat
5164 "\\[\\["
5165 "\\(\\(" (mapconcat 'identity org-link-types "\\|") "\\):\\)?"
5166 "\\([^]]+\\)"
5167 "\\]"
5168 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5169 "\\]")
5170 org-any-link-re
5171 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5172 org-angle-link-re "\\)\\|\\("
5173 org-plain-link-re "\\)")))
5175 (org-make-link-regexps)
5177 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)>"
5178 "Regular expression for fast time stamp matching.")
5179 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)[]>]"
5180 "Regular expression for fast time stamp matching.")
5181 (defconst org-ts-regexp0 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\([^]0-9>\r\n]*\\)\\(\\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5182 "Regular expression matching time strings for analysis.
5183 This one does not require the space after the date.")
5184 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) \\([^]0-9>\r\n]*\\)\\(\\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5185 "Regular expression matching time strings for analysis.")
5186 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
5187 "Regular expression matching time stamps, with groups.")
5188 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
5189 "Regular expression matching time stamps (also [..]), with groups.")
5190 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
5191 "Regular expression matching a time stamp range.")
5192 (defconst org-tr-regexp-both
5193 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
5194 "Regular expression matching a time stamp range.")
5195 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
5196 org-ts-regexp "\\)?")
5197 "Regular expression matching a time stamp or time stamp range.")
5198 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
5199 org-ts-regexp-both "\\)?")
5200 "Regular expression matching a time stamp or time stamp range.
5201 The time stamps may be either active or inactive.")
5203 (defvar org-emph-face nil)
5205 (defun org-do-emphasis-faces (limit)
5206 "Run through the buffer and add overlays to links."
5207 (let (rtn)
5208 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5209 (if (not (= (char-after (match-beginning 3))
5210 (char-after (match-beginning 4))))
5211 (progn
5212 (setq rtn t)
5213 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5214 'face
5215 (nth 1 (assoc (match-string 3)
5216 org-emphasis-alist)))
5217 (add-text-properties (match-beginning 2) (match-end 2)
5218 '(font-lock-multiline t))
5219 (when org-hide-emphasis-markers
5220 (add-text-properties (match-end 4) (match-beginning 5)
5221 '(invisible org-link))
5222 (add-text-properties (match-beginning 3) (match-end 3)
5223 '(invisible org-link)))))
5224 (backward-char 1))
5225 rtn))
5227 (defun org-emphasize (&optional char)
5228 "Insert or change an emphasis, i.e. a font like bold or italic.
5229 If there is an active region, change that region to a new emphasis.
5230 If there is no region, just insert the marker characters and position
5231 the cursor between them.
5232 CHAR should be either the marker character, or the first character of the
5233 HTML tag associated with that emphasis. If CHAR is a space, the means
5234 to remove the emphasis of the selected region.
5235 If char is not given (for example in an interactive call) it
5236 will be prompted for."
5237 (interactive)
5238 (let ((eal org-emphasis-alist) e det
5239 (erc org-emphasis-regexp-components)
5240 (prompt "")
5241 (string "") beg end move tag c s)
5242 (if (org-region-active-p)
5243 (setq beg (region-beginning) end (region-end)
5244 string (buffer-substring beg end))
5245 (setq move t))
5247 (while (setq e (pop eal))
5248 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
5249 c (aref tag 0))
5250 (push (cons c (string-to-char (car e))) det)
5251 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
5252 (substring tag 1)))))
5253 (unless char
5254 (message "%s" (concat "Emphasis marker or tag:" prompt))
5255 (setq char (read-char-exclusive)))
5256 (setq char (or (cdr (assoc char det)) char))
5257 (if (equal char ?\ )
5258 (setq s "" move nil)
5259 (unless (assoc (char-to-string char) org-emphasis-alist)
5260 (error "No such emphasis marker: \"%c\"" char))
5261 (setq s (char-to-string char)))
5262 (while (and (> (length string) 1)
5263 (equal (substring string 0 1) (substring string -1))
5264 (assoc (substring string 0 1) org-emphasis-alist))
5265 (setq string (substring string 1 -1)))
5266 (setq string (concat s string s))
5267 (if beg (delete-region beg end))
5268 (unless (or (bolp)
5269 (string-match (concat "[" (nth 0 erc) "\n]")
5270 (char-to-string (char-before (point)))))
5271 (insert " "))
5272 (unless (string-match (concat "[" (nth 1 erc) "\n]")
5273 (char-to-string (char-after (point))))
5274 (insert " ") (backward-char 1))
5275 (insert string)
5276 (and move (backward-char 1))))
5278 (defconst org-nonsticky-props
5279 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
5282 (defun org-activate-plain-links (limit)
5283 "Run through the buffer and add overlays to links."
5284 (catch 'exit
5285 (let (f)
5286 (while (re-search-forward org-plain-link-re limit t)
5287 (setq f (get-text-property (match-beginning 0) 'face))
5288 (if (or (eq f 'org-tag)
5289 (and (listp f) (memq 'org-tag f)))
5291 (add-text-properties (match-beginning 0) (match-end 0)
5292 (list 'mouse-face 'highlight
5293 'rear-nonsticky org-nonsticky-props
5294 'keymap org-mouse-map
5296 (throw 'exit t))))))
5298 (defun org-activate-code (limit)
5299 (if (re-search-forward "^[ \t]*\\(:.*\\)" limit t)
5300 (unless (get-text-property (match-beginning 1) 'face)
5301 (remove-text-properties (match-beginning 0) (match-end 0)
5302 '(display t invisible t intangible t))
5303 t)))
5305 (defun org-activate-angle-links (limit)
5306 "Run through the buffer and add overlays to links."
5307 (if (re-search-forward org-angle-link-re limit t)
5308 (progn
5309 (add-text-properties (match-beginning 0) (match-end 0)
5310 (list 'mouse-face 'highlight
5311 'rear-nonsticky org-nonsticky-props
5312 'keymap org-mouse-map
5314 t)))
5316 (defmacro org-maybe-intangible (props)
5317 "Add '(intangigble t) to PROPS if Emacs version is earlier than Emacs 22.
5318 In emacs 21, invisible text is not avoided by the command loop, so the
5319 intangible property is needed to make sure point skips this text.
5320 In Emacs 22, this is not necessary. The intangible text property has
5321 led to problems with flyspell. These problems are fixed in flyspell.el,
5322 but we still avoid setting the property in Emacs 22 and later.
5323 We use a macro so that the test can happen at compilation time."
5324 (if (< emacs-major-version 22)
5325 `(append '(intangible t) ,props)
5326 props))
5328 (defun org-activate-bracket-links (limit)
5329 "Run through the buffer and add overlays to bracketed links."
5330 (if (re-search-forward org-bracket-link-regexp limit t)
5331 (let* ((help (concat "LINK: "
5332 (org-match-string-no-properties 1)))
5333 ;; FIXME: above we should remove the escapes.
5334 ;; but that requires another match, protecting match data,
5335 ;; a lot of overhead for font-lock.
5336 (ip (org-maybe-intangible
5337 (list 'invisible 'org-link 'rear-nonsticky org-nonsticky-props
5338 'keymap org-mouse-map 'mouse-face 'highlight
5339 'font-lock-multiline t 'help-echo help)))
5340 (vp (list 'rear-nonsticky org-nonsticky-props
5341 'keymap org-mouse-map 'mouse-face 'highlight
5342 ' font-lock-multiline t 'help-echo help)))
5343 ;; We need to remove the invisible property here. Table narrowing
5344 ;; may have made some of this invisible.
5345 (remove-text-properties (match-beginning 0) (match-end 0)
5346 '(invisible nil))
5347 (if (match-end 3)
5348 (progn
5349 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
5350 (add-text-properties (match-beginning 3) (match-end 3) vp)
5351 (add-text-properties (match-end 3) (match-end 0) ip))
5352 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
5353 (add-text-properties (match-beginning 1) (match-end 1) vp)
5354 (add-text-properties (match-end 1) (match-end 0) ip))
5355 t)))
5357 (defun org-activate-dates (limit)
5358 "Run through the buffer and add overlays to dates."
5359 (if (re-search-forward org-tsr-regexp-both limit t)
5360 (progn
5361 (add-text-properties (match-beginning 0) (match-end 0)
5362 (list 'mouse-face 'highlight
5363 'rear-nonsticky org-nonsticky-props
5364 'keymap org-mouse-map))
5365 (when org-display-custom-times
5366 (if (match-end 3)
5367 (org-display-custom-time (match-beginning 3) (match-end 3)))
5368 (org-display-custom-time (match-beginning 1) (match-end 1)))
5369 t)))
5371 (defvar org-target-link-regexp nil
5372 "Regular expression matching radio targets in plain text.")
5373 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
5374 "Regular expression matching a link target.")
5375 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
5376 "Regular expression matching a radio target.")
5377 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
5378 "Regular expression matching any target.")
5380 (defun org-activate-target-links (limit)
5381 "Run through the buffer and add overlays to target matches."
5382 (when org-target-link-regexp
5383 (let ((case-fold-search t))
5384 (if (re-search-forward org-target-link-regexp limit t)
5385 (progn
5386 (add-text-properties (match-beginning 0) (match-end 0)
5387 (list 'mouse-face 'highlight
5388 'rear-nonsticky org-nonsticky-props
5389 'keymap org-mouse-map
5390 'help-echo "Radio target link"
5391 'org-linked-text t))
5392 t)))))
5394 (defun org-update-radio-target-regexp ()
5395 "Find all radio targets in this file and update the regular expression."
5396 (interactive)
5397 (when (memq 'radio org-activate-links)
5398 (setq org-target-link-regexp
5399 (org-make-target-link-regexp (org-all-targets 'radio)))
5400 (org-restart-font-lock)))
5402 (defun org-hide-wide-columns (limit)
5403 (let (s e)
5404 (setq s (text-property-any (point) (or limit (point-max))
5405 'org-cwidth t))
5406 (when s
5407 (setq e (next-single-property-change s 'org-cwidth))
5408 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
5409 (goto-char e)
5410 t)))
5412 (defvar org-latex-and-specials-regexp nil
5413 "Regular expression for highlighting export special stuff.")
5414 (defvar org-match-substring-regexp)
5415 (defvar org-match-substring-with-braces-regexp)
5416 (defvar org-export-html-special-string-regexps)
5418 (defun org-compute-latex-and-specials-regexp ()
5419 "Compute regular expression for stuff treated specially by exporters."
5420 (if (not org-highlight-latex-fragments-and-specials)
5421 (org-set-local 'org-latex-and-specials-regexp nil)
5422 (let*
5423 ((matchers (plist-get org-format-latex-options :matchers))
5424 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
5425 org-latex-regexps)))
5426 (options (org-combine-plists (org-default-export-plist)
5427 (org-infile-export-plist)))
5428 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
5429 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
5430 (org-export-with-TeX-macros (plist-get options :TeX-macros))
5431 (org-export-html-expand (plist-get options :expand-quoted-html))
5432 (org-export-with-special-strings (plist-get options :special-strings))
5433 (re-sub
5434 (cond
5435 ((equal org-export-with-sub-superscripts '{})
5436 (list org-match-substring-with-braces-regexp))
5437 (org-export-with-sub-superscripts
5438 (list org-match-substring-regexp))
5439 (t nil)))
5440 (re-latex
5441 (if org-export-with-LaTeX-fragments
5442 (mapcar (lambda (x) (nth 1 x)) latexs)))
5443 (re-macros
5444 (if org-export-with-TeX-macros
5445 (list (concat "\\\\"
5446 (regexp-opt
5447 (append (mapcar 'car org-html-entities)
5448 (if (boundp 'org-latex-entities)
5449 org-latex-entities nil))
5450 'words))) ; FIXME
5452 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
5453 (re-special (if org-export-with-special-strings
5454 (mapcar (lambda (x) (car x))
5455 org-export-html-special-string-regexps)))
5456 (re-rest
5457 (delq nil
5458 (list
5459 (if org-export-html-expand "@<[^>\n]+>")
5460 ))))
5461 (org-set-local
5462 'org-latex-and-specials-regexp
5463 (mapconcat 'identity (append re-latex re-sub re-macros re-special
5464 re-rest) "\\|")))))
5466 (defface org-latex-and-export-specials
5467 (let ((font (cond ((assq :inherit custom-face-attributes)
5468 '(:inherit underline))
5469 (t '(:underline t)))))
5470 `((((class grayscale) (background light))
5471 (:foreground "DimGray" ,@font))
5472 (((class grayscale) (background dark))
5473 (:foreground "LightGray" ,@font))
5474 (((class color) (background light))
5475 (:foreground "SaddleBrown"))
5476 (((class color) (background dark))
5477 (:foreground "burlywood"))
5478 (t (,@font))))
5479 "Face used to highlight math latex and other special exporter stuff."
5480 :group 'org-faces)
5482 (defun org-do-latex-and-special-faces (limit)
5483 "Run through the buffer and add overlays to links."
5484 (when org-latex-and-specials-regexp
5485 (let (rtn d)
5486 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
5487 limit t))
5488 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
5489 'face))
5490 '(org-code org-verbatim underline)))
5491 (progn
5492 (setq rtn t
5493 d (cond ((member (char-after (1+ (match-beginning 0)))
5494 '(?_ ?^)) 1)
5495 (t 0)))
5496 (font-lock-prepend-text-property
5497 (+ d (match-beginning 0)) (match-end 0)
5498 'face 'org-latex-and-export-specials)
5499 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
5500 '(font-lock-multiline t)))))
5501 rtn)))
5503 (defun org-restart-font-lock ()
5504 "Restart font-lock-mode, to force refontification."
5505 (when (and (boundp 'font-lock-mode) font-lock-mode)
5506 (font-lock-mode -1)
5507 (font-lock-mode 1)))
5509 (defun org-all-targets (&optional radio)
5510 "Return a list of all targets in this file.
5511 With optional argument RADIO, only find radio targets."
5512 (let ((re (if radio org-radio-target-regexp org-target-regexp))
5513 rtn)
5514 (save-excursion
5515 (goto-char (point-min))
5516 (while (re-search-forward re nil t)
5517 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
5518 rtn)))
5520 (defun org-make-target-link-regexp (targets)
5521 "Make regular expression matching all strings in TARGETS.
5522 The regular expression finds the targets also if there is a line break
5523 between words."
5524 (and targets
5525 (concat
5526 "\\<\\("
5527 (mapconcat
5528 (lambda (x)
5529 (while (string-match " +" x)
5530 (setq x (replace-match "\\s-+" t t x)))
5532 targets
5533 "\\|")
5534 "\\)\\>")))
5536 (defun org-activate-tags (limit)
5537 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \r\n]") limit t)
5538 (progn
5539 (add-text-properties (match-beginning 1) (match-end 1)
5540 (list 'mouse-face 'highlight
5541 'rear-nonsticky org-nonsticky-props
5542 'keymap org-mouse-map))
5543 t)))
5545 (defun org-outline-level ()
5546 (save-excursion
5547 (looking-at outline-regexp)
5548 (if (match-beginning 1)
5549 (+ (org-get-string-indentation (match-string 1)) 1000)
5550 (1- (- (match-end 0) (match-beginning 0))))))
5552 (defvar org-font-lock-keywords nil)
5554 (defconst org-property-re (org-re "^[ \t]*\\(:\\([[:alnum:]_]+\\):\\)[ \t]*\\(\\S-.*\\)")
5555 "Regular expression matching a property line.")
5557 (defun org-set-font-lock-defaults ()
5558 (let* ((em org-fontify-emphasized-text)
5559 (lk org-activate-links)
5560 (org-font-lock-extra-keywords
5561 (list
5562 ;; Headlines
5563 '("^\\(\\**\\)\\(\\* \\)\\(.*\\)" (1 (org-get-level-face 1))
5564 (2 (org-get-level-face 2)) (3 (org-get-level-face 3)))
5565 ;; Table lines
5566 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
5567 (1 'org-table t))
5568 ;; Table internals
5569 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
5570 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
5571 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
5572 ;; Drawers
5573 (list org-drawer-regexp '(0 'org-special-keyword t))
5574 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
5575 ;; Properties
5576 (list org-property-re
5577 '(1 'org-special-keyword t)
5578 '(3 'org-property-value t))
5579 (if org-format-transports-properties-p
5580 '("| *\\(<[0-9]+>\\) *" (1 'org-formula t)))
5581 ;; Links
5582 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
5583 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
5584 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
5585 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
5586 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
5587 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
5588 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
5589 '(org-hide-wide-columns (0 nil append))
5590 ;; TODO lines
5591 (list (concat "^\\*+[ \t]+" org-todo-regexp)
5592 '(1 (org-get-todo-face 1) t))
5593 ;; DONE
5594 (if org-fontify-done-headline
5595 (list (concat "^[*]+ +\\<\\("
5596 (mapconcat 'regexp-quote org-done-keywords "\\|")
5597 "\\)\\(.*\\)")
5598 '(2 'org-headline-done t))
5599 nil)
5600 ;; Priorities
5601 (list (concat "\\[#[A-Z0-9]\\]") '(0 'org-special-keyword t))
5602 ;; Special keywords
5603 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
5604 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
5605 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
5606 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
5607 ;; Emphasis
5608 (if em
5609 (if (featurep 'xemacs)
5610 '(org-do-emphasis-faces (0 nil append))
5611 '(org-do-emphasis-faces)))
5612 ;; Checkboxes
5613 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)"
5614 2 'bold prepend)
5615 (if org-provide-checkbox-statistics
5616 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
5617 (0 (org-get-checkbox-statistics-face) t)))
5618 (list (concat "^\\*+ \\(.*:" org-archive-tag ":.*\\)")
5619 '(1 'org-archived prepend))
5620 ;; Specials
5621 '(org-do-latex-and-special-faces)
5622 ;; Code
5623 '(org-activate-code (1 'org-code t))
5624 ;; COMMENT
5625 (list (concat "^\\*+[ \t]+\\<\\(" org-comment-string
5626 "\\|" org-quote-string "\\)\\>")
5627 '(1 'org-special-keyword t))
5628 '("^#.*" (0 'font-lock-comment-face t))
5630 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
5631 ;; Now set the full font-lock-keywords
5632 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
5633 (org-set-local 'font-lock-defaults
5634 '(org-font-lock-keywords t nil nil backward-paragraph))
5635 (kill-local-variable 'font-lock-keywords) nil))
5637 (defvar org-m nil)
5638 (defvar org-l nil)
5639 (defvar org-f nil)
5640 (defun org-get-level-face (n)
5641 "Get the right face for match N in font-lock matching of healdines."
5642 (setq org-l (- (match-end 2) (match-beginning 1) 1))
5643 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
5644 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
5645 (cond
5646 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
5647 ((eq n 2) org-f)
5648 (t (if org-level-color-stars-only nil org-f))))
5650 (defun org-get-todo-face (kwd)
5651 "Get the right face for a TODO keyword KWD.
5652 If KWD is a number, get the corresponding match group."
5653 (if (numberp kwd) (setq kwd (match-string kwd)))
5654 (or (cdr (assoc kwd org-todo-keyword-faces))
5655 (and (member kwd org-done-keywords) 'org-done)
5656 'org-todo))
5658 (defun org-unfontify-region (beg end &optional maybe_loudly)
5659 "Remove fontification and activation overlays from links."
5660 (font-lock-default-unfontify-region beg end)
5661 (let* ((buffer-undo-list t)
5662 (inhibit-read-only t) (inhibit-point-motion-hooks t)
5663 (inhibit-modification-hooks t)
5664 deactivate-mark buffer-file-name buffer-file-truename)
5665 (remove-text-properties beg end
5666 '(mouse-face t keymap t org-linked-text t
5667 invisible t intangible t))))
5669 ;;;; Visibility cycling, including org-goto and indirect buffer
5671 ;;; Cycling
5673 (defvar org-cycle-global-status nil)
5674 (make-variable-buffer-local 'org-cycle-global-status)
5675 (defvar org-cycle-subtree-status nil)
5676 (make-variable-buffer-local 'org-cycle-subtree-status)
5678 ;;;###autoload
5679 (defun org-cycle (&optional arg)
5680 "Visibility cycling for Org-mode.
5682 - When this function is called with a prefix argument, rotate the entire
5683 buffer through 3 states (global cycling)
5684 1. OVERVIEW: Show only top-level headlines.
5685 2. CONTENTS: Show all headlines of all levels, but no body text.
5686 3. SHOW ALL: Show everything.
5688 - When point is at the beginning of a headline, rotate the subtree started
5689 by this line through 3 different states (local cycling)
5690 1. FOLDED: Only the main headline is shown.
5691 2. CHILDREN: The main headline and the direct children are shown.
5692 From this state, you can move to one of the children
5693 and zoom in further.
5694 3. SUBTREE: Show the entire subtree, including body text.
5696 - When there is a numeric prefix, go up to a heading with level ARG, do
5697 a `show-subtree' and return to the previous cursor position. If ARG
5698 is negative, go up that many levels.
5700 - When point is not at the beginning of a headline, execute
5701 `indent-relative', like TAB normally does. See the option
5702 `org-cycle-emulate-tab' for details.
5704 - Special case: if point is at the beginning of the buffer and there is
5705 no headline in line 1, this function will act as if called with prefix arg.
5706 But only if also the variable `org-cycle-global-at-bob' is t."
5707 (interactive "P")
5708 (let* ((outline-regexp
5709 (if (and (org-mode-p) org-cycle-include-plain-lists)
5710 "\\(?:\\*+ \\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) \\)"
5711 outline-regexp))
5712 (bob-special (and org-cycle-global-at-bob (bobp)
5713 (not (looking-at outline-regexp))))
5714 (org-cycle-hook
5715 (if bob-special
5716 (delq 'org-optimize-window-after-visibility-change
5717 (copy-sequence org-cycle-hook))
5718 org-cycle-hook))
5719 (pos (point)))
5721 (if (or bob-special (equal arg '(4)))
5722 ;; special case: use global cycling
5723 (setq arg t))
5725 (cond
5727 ((org-at-table-p 'any)
5728 ;; Enter the table or move to the next field in the table
5729 (or (org-table-recognize-table.el)
5730 (progn
5731 (if arg (org-table-edit-field t)
5732 (org-table-justify-field-maybe)
5733 (call-interactively 'org-table-next-field)))))
5735 ((eq arg t) ;; Global cycling
5737 (cond
5738 ((and (eq last-command this-command)
5739 (eq org-cycle-global-status 'overview))
5740 ;; We just created the overview - now do table of contents
5741 ;; This can be slow in very large buffers, so indicate action
5742 (message "CONTENTS...")
5743 (org-content)
5744 (message "CONTENTS...done")
5745 (setq org-cycle-global-status 'contents)
5746 (run-hook-with-args 'org-cycle-hook 'contents))
5748 ((and (eq last-command this-command)
5749 (eq org-cycle-global-status 'contents))
5750 ;; We just showed the table of contents - now show everything
5751 (show-all)
5752 (message "SHOW ALL")
5753 (setq org-cycle-global-status 'all)
5754 (run-hook-with-args 'org-cycle-hook 'all))
5757 ;; Default action: go to overview
5758 (org-overview)
5759 (message "OVERVIEW")
5760 (setq org-cycle-global-status 'overview)
5761 (run-hook-with-args 'org-cycle-hook 'overview))))
5763 ((and org-drawers org-drawer-regexp
5764 (save-excursion
5765 (beginning-of-line 1)
5766 (looking-at org-drawer-regexp)))
5767 ;; Toggle block visibility
5768 (org-flag-drawer
5769 (not (get-char-property (match-end 0) 'invisible))))
5771 ((integerp arg)
5772 ;; Show-subtree, ARG levels up from here.
5773 (save-excursion
5774 (org-back-to-heading)
5775 (outline-up-heading (if (< arg 0) (- arg)
5776 (- (funcall outline-level) arg)))
5777 (org-show-subtree)))
5779 ((and (save-excursion (beginning-of-line 1) (looking-at outline-regexp))
5780 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
5781 ;; At a heading: rotate between three different views
5782 (org-back-to-heading)
5783 (let ((goal-column 0) eoh eol eos)
5784 ;; First, some boundaries
5785 (save-excursion
5786 (org-back-to-heading)
5787 (save-excursion
5788 (beginning-of-line 2)
5789 (while (and (not (eobp)) ;; this is like `next-line'
5790 (get-char-property (1- (point)) 'invisible))
5791 (beginning-of-line 2)) (setq eol (point)))
5792 (outline-end-of-heading) (setq eoh (point))
5793 (org-end-of-subtree t)
5794 (unless (eobp)
5795 (skip-chars-forward " \t\n")
5796 (beginning-of-line 1) ; in case this is an item
5798 (setq eos (1- (point))))
5799 ;; Find out what to do next and set `this-command'
5800 (cond
5801 ((= eos eoh)
5802 ;; Nothing is hidden behind this heading
5803 (message "EMPTY ENTRY")
5804 (setq org-cycle-subtree-status nil)
5805 (save-excursion
5806 (goto-char eos)
5807 (outline-next-heading)
5808 (if (org-invisible-p) (org-flag-heading nil))))
5809 ((or (>= eol eos)
5810 (not (string-match "\\S-" (buffer-substring eol eos))))
5811 ;; Entire subtree is hidden in one line: open it
5812 (org-show-entry)
5813 (show-children)
5814 (message "CHILDREN")
5815 (save-excursion
5816 (goto-char eos)
5817 (outline-next-heading)
5818 (if (org-invisible-p) (org-flag-heading nil)))
5819 (setq org-cycle-subtree-status 'children)
5820 (run-hook-with-args 'org-cycle-hook 'children))
5821 ((and (eq last-command this-command)
5822 (eq org-cycle-subtree-status 'children))
5823 ;; We just showed the children, now show everything.
5824 (org-show-subtree)
5825 (message "SUBTREE")
5826 (setq org-cycle-subtree-status 'subtree)
5827 (run-hook-with-args 'org-cycle-hook 'subtree))
5829 ;; Default action: hide the subtree.
5830 (hide-subtree)
5831 (message "FOLDED")
5832 (setq org-cycle-subtree-status 'folded)
5833 (run-hook-with-args 'org-cycle-hook 'folded)))))
5835 ;; TAB emulation
5836 (buffer-read-only (org-back-to-heading))
5838 ((org-try-cdlatex-tab))
5840 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
5841 (or (not (bolp))
5842 (not (looking-at outline-regexp))))
5843 (call-interactively (global-key-binding "\t")))
5845 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
5846 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
5847 (or (and (eq org-cycle-emulate-tab 'white)
5848 (= (match-end 0) (point-at-eol)))
5849 (and (eq org-cycle-emulate-tab 'whitestart)
5850 (>= (match-end 0) pos))))
5852 (eq org-cycle-emulate-tab t))
5853 ; (if (and (looking-at "[ \n\r\t]")
5854 ; (string-match "^[ \t]*$" (buffer-substring
5855 ; (point-at-bol) (point))))
5856 ; (progn
5857 ; (beginning-of-line 1)
5858 ; (and (looking-at "[ \t]+") (replace-match ""))))
5859 (call-interactively (global-key-binding "\t")))
5861 (t (save-excursion
5862 (org-back-to-heading)
5863 (org-cycle))))))
5865 ;;;###autoload
5866 (defun org-global-cycle (&optional arg)
5867 "Cycle the global visibility. For details see `org-cycle'."
5868 (interactive "P")
5869 (let ((org-cycle-include-plain-lists
5870 (if (org-mode-p) org-cycle-include-plain-lists nil)))
5871 (if (integerp arg)
5872 (progn
5873 (show-all)
5874 (hide-sublevels arg)
5875 (setq org-cycle-global-status 'contents))
5876 (org-cycle '(4)))))
5878 (defun org-overview ()
5879 "Switch to overview mode, shoing only top-level headlines.
5880 Really, this shows all headlines with level equal or greater than the level
5881 of the first headline in the buffer. This is important, because if the
5882 first headline is not level one, then (hide-sublevels 1) gives confusing
5883 results."
5884 (interactive)
5885 (let ((level (save-excursion
5886 (goto-char (point-min))
5887 (if (re-search-forward (concat "^" outline-regexp) nil t)
5888 (progn
5889 (goto-char (match-beginning 0))
5890 (funcall outline-level))))))
5891 (and level (hide-sublevels level))))
5893 (defun org-content (&optional arg)
5894 "Show all headlines in the buffer, like a table of contents.
5895 With numerical argument N, show content up to level N."
5896 (interactive "P")
5897 (save-excursion
5898 ;; Visit all headings and show their offspring
5899 (and (integerp arg) (org-overview))
5900 (goto-char (point-max))
5901 (catch 'exit
5902 (while (and (progn (condition-case nil
5903 (outline-previous-visible-heading 1)
5904 (error (goto-char (point-min))))
5906 (looking-at outline-regexp))
5907 (if (integerp arg)
5908 (show-children (1- arg))
5909 (show-branches))
5910 (if (bobp) (throw 'exit nil))))))
5913 (defun org-optimize-window-after-visibility-change (state)
5914 "Adjust the window after a change in outline visibility.
5915 This function is the default value of the hook `org-cycle-hook'."
5916 (when (get-buffer-window (current-buffer))
5917 (cond
5918 ; ((eq state 'overview) (org-first-headline-recenter 1))
5919 ; ((eq state 'overview) (org-beginning-of-line))
5920 ((eq state 'content) nil)
5921 ((eq state 'all) nil)
5922 ((eq state 'folded) nil)
5923 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
5924 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
5926 (defun org-compact-display-after-subtree-move ()
5927 (let (beg end)
5928 (save-excursion
5929 (if (org-up-heading-safe)
5930 (progn
5931 (hide-subtree)
5932 (show-entry)
5933 (show-children)
5934 (org-cycle-show-empty-lines 'children)
5935 (org-cycle-hide-drawers 'children))
5936 (org-overview)))))
5938 (defun org-cycle-show-empty-lines (state)
5939 "Show empty lines above all visible headlines.
5940 The region to be covered depends on STATE when called through
5941 `org-cycle-hook'. Lisp program can use t for STATE to get the
5942 entire buffer covered. Note that an empty line is only shown if there
5943 are at least `org-cycle-separator-lines' empty lines before the headeline."
5944 (when (> org-cycle-separator-lines 0)
5945 (save-excursion
5946 (let* ((n org-cycle-separator-lines)
5947 (re (cond
5948 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
5949 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
5950 (t (let ((ns (number-to-string (- n 2))))
5951 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
5952 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
5953 beg end)
5954 (cond
5955 ((memq state '(overview contents t))
5956 (setq beg (point-min) end (point-max)))
5957 ((memq state '(children folded))
5958 (setq beg (point) end (progn (org-end-of-subtree t t)
5959 (beginning-of-line 2)
5960 (point)))))
5961 (when beg
5962 (goto-char beg)
5963 (while (re-search-forward re end t)
5964 (if (not (get-char-property (match-end 1) 'invisible))
5965 (outline-flag-region
5966 (match-beginning 1) (match-end 1) nil)))))))
5967 ;; Never hide empty lines at the end of the file.
5968 (save-excursion
5969 (goto-char (point-max))
5970 (outline-previous-heading)
5971 (outline-end-of-heading)
5972 (if (and (looking-at "[ \t\n]+")
5973 (= (match-end 0) (point-max)))
5974 (outline-flag-region (point) (match-end 0) nil))))
5976 (defun org-subtree-end-visible-p ()
5977 "Is the end of the current subtree visible?"
5978 (pos-visible-in-window-p
5979 (save-excursion (org-end-of-subtree t) (point))))
5981 (defun org-first-headline-recenter (&optional N)
5982 "Move cursor to the first headline and recenter the headline.
5983 Optional argument N means, put the headline into the Nth line of the window."
5984 (goto-char (point-min))
5985 (when (re-search-forward (concat "^\\(" outline-regexp "\\)") nil t)
5986 (beginning-of-line)
5987 (recenter (prefix-numeric-value N))))
5989 ;;; Org-goto
5991 (defvar org-goto-window-configuration nil)
5992 (defvar org-goto-marker nil)
5993 (defvar org-goto-map
5994 (let ((map (make-sparse-keymap)))
5995 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
5996 (while (setq cmd (pop cmds))
5997 (substitute-key-definition cmd cmd map global-map)))
5998 (suppress-keymap map)
5999 (org-defkey map "\C-m" 'org-goto-ret)
6000 (org-defkey map [(return)] 'org-goto-ret)
6001 (org-defkey map [(left)] 'org-goto-left)
6002 (org-defkey map [(right)] 'org-goto-right)
6003 (org-defkey map [(control ?g)] 'org-goto-quit)
6004 (org-defkey map "\C-i" 'org-cycle)
6005 (org-defkey map [(tab)] 'org-cycle)
6006 (org-defkey map [(down)] 'outline-next-visible-heading)
6007 (org-defkey map [(up)] 'outline-previous-visible-heading)
6008 (if org-goto-auto-isearch
6009 (if (fboundp 'define-key-after)
6010 (define-key-after map [t] 'org-goto-local-auto-isearch)
6011 nil)
6012 (org-defkey map "q" 'org-goto-quit)
6013 (org-defkey map "n" 'outline-next-visible-heading)
6014 (org-defkey map "p" 'outline-previous-visible-heading)
6015 (org-defkey map "f" 'outline-forward-same-level)
6016 (org-defkey map "b" 'outline-backward-same-level)
6017 (org-defkey map "u" 'outline-up-heading))
6018 (org-defkey map "/" 'org-occur)
6019 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
6020 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
6021 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
6022 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
6023 (org-defkey map "\C-c\C-u" 'outline-up-heading)
6024 map))
6026 (defconst org-goto-help
6027 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
6028 RET=jump to location [Q]uit and return to previous location
6029 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
6031 (defvar org-goto-start-pos) ; dynamically scoped parameter
6033 (defun org-goto (&optional alternative-interface)
6034 "Look up a different location in the current file, keeping current visibility.
6036 When you want look-up or go to a different location in a document, the
6037 fastest way is often to fold the entire buffer and then dive into the tree.
6038 This method has the disadvantage, that the previous location will be folded,
6039 which may not be what you want.
6041 This command works around this by showing a copy of the current buffer
6042 in an indirect buffer, in overview mode. You can dive into the tree in
6043 that copy, use org-occur and incremental search to find a location.
6044 When pressing RET or `Q', the command returns to the original buffer in
6045 which the visibility is still unchanged. After RET is will also jump to
6046 the location selected in the indirect buffer and expose the
6047 the headline hierarchy above."
6048 (interactive "P")
6049 (let* ((org-refile-targets '((nil . (:maxlevel . 10))))
6050 (org-refile-use-outline-path t)
6051 (interface
6052 (if (not alternative-interface)
6053 org-goto-interface
6054 (if (eq org-goto-interface 'outline)
6055 'outline-path-completion
6056 'outline)))
6057 (org-goto-start-pos (point))
6058 (selected-point
6059 (if (eq interface 'outline)
6060 (car (org-get-location (current-buffer) org-goto-help))
6061 (nth 3 (org-refile-get-location "Goto: ")))))
6062 (if selected-point
6063 (progn
6064 (org-mark-ring-push org-goto-start-pos)
6065 (goto-char selected-point)
6066 (if (or (org-invisible-p) (org-invisible-p2))
6067 (org-show-context 'org-goto)))
6068 (message "Quit"))))
6070 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
6071 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
6072 (defvar org-goto-local-auto-isearch-map) ; defined below
6074 (defun org-get-location (buf help)
6075 "Let the user select a location in the Org-mode buffer BUF.
6076 This function uses a recursive edit. It returns the selected position
6077 or nil."
6078 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
6079 (isearch-hide-immediately nil)
6080 (isearch-search-fun-function
6081 (lambda () 'org-goto-local-search-forward-headings))
6082 (org-goto-selected-point org-goto-exit-command))
6083 (save-excursion
6084 (save-window-excursion
6085 (delete-other-windows)
6086 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
6087 (switch-to-buffer
6088 (condition-case nil
6089 (make-indirect-buffer (current-buffer) "*org-goto*")
6090 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
6091 (with-output-to-temp-buffer "*Help*"
6092 (princ help))
6093 (shrink-window-if-larger-than-buffer (get-buffer-window "*Help*"))
6094 (setq buffer-read-only nil)
6095 (let ((org-startup-truncated t)
6096 (org-startup-folded nil)
6097 (org-startup-align-all-tables nil))
6098 (org-mode)
6099 (org-overview))
6100 (setq buffer-read-only t)
6101 (if (and (boundp 'org-goto-start-pos)
6102 (integer-or-marker-p org-goto-start-pos))
6103 (let ((org-show-hierarchy-above t)
6104 (org-show-siblings t)
6105 (org-show-following-heading t))
6106 (goto-char org-goto-start-pos)
6107 (and (org-invisible-p) (org-show-context)))
6108 (goto-char (point-min)))
6109 (org-beginning-of-line)
6110 (message "Select location and press RET")
6111 (use-local-map org-goto-map)
6112 (recursive-edit)
6114 (kill-buffer "*org-goto*")
6115 (cons org-goto-selected-point org-goto-exit-command)))
6117 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
6118 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
6119 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
6120 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
6122 (defun org-goto-local-search-forward-headings (string bound noerror)
6123 "Search and make sure that anu matches are in headlines."
6124 (catch 'return
6125 (while (search-forward string bound noerror)
6126 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
6127 (and (member :headline context)
6128 (not (member :tags context))))
6129 (throw 'return (point))))))
6131 (defun org-goto-local-auto-isearch ()
6132 "Start isearch."
6133 (interactive)
6134 (goto-char (point-min))
6135 (let ((keys (this-command-keys)))
6136 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
6137 (isearch-mode t)
6138 (isearch-process-search-char (string-to-char keys)))))
6140 (defun org-goto-ret (&optional arg)
6141 "Finish `org-goto' by going to the new location."
6142 (interactive "P")
6143 (setq org-goto-selected-point (point)
6144 org-goto-exit-command 'return)
6145 (throw 'exit nil))
6147 (defun org-goto-left ()
6148 "Finish `org-goto' by going to the new location."
6149 (interactive)
6150 (if (org-on-heading-p)
6151 (progn
6152 (beginning-of-line 1)
6153 (setq org-goto-selected-point (point)
6154 org-goto-exit-command 'left)
6155 (throw 'exit nil))
6156 (error "Not on a heading")))
6158 (defun org-goto-right ()
6159 "Finish `org-goto' by going to the new location."
6160 (interactive)
6161 (if (org-on-heading-p)
6162 (progn
6163 (setq org-goto-selected-point (point)
6164 org-goto-exit-command 'right)
6165 (throw 'exit nil))
6166 (error "Not on a heading")))
6168 (defun org-goto-quit ()
6169 "Finish `org-goto' without cursor motion."
6170 (interactive)
6171 (setq org-goto-selected-point nil)
6172 (setq org-goto-exit-command 'quit)
6173 (throw 'exit nil))
6175 ;;; Indirect buffer display of subtrees
6177 (defvar org-indirect-dedicated-frame nil
6178 "This is the frame being used for indirect tree display.")
6179 (defvar org-last-indirect-buffer nil)
6181 (defun org-tree-to-indirect-buffer (&optional arg)
6182 "Create indirect buffer and narrow it to current subtree.
6183 With numerical prefix ARG, go up to this level and then take that tree.
6184 If ARG is negative, go up that many levels.
6185 If `org-indirect-buffer-display' is not `new-frame', the command removes the
6186 indirect buffer previously made with this command, to avoid proliferation of
6187 indirect buffers. However, when you call the command with a `C-u' prefix, or
6188 when `org-indirect-buffer-display' is `new-frame', the last buffer
6189 is kept so that you can work with several indirect buffers at the same time.
6190 If `org-indirect-buffer-display' is `dedicated-frame', the C-u prefix also
6191 requests that a new frame be made for the new buffer, so that the dedicated
6192 frame is not changed."
6193 (interactive "P")
6194 (let ((cbuf (current-buffer))
6195 (cwin (selected-window))
6196 (pos (point))
6197 beg end level heading ibuf)
6198 (save-excursion
6199 (org-back-to-heading t)
6200 (when (numberp arg)
6201 (setq level (org-outline-level))
6202 (if (< arg 0) (setq arg (+ level arg)))
6203 (while (> (setq level (org-outline-level)) arg)
6204 (outline-up-heading 1 t)))
6205 (setq beg (point)
6206 heading (org-get-heading))
6207 (org-end-of-subtree t) (setq end (point)))
6208 (if (and (buffer-live-p org-last-indirect-buffer)
6209 (not (eq org-indirect-buffer-display 'new-frame))
6210 (not arg))
6211 (kill-buffer org-last-indirect-buffer))
6212 (setq ibuf (org-get-indirect-buffer cbuf)
6213 org-last-indirect-buffer ibuf)
6214 (cond
6215 ((or (eq org-indirect-buffer-display 'new-frame)
6216 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
6217 (select-frame (make-frame))
6218 (delete-other-windows)
6219 (switch-to-buffer ibuf)
6220 (org-set-frame-title heading))
6221 ((eq org-indirect-buffer-display 'dedicated-frame)
6222 (raise-frame
6223 (select-frame (or (and org-indirect-dedicated-frame
6224 (frame-live-p org-indirect-dedicated-frame)
6225 org-indirect-dedicated-frame)
6226 (setq org-indirect-dedicated-frame (make-frame)))))
6227 (delete-other-windows)
6228 (switch-to-buffer ibuf)
6229 (org-set-frame-title (concat "Indirect: " heading)))
6230 ((eq org-indirect-buffer-display 'current-window)
6231 (switch-to-buffer ibuf))
6232 ((eq org-indirect-buffer-display 'other-window)
6233 (pop-to-buffer ibuf))
6234 (t (error "Invalid value.")))
6235 (if (featurep 'xemacs)
6236 (save-excursion (org-mode) (turn-on-font-lock)))
6237 (narrow-to-region beg end)
6238 (show-all)
6239 (goto-char pos)
6240 (and (window-live-p cwin) (select-window cwin))))
6242 (defun org-get-indirect-buffer (&optional buffer)
6243 (setq buffer (or buffer (current-buffer)))
6244 (let ((n 1) (base (buffer-name buffer)) bname)
6245 (while (buffer-live-p
6246 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
6247 (setq n (1+ n)))
6248 (condition-case nil
6249 (make-indirect-buffer buffer bname 'clone)
6250 (error (make-indirect-buffer buffer bname)))))
6252 (defun org-set-frame-title (title)
6253 "Set the title of the current frame to the string TITLE."
6254 ;; FIXME: how to name a single frame in XEmacs???
6255 (unless (featurep 'xemacs)
6256 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
6258 ;;;; Structure editing
6260 ;;; Inserting headlines
6262 (defun org-insert-heading (&optional force-heading)
6263 "Insert a new heading or item with same depth at point.
6264 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
6265 If point is at the beginning of a headline, insert a sibling before the
6266 current headline. If point is not at the beginning, do not split the line,
6267 but create the new hedline after the current line."
6268 (interactive "P")
6269 (if (= (buffer-size) 0)
6270 (insert "\n* ")
6271 (when (or force-heading (not (org-insert-item)))
6272 (let* ((head (save-excursion
6273 (condition-case nil
6274 (progn
6275 (org-back-to-heading)
6276 (match-string 0))
6277 (error "*"))))
6278 (blank (cdr (assq 'heading org-blank-before-new-entry)))
6279 pos)
6280 (cond
6281 ((and (org-on-heading-p) (bolp)
6282 (or (bobp)
6283 (save-excursion (backward-char 1) (not (org-invisible-p)))))
6284 ;; insert before the current line
6285 (open-line (if blank 2 1)))
6286 ((and (bolp)
6287 (or (bobp)
6288 (save-excursion
6289 (backward-char 1) (not (org-invisible-p)))))
6290 ;; insert right here
6291 nil)
6293 ; ;; in the middle of the line
6294 ; (org-show-entry)
6295 ; (if (org-get-alist-option org-M-RET-may-split-line 'headline)
6296 ; (if (and
6297 ; (org-on-heading-p)
6298 ; (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \r\n]"))
6299 ; ;; protect the tags
6300 ;; (let ((tags (match-string 2)) pos)
6301 ; (delete-region (match-beginning 1) (match-end 1))
6302 ; (setq pos (point-at-bol))
6303 ; (newline (if blank 2 1))
6304 ; (save-excursion
6305 ; (goto-char pos)
6306 ; (end-of-line 1)
6307 ; (insert " " tags)
6308 ; (org-set-tags nil 'align)))
6309 ; (newline (if blank 2 1)))
6310 ; (newline (if blank 2 1))))
6313 ;; in the middle of the line
6314 (org-show-entry)
6315 (let ((split
6316 (org-get-alist-option org-M-RET-may-split-line 'headline))
6317 tags pos)
6318 (if (org-on-heading-p)
6319 (progn
6320 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
6321 (setq tags (and (match-end 2) (match-string 2)))
6322 (and (match-end 1)
6323 (delete-region (match-beginning 1) (match-end 1)))
6324 (setq pos (point-at-bol))
6325 (or split (end-of-line 1))
6326 (delete-horizontal-space)
6327 (newline (if blank 2 1))
6328 (when tags
6329 (save-excursion
6330 (goto-char pos)
6331 (end-of-line 1)
6332 (insert " " tags)
6333 (org-set-tags nil 'align))))
6334 (or split (end-of-line 1))
6335 (newline (if blank 2 1))))))
6336 (insert head) (just-one-space)
6337 (setq pos (point))
6338 (end-of-line 1)
6339 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
6340 (run-hooks 'org-insert-heading-hook)))))
6342 (defun org-insert-heading-after-current ()
6343 "Insert a new heading with same level as current, after current subtree."
6344 (interactive)
6345 (org-back-to-heading)
6346 (org-insert-heading)
6347 (org-move-subtree-down)
6348 (end-of-line 1))
6350 (defun org-insert-todo-heading (arg)
6351 "Insert a new heading with the same level and TODO state as current heading.
6352 If the heading has no TODO state, or if the state is DONE, use the first
6353 state (TODO by default). Also with prefix arg, force first state."
6354 (interactive "P")
6355 (when (not (org-insert-item 'checkbox))
6356 (org-insert-heading)
6357 (save-excursion
6358 (org-back-to-heading)
6359 (outline-previous-heading)
6360 (looking-at org-todo-line-regexp))
6361 (if (or arg
6362 (not (match-beginning 2))
6363 (member (match-string 2) org-done-keywords))
6364 (insert (car org-todo-keywords-1) " ")
6365 (insert (match-string 2) " "))))
6367 (defun org-insert-subheading (arg)
6368 "Insert a new subheading and demote it.
6369 Works for outline headings and for plain lists alike."
6370 (interactive "P")
6371 (org-insert-heading arg)
6372 (cond
6373 ((org-on-heading-p) (org-do-demote))
6374 ((org-at-item-p) (org-indent-item 1))))
6376 (defun org-insert-todo-subheading (arg)
6377 "Insert a new subheading with TODO keyword or checkbox and demote it.
6378 Works for outline headings and for plain lists alike."
6379 (interactive "P")
6380 (org-insert-todo-heading arg)
6381 (cond
6382 ((org-on-heading-p) (org-do-demote))
6383 ((org-at-item-p) (org-indent-item 1))))
6385 ;;; Promotion and Demotion
6387 (defun org-promote-subtree ()
6388 "Promote the entire subtree.
6389 See also `org-promote'."
6390 (interactive)
6391 (save-excursion
6392 (org-map-tree 'org-promote))
6393 (org-fix-position-after-promote))
6395 (defun org-demote-subtree ()
6396 "Demote the entire subtree. See `org-demote'.
6397 See also `org-promote'."
6398 (interactive)
6399 (save-excursion
6400 (org-map-tree 'org-demote))
6401 (org-fix-position-after-promote))
6404 (defun org-do-promote ()
6405 "Promote the current heading higher up the tree.
6406 If the region is active in `transient-mark-mode', promote all headings
6407 in the region."
6408 (interactive)
6409 (save-excursion
6410 (if (org-region-active-p)
6411 (org-map-region 'org-promote (region-beginning) (region-end))
6412 (org-promote)))
6413 (org-fix-position-after-promote))
6415 (defun org-do-demote ()
6416 "Demote the current heading lower down the tree.
6417 If the region is active in `transient-mark-mode', demote all headings
6418 in the region."
6419 (interactive)
6420 (save-excursion
6421 (if (org-region-active-p)
6422 (org-map-region 'org-demote (region-beginning) (region-end))
6423 (org-demote)))
6424 (org-fix-position-after-promote))
6426 (defun org-fix-position-after-promote ()
6427 "Make sure that after pro/demotion cursor position is right."
6428 (let ((pos (point)))
6429 (when (save-excursion
6430 (beginning-of-line 1)
6431 (looking-at org-todo-line-regexp)
6432 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
6433 (cond ((eobp) (insert " "))
6434 ((eolp) (insert " "))
6435 ((equal (char-after) ?\ ) (forward-char 1))))))
6437 (defun org-reduced-level (l)
6438 (if org-odd-levels-only (1+ (floor (/ l 2))) l))
6440 (defun org-get-legal-level (level &optional change)
6441 "Rectify a level change under the influence of `org-odd-levels-only'
6442 LEVEL is a current level, CHANGE is by how much the level should be
6443 modified. Even if CHANGE is nil, LEVEL may be returned modified because
6444 even level numbers will become the next higher odd number."
6445 (if org-odd-levels-only
6446 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
6447 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
6448 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
6449 (max 1 (+ level change))))
6451 (defun org-promote ()
6452 "Promote the current heading higher up the tree.
6453 If the region is active in `transient-mark-mode', promote all headings
6454 in the region."
6455 (org-back-to-heading t)
6456 (let* ((level (save-match-data (funcall outline-level)))
6457 (up-head (concat (make-string (org-get-legal-level level -1) ?*) " "))
6458 (diff (abs (- level (length up-head) -1))))
6459 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
6460 (replace-match up-head nil t)
6461 ;; Fixup tag positioning
6462 (and org-auto-align-tags (org-set-tags nil t))
6463 (if org-adapt-indentation (org-fixup-indentation (- diff)))))
6465 (defun org-demote ()
6466 "Demote the current heading lower down the tree.
6467 If the region is active in `transient-mark-mode', demote all headings
6468 in the region."
6469 (org-back-to-heading t)
6470 (let* ((level (save-match-data (funcall outline-level)))
6471 (down-head (concat (make-string (org-get-legal-level level 1) ?*) " "))
6472 (diff (abs (- level (length down-head) -1))))
6473 (replace-match down-head nil t)
6474 ;; Fixup tag positioning
6475 (and org-auto-align-tags (org-set-tags nil t))
6476 (if org-adapt-indentation (org-fixup-indentation diff))))
6478 (defun org-map-tree (fun)
6479 "Call FUN for every heading underneath the current one."
6480 (org-back-to-heading)
6481 (let ((level (funcall outline-level)))
6482 (save-excursion
6483 (funcall fun)
6484 (while (and (progn
6485 (outline-next-heading)
6486 (> (funcall outline-level) level))
6487 (not (eobp)))
6488 (funcall fun)))))
6490 (defun org-map-region (fun beg end)
6491 "Call FUN for every heading between BEG and END."
6492 (let ((org-ignore-region t))
6493 (save-excursion
6494 (setq end (copy-marker end))
6495 (goto-char beg)
6496 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
6497 (< (point) end))
6498 (funcall fun))
6499 (while (and (progn
6500 (outline-next-heading)
6501 (< (point) end))
6502 (not (eobp)))
6503 (funcall fun)))))
6505 (defun org-fixup-indentation (diff)
6506 "Change the indentation in the current entry by DIFF
6507 However, if any line in the current entry has no indentation, or if it
6508 would end up with no indentation after the change, nothing at all is done."
6509 (save-excursion
6510 (let ((end (save-excursion (outline-next-heading)
6511 (point-marker)))
6512 (prohibit (if (> diff 0)
6513 "^\\S-"
6514 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
6515 col)
6516 (unless (save-excursion (end-of-line 1)
6517 (re-search-forward prohibit end t))
6518 (while (and (< (point) end)
6519 (re-search-forward "^[ \t]+" end t))
6520 (goto-char (match-end 0))
6521 (setq col (current-column))
6522 (if (< diff 0) (replace-match ""))
6523 (indent-to (+ diff col))))
6524 (move-marker end nil))))
6526 (defun org-convert-to-odd-levels ()
6527 "Convert an org-mode file with all levels allowed to one with odd levels.
6528 This will leave level 1 alone, convert level 2 to level 3, level 3 to
6529 level 5 etc."
6530 (interactive)
6531 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
6532 (let ((org-odd-levels-only nil) n)
6533 (save-excursion
6534 (goto-char (point-min))
6535 (while (re-search-forward "^\\*\\*+ " nil t)
6536 (setq n (- (length (match-string 0)) 2))
6537 (while (>= (setq n (1- n)) 0)
6538 (org-demote))
6539 (end-of-line 1))))))
6542 (defun org-convert-to-oddeven-levels ()
6543 "Convert an org-mode file with only odd levels to one with odd and even levels.
6544 This promotes level 3 to level 2, level 5 to level 3 etc. If the file contains a
6545 section with an even level, conversion would destroy the structure of the file. An error
6546 is signaled in this case."
6547 (interactive)
6548 (goto-char (point-min))
6549 ;; First check if there are no even levels
6550 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
6551 (org-show-context t)
6552 (error "Not all levels are odd in this file. Conversion not possible."))
6553 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
6554 (let ((org-odd-levels-only nil) n)
6555 (save-excursion
6556 (goto-char (point-min))
6557 (while (re-search-forward "^\\*\\*+ " nil t)
6558 (setq n (/ (1- (length (match-string 0))) 2))
6559 (while (>= (setq n (1- n)) 0)
6560 (org-promote))
6561 (end-of-line 1))))))
6563 (defun org-tr-level (n)
6564 "Make N odd if required."
6565 (if org-odd-levels-only (1+ (/ n 2)) n))
6567 ;;; Vertical tree motion, cutting and pasting of subtrees
6569 (defun org-move-subtree-up (&optional arg)
6570 "Move the current subtree up past ARG headlines of the same level."
6571 (interactive "p")
6572 (org-move-subtree-down (- (prefix-numeric-value arg))))
6574 (defun org-move-subtree-down (&optional arg)
6575 "Move the current subtree down past ARG headlines of the same level."
6576 (interactive "p")
6577 (setq arg (prefix-numeric-value arg))
6578 (let ((movfunc (if (> arg 0) 'outline-get-next-sibling
6579 'outline-get-last-sibling))
6580 (ins-point (make-marker))
6581 (cnt (abs arg))
6582 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
6583 ;; Select the tree
6584 (org-back-to-heading)
6585 (setq beg0 (point))
6586 (save-excursion
6587 (setq ne-beg (org-back-over-empty-lines))
6588 (setq beg (point)))
6589 (save-match-data
6590 (save-excursion (outline-end-of-heading)
6591 (setq folded (org-invisible-p)))
6592 (outline-end-of-subtree))
6593 (outline-next-heading)
6594 (setq ne-end (org-back-over-empty-lines))
6595 (setq end (point))
6596 (goto-char beg0)
6597 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
6598 ;; include less whitespace
6599 (save-excursion
6600 (goto-char beg)
6601 (forward-line (- ne-beg ne-end))
6602 (setq beg (point))))
6603 ;; Find insertion point, with error handling
6604 (while (> cnt 0)
6605 (or (and (funcall movfunc) (looking-at outline-regexp))
6606 (progn (goto-char beg0)
6607 (error "Cannot move past superior level or buffer limit")))
6608 (setq cnt (1- cnt)))
6609 (if (> arg 0)
6610 ;; Moving forward - still need to move over subtree
6611 (progn (org-end-of-subtree t t)
6612 (save-excursion
6613 (org-back-over-empty-lines)
6614 (or (bolp) (newline)))))
6615 (setq ne-ins (org-back-over-empty-lines))
6616 (move-marker ins-point (point))
6617 (setq txt (buffer-substring beg end))
6618 (delete-region beg end)
6619 (outline-flag-region (1- beg) beg nil)
6620 (outline-flag-region (1- (point)) (point) nil)
6621 (insert txt)
6622 (or (bolp) (insert "\n"))
6623 (setq ins-end (point))
6624 (goto-char ins-point)
6625 (org-skip-whitespace)
6626 (when (and (< arg 0)
6627 (org-first-sibling-p)
6628 (> ne-ins ne-beg))
6629 ;; Move whitespace back to beginning
6630 (save-excursion
6631 (goto-char ins-end)
6632 (let ((kill-whole-line t))
6633 (kill-line (- ne-ins ne-beg)) (point)))
6634 (insert (make-string (- ne-ins ne-beg) ?\n)))
6635 (move-marker ins-point nil)
6636 (org-compact-display-after-subtree-move)
6637 (unless folded
6638 (org-show-entry)
6639 (show-children)
6640 (org-cycle-hide-drawers 'children))))
6642 (defvar org-subtree-clip ""
6643 "Clipboard for cut and paste of subtrees.
6644 This is actually only a copy of the kill, because we use the normal kill
6645 ring. We need it to check if the kill was created by `org-copy-subtree'.")
6647 (defvar org-subtree-clip-folded nil
6648 "Was the last copied subtree folded?
6649 This is used to fold the tree back after pasting.")
6651 (defun org-cut-subtree (&optional n)
6652 "Cut the current subtree into the clipboard.
6653 With prefix arg N, cut this many sequential subtrees.
6654 This is a short-hand for marking the subtree and then cutting it."
6655 (interactive "p")
6656 (org-copy-subtree n 'cut))
6658 (defun org-copy-subtree (&optional n cut)
6659 "Cut the current subtree into the clipboard.
6660 With prefix arg N, cut this many sequential subtrees.
6661 This is a short-hand for marking the subtree and then copying it.
6662 If CUT is non-nil, actually cut the subtree."
6663 (interactive "p")
6664 (let (beg end folded (beg0 (point)))
6665 (if (interactive-p)
6666 (org-back-to-heading nil) ; take what looks like a subtree
6667 (org-back-to-heading t)) ; take what is really there
6668 (org-back-over-empty-lines)
6669 (setq beg (point))
6670 (skip-chars-forward " \t\r\n")
6671 (save-match-data
6672 (save-excursion (outline-end-of-heading)
6673 (setq folded (org-invisible-p)))
6674 (condition-case nil
6675 (outline-forward-same-level (1- n))
6676 (error nil))
6677 (org-end-of-subtree t t))
6678 (org-back-over-empty-lines)
6679 (setq end (point))
6680 (goto-char beg0)
6681 (when (> end beg)
6682 (setq org-subtree-clip-folded folded)
6683 (if cut (kill-region beg end) (copy-region-as-kill beg end))
6684 (setq org-subtree-clip (current-kill 0))
6685 (message "%s: Subtree(s) with %d characters"
6686 (if cut "Cut" "Copied")
6687 (length org-subtree-clip)))))
6689 (defun org-paste-subtree (&optional level tree)
6690 "Paste the clipboard as a subtree, with modification of headline level.
6691 The entire subtree is promoted or demoted in order to match a new headline
6692 level. By default, the new level is derived from the visible headings
6693 before and after the insertion point, and taken to be the inferior headline
6694 level of the two. So if the previous visible heading is level 3 and the
6695 next is level 4 (or vice versa), level 4 will be used for insertion.
6696 This makes sure that the subtree remains an independent subtree and does
6697 not swallow low level entries.
6699 You can also force a different level, either by using a numeric prefix
6700 argument, or by inserting the heading marker by hand. For example, if the
6701 cursor is after \"*****\", then the tree will be shifted to level 5.
6703 If you want to insert the tree as is, just use \\[yank].
6705 If optional TREE is given, use this text instead of the kill ring."
6706 (interactive "P")
6707 (unless (org-kill-is-subtree-p tree)
6708 (error "%s"
6709 (substitute-command-keys
6710 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
6711 (let* ((txt (or tree (and kill-ring (current-kill 0))))
6712 (^re (concat "^\\(" outline-regexp "\\)"))
6713 (re (concat "\\(" outline-regexp "\\)"))
6714 (^re_ (concat "\\(\\*+\\)[ \t]*"))
6716 (old-level (if (string-match ^re txt)
6717 (- (match-end 0) (match-beginning 0) 1)
6718 -1))
6719 (force-level (cond (level (prefix-numeric-value level))
6720 ((string-match
6721 ^re_ (buffer-substring (point-at-bol) (point)))
6722 (- (match-end 1) (match-beginning 1)))
6723 (t nil)))
6724 (previous-level (save-excursion
6725 (condition-case nil
6726 (progn
6727 (outline-previous-visible-heading 1)
6728 (if (looking-at re)
6729 (- (match-end 0) (match-beginning 0) 1)
6731 (error 1))))
6732 (next-level (save-excursion
6733 (condition-case nil
6734 (progn
6735 (or (looking-at outline-regexp)
6736 (outline-next-visible-heading 1))
6737 (if (looking-at re)
6738 (- (match-end 0) (match-beginning 0) 1)
6740 (error 1))))
6741 (new-level (or force-level (max previous-level next-level)))
6742 (shift (if (or (= old-level -1)
6743 (= new-level -1)
6744 (= old-level new-level))
6746 (- new-level old-level)))
6747 (delta (if (> shift 0) -1 1))
6748 (func (if (> shift 0) 'org-demote 'org-promote))
6749 (org-odd-levels-only nil)
6750 beg end)
6751 ;; Remove the forced level indicator
6752 (if force-level
6753 (delete-region (point-at-bol) (point)))
6754 ;; Paste
6755 (beginning-of-line 1)
6756 (org-back-over-empty-lines) ;; FIXME: correct fix????
6757 (setq beg (point))
6758 (insert-before-markers txt) ;; FIXME: correct fix????
6759 (unless (string-match "\n\\'" txt) (insert "\n"))
6760 (setq end (point))
6761 (goto-char beg)
6762 (skip-chars-forward " \t\n\r")
6763 (setq beg (point))
6764 ;; Shift if necessary
6765 (unless (= shift 0)
6766 (save-restriction
6767 (narrow-to-region beg end)
6768 (while (not (= shift 0))
6769 (org-map-region func (point-min) (point-max))
6770 (setq shift (+ delta shift)))
6771 (goto-char (point-min))))
6772 (when (interactive-p)
6773 (message "Clipboard pasted as level %d subtree" new-level))
6774 (if (and kill-ring
6775 (eq org-subtree-clip (current-kill 0))
6776 org-subtree-clip-folded)
6777 ;; The tree was folded before it was killed/copied
6778 (hide-subtree))))
6780 (defun org-kill-is-subtree-p (&optional txt)
6781 "Check if the current kill is an outline subtree, or a set of trees.
6782 Returns nil if kill does not start with a headline, or if the first
6783 headline level is not the largest headline level in the tree.
6784 So this will actually accept several entries of equal levels as well,
6785 which is OK for `org-paste-subtree'.
6786 If optional TXT is given, check this string instead of the current kill."
6787 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
6788 (start-level (and kill
6789 (string-match (concat "\\`\\([ \t\n\r]*?\n\\)?\\("
6790 org-outline-regexp "\\)")
6791 kill)
6792 (- (match-end 2) (match-beginning 2) 1)))
6793 (re (concat "^" org-outline-regexp))
6794 (start (1+ (match-beginning 2))))
6795 (if (not start-level)
6796 (progn
6797 nil) ;; does not even start with a heading
6798 (catch 'exit
6799 (while (setq start (string-match re kill (1+ start)))
6800 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
6801 (throw 'exit nil)))
6802 t))))
6804 (defun org-narrow-to-subtree ()
6805 "Narrow buffer to the current subtree."
6806 (interactive)
6807 (save-excursion
6808 (save-match-data
6809 (narrow-to-region
6810 (progn (org-back-to-heading) (point))
6811 (progn (org-end-of-subtree t t) (point))))))
6814 ;;; Outline Sorting
6816 (defun org-sort (with-case)
6817 "Call `org-sort-entries-or-items' or `org-table-sort-lines'.
6818 Optional argument WITH-CASE means sort case-sensitively."
6819 (interactive "P")
6820 (if (org-at-table-p)
6821 (org-call-with-arg 'org-table-sort-lines with-case)
6822 (org-call-with-arg 'org-sort-entries-or-items with-case)))
6824 (defvar org-priority-regexp) ; defined later in the file
6826 (defun org-sort-entries-or-items (&optional with-case sorting-type getkey-func property)
6827 "Sort entries on a certain level of an outline tree.
6828 If there is an active region, the entries in the region are sorted.
6829 Else, if the cursor is before the first entry, sort the top-level items.
6830 Else, the children of the entry at point are sorted.
6832 Sorting can be alphabetically, numerically, and by date/time as given by
6833 the first time stamp in the entry. The command prompts for the sorting
6834 type unless it has been given to the function through the SORTING-TYPE
6835 argument, which needs to a character, any of (?n ?N ?a ?A ?t ?T ?p ?P ?f ?F).
6836 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
6837 called with point at the beginning of the record. It must return either
6838 a string or a number that should serve as the sorting key for that record.
6840 Comparing entries ignores case by default. However, with an optional argument
6841 WITH-CASE, the sorting considers case as well."
6842 (interactive "P")
6843 (let ((case-func (if with-case 'identity 'downcase))
6844 start beg end stars re re2
6845 txt what tmp plain-list-p)
6846 ;; Find beginning and end of region to sort
6847 (cond
6848 ((org-region-active-p)
6849 ;; we will sort the region
6850 (setq end (region-end)
6851 what "region")
6852 (goto-char (region-beginning))
6853 (if (not (org-on-heading-p)) (outline-next-heading))
6854 (setq start (point)))
6855 ((org-at-item-p)
6856 ;; we will sort this plain list
6857 (org-beginning-of-item-list) (setq start (point))
6858 (org-end-of-item-list) (setq end (point))
6859 (goto-char start)
6860 (setq plain-list-p t
6861 what "plain list"))
6862 ((or (org-on-heading-p)
6863 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
6864 ;; we will sort the children of the current headline
6865 (org-back-to-heading)
6866 (setq start (point)
6867 end (progn (org-end-of-subtree t t)
6868 (org-back-over-empty-lines)
6869 (point))
6870 what "children")
6871 (goto-char start)
6872 (show-subtree)
6873 (outline-next-heading))
6875 ;; we will sort the top-level entries in this file
6876 (goto-char (point-min))
6877 (or (org-on-heading-p) (outline-next-heading))
6878 (setq start (point) end (point-max) what "top-level")
6879 (goto-char start)
6880 (show-all)))
6882 (setq beg (point))
6883 (if (>= beg end) (error "Nothing to sort"))
6885 (unless plain-list-p
6886 (looking-at "\\(\\*+\\)")
6887 (setq stars (match-string 1)
6888 re (concat "^" (regexp-quote stars) " +")
6889 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[^*]")
6890 txt (buffer-substring beg end))
6891 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
6892 (if (and (not (equal stars "*")) (string-match re2 txt))
6893 (error "Region to sort contains a level above the first entry")))
6895 (unless sorting-type
6896 (message
6897 (if plain-list-p
6898 "Sort %s: [a]lpha [n]umeric [t]ime [f]unc A/N/T/F means reversed:"
6899 "Sort %s: [a]lpha [n]umeric [t]ime [p]riority p[r]operty [f]unc A/N/T/P/F means reversed:")
6900 what)
6901 (setq sorting-type (read-char-exclusive))
6903 (and (= (downcase sorting-type) ?f)
6904 (setq getkey-func
6905 (completing-read "Sort using function: "
6906 obarray 'fboundp t nil nil))
6907 (setq getkey-func (intern getkey-func)))
6909 (and (= (downcase sorting-type) ?r)
6910 (setq property
6911 (completing-read "Property: "
6912 (mapcar 'list (org-buffer-property-keys t))
6913 nil t))))
6915 (message "Sorting entries...")
6917 (save-restriction
6918 (narrow-to-region start end)
6920 (let ((dcst (downcase sorting-type))
6921 (now (current-time)))
6922 (sort-subr
6923 (/= dcst sorting-type)
6924 ;; This function moves to the beginning character of the "record" to
6925 ;; be sorted.
6926 (if plain-list-p
6927 (lambda nil
6928 (if (org-at-item-p) t (goto-char (point-max))))
6929 (lambda nil
6930 (if (re-search-forward re nil t)
6931 (goto-char (match-beginning 0))
6932 (goto-char (point-max)))))
6933 ;; This function moves to the last character of the "record" being
6934 ;; sorted.
6935 (if plain-list-p
6936 'org-end-of-item
6937 (lambda nil
6938 (save-match-data
6939 (condition-case nil
6940 (outline-forward-same-level 1)
6941 (error
6942 (goto-char (point-max)))))))
6944 ;; This function returns the value that gets sorted against.
6945 (if plain-list-p
6946 (lambda nil
6947 (when (looking-at "[ \t]*[-+*0-9.)]+[ \t]+")
6948 (cond
6949 ((= dcst ?n)
6950 (string-to-number (buffer-substring (match-end 0)
6951 (point-at-eol))))
6952 ((= dcst ?a)
6953 (buffer-substring (match-end 0) (point-at-eol)))
6954 ((= dcst ?t)
6955 (if (re-search-forward org-ts-regexp
6956 (point-at-eol) t)
6957 (org-time-string-to-time (match-string 0))
6958 now))
6959 ((= dcst ?f)
6960 (if getkey-func
6961 (progn
6962 (setq tmp (funcall getkey-func))
6963 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
6964 tmp)
6965 (error "Invalid key function `%s'" getkey-func)))
6966 (t (error "Invalid sorting type `%c'" sorting-type)))))
6967 (lambda nil
6968 (cond
6969 ((= dcst ?n)
6970 (if (looking-at outline-regexp)
6971 (string-to-number (buffer-substring (match-end 0)
6972 (point-at-eol)))
6973 nil))
6974 ((= dcst ?a)
6975 (funcall case-func (buffer-substring (point-at-bol)
6976 (point-at-eol))))
6977 ((= dcst ?t)
6978 (if (re-search-forward org-ts-regexp
6979 (save-excursion
6980 (forward-line 2)
6981 (point)) t)
6982 (org-time-string-to-time (match-string 0))
6983 now))
6984 ((= dcst ?p)
6985 (if (re-search-forward org-priority-regexp (point-at-eol) t)
6986 (string-to-char (match-string 2))
6987 org-default-priority))
6988 ((= dcst ?r)
6989 (or (org-entry-get nil property) ""))
6990 ((= dcst ?f)
6991 (if getkey-func
6992 (progn
6993 (setq tmp (funcall getkey-func))
6994 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
6995 tmp)
6996 (error "Invalid key function `%s'" getkey-func)))
6997 (t (error "Invalid sorting type `%c'" sorting-type)))))
6999 (cond
7000 ((= dcst ?a) 'string<)
7001 ((= dcst ?t) 'time-less-p)
7002 (t nil)))))
7003 (message "Sorting entries...done")))
7005 (defun org-do-sort (table what &optional with-case sorting-type)
7006 "Sort TABLE of WHAT according to SORTING-TYPE.
7007 The user will be prompted for the SORTING-TYPE if the call to this
7008 function does not specify it. WHAT is only for the prompt, to indicate
7009 what is being sorted. The sorting key will be extracted from
7010 the car of the elements of the table.
7011 If WITH-CASE is non-nil, the sorting will be case-sensitive."
7012 (unless sorting-type
7013 (message
7014 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
7015 what)
7016 (setq sorting-type (read-char-exclusive)))
7017 (let ((dcst (downcase sorting-type))
7018 extractfun comparefun)
7019 ;; Define the appropriate functions
7020 (cond
7021 ((= dcst ?n)
7022 (setq extractfun 'string-to-number
7023 comparefun (if (= dcst sorting-type) '< '>)))
7024 ((= dcst ?a)
7025 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
7026 (lambda(x) (downcase (org-sort-remove-invisible x))))
7027 comparefun (if (= dcst sorting-type)
7028 'string<
7029 (lambda (a b) (and (not (string< a b))
7030 (not (string= a b)))))))
7031 ((= dcst ?t)
7032 (setq extractfun
7033 (lambda (x)
7034 (if (string-match org-ts-regexp x)
7035 (time-to-seconds
7036 (org-time-string-to-time (match-string 0 x)))
7038 comparefun (if (= dcst sorting-type) '< '>)))
7039 (t (error "Invalid sorting type `%c'" sorting-type)))
7041 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
7042 table)
7043 (lambda (a b) (funcall comparefun (car a) (car b))))))
7045 ;;;; Plain list items, including checkboxes
7047 ;;; Plain list items
7049 (defun org-at-item-p ()
7050 "Is point in a line starting a hand-formatted item?"
7051 (let ((llt org-plain-list-ordered-item-terminator))
7052 (save-excursion
7053 (goto-char (point-at-bol))
7054 (looking-at
7055 (cond
7056 ((eq llt t) "\\([ \t]*\\([-+]\\|\\([0-9]+[.)]\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
7057 ((= llt ?.) "\\([ \t]*\\([-+]\\|\\([0-9]+\\.\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
7058 ((= llt ?\)) "\\([ \t]*\\([-+]\\|\\([0-9]+))\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
7059 (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))))))
7061 (defun org-in-item-p ()
7062 "It the cursor inside a plain list item.
7063 Does not have to be the first line."
7064 (save-excursion
7065 (condition-case nil
7066 (progn
7067 (org-beginning-of-item)
7068 (org-at-item-p)
7070 (error nil))))
7072 (defun org-insert-item (&optional checkbox)
7073 "Insert a new item at the current level.
7074 Return t when things worked, nil when we are not in an item."
7075 (when (save-excursion
7076 (condition-case nil
7077 (progn
7078 (org-beginning-of-item)
7079 (org-at-item-p)
7080 (if (org-invisible-p) (error "Invisible item"))
7082 (error nil)))
7083 (let* ((bul (match-string 0))
7084 (eow (save-excursion (beginning-of-line 1) (looking-at "[ \t]*")
7085 (match-end 0)))
7086 (blank (cdr (assq 'plain-list-item org-blank-before-new-entry)))
7087 pos)
7088 (cond
7089 ((and (org-at-item-p) (<= (point) eow))
7090 ;; before the bullet
7091 (beginning-of-line 1)
7092 (open-line (if blank 2 1)))
7093 ((<= (point) eow)
7094 (beginning-of-line 1))
7096 (unless (org-get-alist-option org-M-RET-may-split-line 'item)
7097 (end-of-line 1)
7098 (delete-horizontal-space))
7099 (newline (if blank 2 1))))
7100 (insert bul (if checkbox "[ ]" ""))
7101 (just-one-space)
7102 (setq pos (point))
7103 (end-of-line 1)
7104 (unless (= (point) pos) (just-one-space) (backward-delete-char 1)))
7105 (org-maybe-renumber-ordered-list)
7106 (and checkbox (org-update-checkbox-count-maybe))
7109 ;;; Checkboxes
7111 (defun org-at-item-checkbox-p ()
7112 "Is point at a line starting a plain-list item with a checklet?"
7113 (and (org-at-item-p)
7114 (save-excursion
7115 (goto-char (match-end 0))
7116 (skip-chars-forward " \t")
7117 (looking-at "\\[[- X]\\]"))))
7119 (defun org-toggle-checkbox (&optional arg)
7120 "Toggle the checkbox in the current line."
7121 (interactive "P")
7122 (catch 'exit
7123 (let (beg end status (firstnew 'unknown))
7124 (cond
7125 ((org-region-active-p)
7126 (setq beg (region-beginning) end (region-end)))
7127 ((org-on-heading-p)
7128 (setq beg (point) end (save-excursion (outline-next-heading) (point))))
7129 ((org-at-item-checkbox-p)
7130 (let ((pos (point)))
7131 (replace-match
7132 (cond (arg "[-]")
7133 ((member (match-string 0) '("[ ]" "[-]")) "[X]")
7134 (t "[ ]"))
7135 t t)
7136 (goto-char pos))
7137 (throw 'exit t))
7138 (t (error "Not at a checkbox or heading, and no active region")))
7139 (save-excursion
7140 (goto-char beg)
7141 (while (< (point) end)
7142 (when (org-at-item-checkbox-p)
7143 (setq status (equal (match-string 0) "[X]"))
7144 (when (eq firstnew 'unknown)
7145 (setq firstnew (not status)))
7146 (replace-match
7147 (if (if arg (not status) firstnew) "[X]" "[ ]") t t))
7148 (beginning-of-line 2)))))
7149 (org-update-checkbox-count-maybe))
7151 (defun org-update-checkbox-count-maybe ()
7152 "Update checkbox statistics unless turned off by user."
7153 (when org-provide-checkbox-statistics
7154 (org-update-checkbox-count)))
7156 (defun org-update-checkbox-count (&optional all)
7157 "Update the checkbox statistics in the current section.
7158 This will find all statistic cookies like [57%] and [6/12] and update them
7159 with the current numbers. With optional prefix argument ALL, do this for
7160 the whole buffer."
7161 (interactive "P")
7162 (save-excursion
7163 (let* ((buffer-invisibility-spec (org-inhibit-invisibility)) ; Emacs 21
7164 (beg (condition-case nil
7165 (progn (outline-back-to-heading) (point))
7166 (error (point-min))))
7167 (end (move-marker (make-marker)
7168 (progn (outline-next-heading) (point))))
7169 (re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
7170 (re-box "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)")
7171 (re-find (concat re "\\|" re-box))
7172 beg-cookie end-cookie is-percent c-on c-off lim
7173 eline curr-ind next-ind continue-from startsearch
7174 (cstat 0)
7176 (when all
7177 (goto-char (point-min))
7178 (outline-next-heading)
7179 (setq beg (point) end (point-max)))
7180 (goto-char end)
7181 ;; find each statistic cookie
7182 (while (re-search-backward re-find beg t)
7183 (setq beg-cookie (match-beginning 1)
7184 end-cookie (match-end 1)
7185 cstat (+ cstat (if end-cookie 1 0))
7186 startsearch (point-at-eol)
7187 continue-from (point-at-bol)
7188 is-percent (match-beginning 2)
7189 lim (cond
7190 ((org-on-heading-p) (outline-next-heading) (point))
7191 ((org-at-item-p) (org-end-of-item) (point))
7192 (t nil))
7193 c-on 0
7194 c-off 0)
7195 (when lim
7196 ;; find first checkbox for this cookie and gather
7197 ;; statistics from all that are at this indentation level
7198 (goto-char startsearch)
7199 (if (re-search-forward re-box lim t)
7200 (progn
7201 (org-beginning-of-item)
7202 (setq curr-ind (org-get-indentation))
7203 (setq next-ind curr-ind)
7204 (while (= curr-ind next-ind)
7205 (save-excursion (end-of-line) (setq eline (point)))
7206 (if (re-search-forward re-box eline t)
7207 (if (member (match-string 2) '("[ ]" "[-]"))
7208 (setq c-off (1+ c-off))
7209 (setq c-on (1+ c-on))
7212 (org-end-of-item)
7213 (setq next-ind (org-get-indentation))
7215 (goto-char continue-from)
7216 ;; update cookie
7217 (when end-cookie
7218 (delete-region beg-cookie end-cookie)
7219 (goto-char beg-cookie)
7220 (insert
7221 (if is-percent
7222 (format "[%d%%]" (/ (* 100 c-on) (max 1 (+ c-on c-off))))
7223 (format "[%d/%d]" c-on (+ c-on c-off)))))
7224 ;; update items checkbox if it has one
7225 (when (org-at-item-p)
7226 (org-beginning-of-item)
7227 (when (and (> (+ c-on c-off) 0)
7228 (re-search-forward re-box (point-at-eol) t))
7229 (setq beg-cookie (match-beginning 2)
7230 end-cookie (match-end 2))
7231 (delete-region beg-cookie end-cookie)
7232 (goto-char beg-cookie)
7233 (cond ((= c-off 0) (insert "[X]"))
7234 ((= c-on 0) (insert "[ ]"))
7235 (t (insert "[-]")))
7237 (goto-char continue-from))
7238 (when (interactive-p)
7239 (message "Checkbox satistics updated %s (%d places)"
7240 (if all "in entire file" "in current outline entry") cstat)))))
7242 (defun org-get-checkbox-statistics-face ()
7243 "Select the face for checkbox statistics.
7244 The face will be `org-done' when all relevant boxes are checked. Otherwise
7245 it will be `org-todo'."
7246 (if (match-end 1)
7247 (if (equal (match-string 1) "100%") 'org-done 'org-todo)
7248 (if (and (> (match-end 2) (match-beginning 2))
7249 (equal (match-string 2) (match-string 3)))
7250 'org-done
7251 'org-todo)))
7253 (defun org-get-indentation (&optional line)
7254 "Get the indentation of the current line, interpreting tabs.
7255 When LINE is given, assume it represents a line and compute its indentation."
7256 (if line
7257 (if (string-match "^ *" (org-remove-tabs line))
7258 (match-end 0))
7259 (save-excursion
7260 (beginning-of-line 1)
7261 (skip-chars-forward " \t")
7262 (current-column))))
7264 (defun org-remove-tabs (s &optional width)
7265 "Replace tabulators in S with spaces.
7266 Assumes that s is a single line, starting in column 0."
7267 (setq width (or width tab-width))
7268 (while (string-match "\t" s)
7269 (setq s (replace-match
7270 (make-string
7271 (- (* width (/ (+ (match-beginning 0) width) width))
7272 (match-beginning 0)) ?\ )
7273 t t s)))
7276 (defun org-fix-indentation (line ind)
7277 "Fix indentation in LINE.
7278 IND is a cons cell with target and minimum indentation.
7279 If the current indenation in LINE is smaller than the minimum,
7280 leave it alone. If it is larger than ind, set it to the target."
7281 (let* ((l (org-remove-tabs line))
7282 (i (org-get-indentation l))
7283 (i1 (car ind)) (i2 (cdr ind)))
7284 (if (>= i i2) (setq l (substring line i2)))
7285 (if (> i1 0)
7286 (concat (make-string i1 ?\ ) l)
7287 l)))
7289 (defcustom org-empty-line-terminates-plain-lists nil
7290 "Non-nil means, an empty line ends all plain list levels.
7291 When nil, empty lines are part of the preceeding item."
7292 :group 'org-plain-lists
7293 :type 'boolean)
7295 (defun org-beginning-of-item ()
7296 "Go to the beginning of the current hand-formatted item.
7297 If the cursor is not in an item, throw an error."
7298 (interactive)
7299 (let ((pos (point))
7300 (limit (save-excursion
7301 (condition-case nil
7302 (progn
7303 (org-back-to-heading)
7304 (beginning-of-line 2) (point))
7305 (error (point-min)))))
7306 (ind-empty (if org-empty-line-terminates-plain-lists 0 10000))
7307 ind ind1)
7308 (if (org-at-item-p)
7309 (beginning-of-line 1)
7310 (beginning-of-line 1)
7311 (skip-chars-forward " \t")
7312 (setq ind (current-column))
7313 (if (catch 'exit
7314 (while t
7315 (beginning-of-line 0)
7316 (if (or (bobp) (< (point) limit)) (throw 'exit nil))
7318 (if (looking-at "[ \t]*$")
7319 (setq ind1 ind-empty)
7320 (skip-chars-forward " \t")
7321 (setq ind1 (current-column)))
7322 (if (< ind1 ind)
7323 (progn (beginning-of-line 1) (throw 'exit (org-at-item-p))))))
7325 (goto-char pos)
7326 (error "Not in an item")))))
7328 (defun org-end-of-item ()
7329 "Go to the end of the current hand-formatted item.
7330 If the cursor is not in an item, throw an error."
7331 (interactive)
7332 (let* ((pos (point))
7333 ind1
7334 (ind-empty (if org-empty-line-terminates-plain-lists 0 10000))
7335 (limit (save-excursion (outline-next-heading) (point)))
7336 (ind (save-excursion
7337 (org-beginning-of-item)
7338 (skip-chars-forward " \t")
7339 (current-column)))
7340 (end (catch 'exit
7341 (while t
7342 (beginning-of-line 2)
7343 (if (eobp) (throw 'exit (point)))
7344 (if (>= (point) limit) (throw 'exit (point-at-bol)))
7345 (if (looking-at "[ \t]*$")
7346 (setq ind1 ind-empty)
7347 (skip-chars-forward " \t")
7348 (setq ind1 (current-column)))
7349 (if (<= ind1 ind)
7350 (throw 'exit (point-at-bol)))))))
7351 (if end
7352 (goto-char end)
7353 (goto-char pos)
7354 (error "Not in an item"))))
7356 (defun org-next-item ()
7357 "Move to the beginning of the next item in the current plain list.
7358 Error if not at a plain list, or if this is the last item in the list."
7359 (interactive)
7360 (let (ind ind1 (pos (point)))
7361 (org-beginning-of-item)
7362 (setq ind (org-get-indentation))
7363 (org-end-of-item)
7364 (setq ind1 (org-get-indentation))
7365 (unless (and (org-at-item-p) (= ind ind1))
7366 (goto-char pos)
7367 (error "On last item"))))
7369 (defun org-previous-item ()
7370 "Move to the beginning of the previous item in the current plain list.
7371 Error if not at a plain list, or if this is the first item in the list."
7372 (interactive)
7373 (let (beg ind ind1 (pos (point)))
7374 (org-beginning-of-item)
7375 (setq beg (point))
7376 (setq ind (org-get-indentation))
7377 (goto-char beg)
7378 (catch 'exit
7379 (while t
7380 (beginning-of-line 0)
7381 (if (looking-at "[ \t]*$")
7383 (if (<= (setq ind1 (org-get-indentation)) ind)
7384 (throw 'exit t)))))
7385 (condition-case nil
7386 (if (or (not (org-at-item-p))
7387 (< ind1 (1- ind)))
7388 (error "")
7389 (org-beginning-of-item))
7390 (error (goto-char pos)
7391 (error "On first item")))))
7393 (defun org-first-list-item-p ()
7394 "Is this heading the item in a plain list?"
7395 (unless (org-at-item-p)
7396 (error "Not at a plain list item"))
7397 (org-beginning-of-item)
7398 (= (point) (save-excursion (org-beginning-of-item-list))))
7400 (defun org-move-item-down ()
7401 "Move the plain list item at point down, i.e. swap with following item.
7402 Subitems (items with larger indentation) are considered part of the item,
7403 so this really moves item trees."
7404 (interactive)
7405 (let (beg beg0 end end0 ind ind1 (pos (point)) txt ne-end ne-beg)
7406 (org-beginning-of-item)
7407 (setq beg0 (point))
7408 (save-excursion
7409 (setq ne-beg (org-back-over-empty-lines))
7410 (setq beg (point)))
7411 (goto-char beg0)
7412 (setq ind (org-get-indentation))
7413 (org-end-of-item)
7414 (setq end0 (point))
7415 (setq ind1 (org-get-indentation))
7416 (setq ne-end (org-back-over-empty-lines))
7417 (setq end (point))
7418 (goto-char beg0)
7419 (when (and (org-first-list-item-p) (< ne-end ne-beg))
7420 ;; include less whitespace
7421 (save-excursion
7422 (goto-char beg)
7423 (forward-line (- ne-beg ne-end))
7424 (setq beg (point))))
7425 (goto-char end0)
7426 (if (and (org-at-item-p) (= ind ind1))
7427 (progn
7428 (org-end-of-item)
7429 (org-back-over-empty-lines)
7430 (setq txt (buffer-substring beg end))
7431 (save-excursion
7432 (delete-region beg end))
7433 (setq pos (point))
7434 (insert txt)
7435 (goto-char pos) (org-skip-whitespace)
7436 (org-maybe-renumber-ordered-list))
7437 (goto-char pos)
7438 (error "Cannot move this item further down"))))
7440 (defun org-move-item-up (arg)
7441 "Move the plain list item at point up, i.e. swap with previous item.
7442 Subitems (items with larger indentation) are considered part of the item,
7443 so this really moves item trees."
7444 (interactive "p")
7445 (let (beg beg0 end ind ind1 (pos (point)) txt
7446 ne-beg ne-ins ins-end)
7447 (org-beginning-of-item)
7448 (setq beg0 (point))
7449 (setq ind (org-get-indentation))
7450 (save-excursion
7451 (setq ne-beg (org-back-over-empty-lines))
7452 (setq beg (point)))
7453 (goto-char beg0)
7454 (org-end-of-item)
7455 (setq end (point))
7456 (goto-char beg0)
7457 (catch 'exit
7458 (while t
7459 (beginning-of-line 0)
7460 (if (looking-at "[ \t]*$")
7461 (if org-empty-line-terminates-plain-lists
7462 (progn
7463 (goto-char pos)
7464 (error "Cannot move this item further up"))
7465 nil)
7466 (if (<= (setq ind1 (org-get-indentation)) ind)
7467 (throw 'exit t)))))
7468 (condition-case nil
7469 (org-beginning-of-item)
7470 (error (goto-char beg)
7471 (error "Cannot move this item further up")))
7472 (setq ind1 (org-get-indentation))
7473 (if (and (org-at-item-p) (= ind ind1))
7474 (progn
7475 (setq ne-ins (org-back-over-empty-lines))
7476 (setq txt (buffer-substring beg end))
7477 (save-excursion
7478 (delete-region beg end))
7479 (setq pos (point))
7480 (insert txt)
7481 (setq ins-end (point))
7482 (goto-char pos) (org-skip-whitespace)
7484 (when (and (org-first-list-item-p) (> ne-ins ne-beg))
7485 ;; Move whitespace back to beginning
7486 (save-excursion
7487 (goto-char ins-end)
7488 (let ((kill-whole-line t))
7489 (kill-line (- ne-ins ne-beg)) (point)))
7490 (insert (make-string (- ne-ins ne-beg) ?\n)))
7492 (org-maybe-renumber-ordered-list))
7493 (goto-char pos)
7494 (error "Cannot move this item further up"))))
7496 (defun org-maybe-renumber-ordered-list ()
7497 "Renumber the ordered list at point if setup allows it.
7498 This tests the user option `org-auto-renumber-ordered-lists' before
7499 doing the renumbering."
7500 (interactive)
7501 (when (and org-auto-renumber-ordered-lists
7502 (org-at-item-p))
7503 (if (match-beginning 3)
7504 (org-renumber-ordered-list 1)
7505 (org-fix-bullet-type))))
7507 (defun org-maybe-renumber-ordered-list-safe ()
7508 (condition-case nil
7509 (save-excursion
7510 (org-maybe-renumber-ordered-list))
7511 (error nil)))
7513 (defun org-cycle-list-bullet (&optional which)
7514 "Cycle through the different itemize/enumerate bullets.
7515 This cycle the entire list level through the sequence:
7517 `-' -> `+' -> `*' -> `1.' -> `1)'
7519 If WHICH is a string, use that as the new bullet. If WHICH is an integer,
7520 0 meand `-', 1 means `+' etc."
7521 (interactive "P")
7522 (org-preserve-lc
7523 (org-beginning-of-item-list)
7524 (org-at-item-p)
7525 (beginning-of-line 1)
7526 (let ((current (match-string 0))
7527 (prevp (eq which 'previous))
7528 new)
7529 (setq new (cond
7530 ((and (numberp which)
7531 (nth (1- which) '("-" "+" "*" "1." "1)"))))
7532 ((string-match "-" current) (if prevp "1)" "+"))
7533 ((string-match "\\+" current)
7534 (if prevp "-" (if (looking-at "\\S-") "1." "*")))
7535 ((string-match "\\*" current) (if prevp "+" "1."))
7536 ((string-match "\\." current) (if prevp "*" "1)"))
7537 ((string-match ")" current) (if prevp "1." "-"))
7538 (t (error "This should not happen"))))
7539 (and (looking-at "\\([ \t]*\\)\\S-+") (replace-match (concat "\\1" new)))
7540 (org-fix-bullet-type)
7541 (org-maybe-renumber-ordered-list))))
7543 (defun org-get-string-indentation (s)
7544 "What indentation has S due to SPACE and TAB at the beginning of the string?"
7545 (let ((n -1) (i 0) (w tab-width) c)
7546 (catch 'exit
7547 (while (< (setq n (1+ n)) (length s))
7548 (setq c (aref s n))
7549 (cond ((= c ?\ ) (setq i (1+ i)))
7550 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
7551 (t (throw 'exit t)))))
7554 (defun org-renumber-ordered-list (arg)
7555 "Renumber an ordered plain list.
7556 Cursor needs to be in the first line of an item, the line that starts
7557 with something like \"1.\" or \"2)\"."
7558 (interactive "p")
7559 (unless (and (org-at-item-p)
7560 (match-beginning 3))
7561 (error "This is not an ordered list"))
7562 (let ((line (org-current-line))
7563 (col (current-column))
7564 (ind (org-get-string-indentation
7565 (buffer-substring (point-at-bol) (match-beginning 3))))
7566 ;; (term (substring (match-string 3) -1))
7567 ind1 (n (1- arg))
7568 fmt)
7569 ;; find where this list begins
7570 (org-beginning-of-item-list)
7571 (looking-at "[ \t]*[0-9]+\\([.)]\\)")
7572 (setq fmt (concat "%d" (match-string 1)))
7573 (beginning-of-line 0)
7574 ;; walk forward and replace these numbers
7575 (catch 'exit
7576 (while t
7577 (catch 'next
7578 (beginning-of-line 2)
7579 (if (eobp) (throw 'exit nil))
7580 (if (looking-at "[ \t]*$") (throw 'next nil))
7581 (skip-chars-forward " \t") (setq ind1 (current-column))
7582 (if (> ind1 ind) (throw 'next t))
7583 (if (< ind1 ind) (throw 'exit t))
7584 (if (not (org-at-item-p)) (throw 'exit nil))
7585 (delete-region (match-beginning 2) (match-end 2))
7586 (goto-char (match-beginning 2))
7587 (insert (format fmt (setq n (1+ n)))))))
7588 (goto-line line)
7589 (move-to-column col)))
7591 (defun org-fix-bullet-type ()
7592 "Make sure all items in this list have the same bullet as the firsst item."
7593 (interactive)
7594 (unless (org-at-item-p) (error "This is not a list"))
7595 (let ((line (org-current-line))
7596 (col (current-column))
7597 (ind (current-indentation))
7598 ind1 bullet)
7599 ;; find where this list begins
7600 (org-beginning-of-item-list)
7601 (beginning-of-line 1)
7602 ;; find out what the bullet type is
7603 (looking-at "[ \t]*\\(\\S-+\\)")
7604 (setq bullet (match-string 1))
7605 ;; walk forward and replace these numbers
7606 (beginning-of-line 0)
7607 (catch 'exit
7608 (while t
7609 (catch 'next
7610 (beginning-of-line 2)
7611 (if (eobp) (throw 'exit nil))
7612 (if (looking-at "[ \t]*$") (throw 'next nil))
7613 (skip-chars-forward " \t") (setq ind1 (current-column))
7614 (if (> ind1 ind) (throw 'next t))
7615 (if (< ind1 ind) (throw 'exit t))
7616 (if (not (org-at-item-p)) (throw 'exit nil))
7617 (skip-chars-forward " \t")
7618 (looking-at "\\S-+")
7619 (replace-match bullet))))
7620 (goto-line line)
7621 (move-to-column col)
7622 (if (string-match "[0-9]" bullet)
7623 (org-renumber-ordered-list 1))))
7625 (defun org-beginning-of-item-list ()
7626 "Go to the beginning of the current item list.
7627 I.e. to the first item in this list."
7628 (interactive)
7629 (org-beginning-of-item)
7630 (let ((pos (point-at-bol))
7631 (ind (org-get-indentation))
7632 ind1)
7633 ;; find where this list begins
7634 (catch 'exit
7635 (while t
7636 (catch 'next
7637 (beginning-of-line 0)
7638 (if (looking-at "[ \t]*$")
7639 (throw (if (bobp) 'exit 'next) t))
7640 (skip-chars-forward " \t") (setq ind1 (current-column))
7641 (if (or (< ind1 ind)
7642 (and (= ind1 ind)
7643 (not (org-at-item-p)))
7644 (bobp))
7645 (throw 'exit t)
7646 (when (org-at-item-p) (setq pos (point-at-bol)))))))
7647 (goto-char pos)))
7650 (defun org-end-of-item-list ()
7651 "Go to the end of the current item list.
7652 I.e. to the text after the last item."
7653 (interactive)
7654 (org-beginning-of-item)
7655 (let ((pos (point-at-bol))
7656 (ind (org-get-indentation))
7657 ind1)
7658 ;; find where this list begins
7659 (catch 'exit
7660 (while t
7661 (catch 'next
7662 (beginning-of-line 2)
7663 (if (looking-at "[ \t]*$")
7664 (throw (if (eobp) 'exit 'next) t))
7665 (skip-chars-forward " \t") (setq ind1 (current-column))
7666 (if (or (< ind1 ind)
7667 (and (= ind1 ind)
7668 (not (org-at-item-p)))
7669 (eobp))
7670 (progn
7671 (setq pos (point-at-bol))
7672 (throw 'exit t))))))
7673 (goto-char pos)))
7676 (defvar org-last-indent-begin-marker (make-marker))
7677 (defvar org-last-indent-end-marker (make-marker))
7679 (defun org-outdent-item (arg)
7680 "Outdent a local list item."
7681 (interactive "p")
7682 (org-indent-item (- arg)))
7684 (defun org-indent-item (arg)
7685 "Indent a local list item."
7686 (interactive "p")
7687 (unless (org-at-item-p)
7688 (error "Not on an item"))
7689 (save-excursion
7690 (let (beg end ind ind1 tmp delta ind-down ind-up)
7691 (if (memq last-command '(org-shiftmetaright org-shiftmetaleft))
7692 (setq beg org-last-indent-begin-marker
7693 end org-last-indent-end-marker)
7694 (org-beginning-of-item)
7695 (setq beg (move-marker org-last-indent-begin-marker (point)))
7696 (org-end-of-item)
7697 (setq end (move-marker org-last-indent-end-marker (point))))
7698 (goto-char beg)
7699 (setq tmp (org-item-indent-positions)
7700 ind (car tmp)
7701 ind-down (nth 2 tmp)
7702 ind-up (nth 1 tmp)
7703 delta (if (> arg 0)
7704 (if ind-down (- ind-down ind) 2)
7705 (if ind-up (- ind-up ind) -2)))
7706 (if (< (+ delta ind) 0) (error "Cannot outdent beyond margin"))
7707 (while (< (point) end)
7708 (beginning-of-line 1)
7709 (skip-chars-forward " \t") (setq ind1 (current-column))
7710 (delete-region (point-at-bol) (point))
7711 (or (eolp) (indent-to-column (+ ind1 delta)))
7712 (beginning-of-line 2))))
7713 (org-fix-bullet-type)
7714 (org-maybe-renumber-ordered-list-safe)
7715 (save-excursion
7716 (beginning-of-line 0)
7717 (condition-case nil (org-beginning-of-item) (error nil))
7718 (org-maybe-renumber-ordered-list-safe)))
7720 (defun org-item-indent-positions ()
7721 "Return indentation for plain list items.
7722 This returns a list with three values: The current indentation, the
7723 parent indentation and the indentation a child should habe.
7724 Assumes cursor in item line."
7725 (let* ((bolpos (point-at-bol))
7726 (ind (org-get-indentation))
7727 ind-down ind-up pos)
7728 (save-excursion
7729 (org-beginning-of-item-list)
7730 (skip-chars-backward "\n\r \t")
7731 (when (org-in-item-p)
7732 (org-beginning-of-item)
7733 (setq ind-up (org-get-indentation))))
7734 (setq pos (point))
7735 (save-excursion
7736 (cond
7737 ((and (condition-case nil (progn (org-previous-item) t)
7738 (error nil))
7739 (or (forward-char 1) t)
7740 (re-search-forward "^\\([ \t]*\\([-+]\\|\\([0-9]+[.)]\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)" bolpos t))
7741 (setq ind-down (org-get-indentation)))
7742 ((and (goto-char pos)
7743 (org-at-item-p))
7744 (goto-char (match-end 0))
7745 (skip-chars-forward " \t")
7746 (setq ind-down (current-column)))))
7747 (list ind ind-up ind-down)))
7749 ;;; The orgstruct minor mode
7751 ;; Define a minor mode which can be used in other modes in order to
7752 ;; integrate the org-mode structure editing commands.
7754 ;; This is really a hack, because the org-mode structure commands use
7755 ;; keys which normally belong to the major mode. Here is how it
7756 ;; works: The minor mode defines all the keys necessary to operate the
7757 ;; structure commands, but wraps the commands into a function which
7758 ;; tests if the cursor is currently at a headline or a plain list
7759 ;; item. If that is the case, the structure command is used,
7760 ;; temporarily setting many Org-mode variables like regular
7761 ;; expressions for filling etc. However, when any of those keys is
7762 ;; used at a different location, function uses `key-binding' to look
7763 ;; up if the key has an associated command in another currently active
7764 ;; keymap (minor modes, major mode, global), and executes that
7765 ;; command. There might be problems if any of the keys is otherwise
7766 ;; used as a prefix key.
7768 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
7769 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
7770 ;; addresses this by checking explicitly for both bindings.
7772 (defvar orgstruct-mode-map (make-sparse-keymap)
7773 "Keymap for the minor `orgstruct-mode'.")
7775 (defvar org-local-vars nil
7776 "List of local variables, for use by `orgstruct-mode'")
7778 ;;;###autoload
7779 (define-minor-mode orgstruct-mode
7780 "Toggle the minor more `orgstruct-mode'.
7781 This mode is for using Org-mode structure commands in other modes.
7782 The following key behave as if Org-mode was active, if the cursor
7783 is on a headline, or on a plain list item (both in the definition
7784 of Org-mode).
7786 M-up Move entry/item up
7787 M-down Move entry/item down
7788 M-left Promote
7789 M-right Demote
7790 M-S-up Move entry/item up
7791 M-S-down Move entry/item down
7792 M-S-left Promote subtree
7793 M-S-right Demote subtree
7794 M-q Fill paragraph and items like in Org-mode
7795 C-c ^ Sort entries
7796 C-c - Cycle list bullet
7797 TAB Cycle item visibility
7798 M-RET Insert new heading/item
7799 S-M-RET Insert new TODO heading / Chekbox item
7800 C-c C-c Set tags / toggle checkbox"
7801 nil " OrgStruct" nil
7802 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
7804 ;;;###autoload
7805 (defun turn-on-orgstruct ()
7806 "Unconditionally turn on `orgstruct-mode'."
7807 (orgstruct-mode 1))
7809 ;;;###autoload
7810 (defun turn-on-orgstruct++ ()
7811 "Unconditionally turn on `orgstruct-mode', and force org-mode indentations.
7812 In addition to setting orgstruct-mode, this also exports all indentation and
7813 autofilling variables from org-mode into the buffer. Note that turning
7814 off orgstruct-mode will *not* remove these additional settings."
7815 (orgstruct-mode 1)
7816 (let (var val)
7817 (mapc
7818 (lambda (x)
7819 (when (string-match
7820 "^\\(paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
7821 (symbol-name (car x)))
7822 (setq var (car x) val (nth 1 x))
7823 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
7824 org-local-vars)))
7826 (defun orgstruct-error ()
7827 "Error when there is no default binding for a structure key."
7828 (interactive)
7829 (error "This key has no function outside structure elements"))
7831 (defun orgstruct-setup ()
7832 "Setup orgstruct keymaps."
7833 (let ((nfunc 0)
7834 (bindings
7835 (list
7836 '([(meta up)] org-metaup)
7837 '([(meta down)] org-metadown)
7838 '([(meta left)] org-metaleft)
7839 '([(meta right)] org-metaright)
7840 '([(meta shift up)] org-shiftmetaup)
7841 '([(meta shift down)] org-shiftmetadown)
7842 '([(meta shift left)] org-shiftmetaleft)
7843 '([(meta shift right)] org-shiftmetaright)
7844 '([(shift up)] org-shiftup)
7845 '([(shift down)] org-shiftdown)
7846 '("\C-c\C-c" org-ctrl-c-ctrl-c)
7847 '("\M-q" fill-paragraph)
7848 '("\C-c^" org-sort)
7849 '("\C-c-" org-cycle-list-bullet)))
7850 elt key fun cmd)
7851 (while (setq elt (pop bindings))
7852 (setq nfunc (1+ nfunc))
7853 (setq key (org-key (car elt))
7854 fun (nth 1 elt)
7855 cmd (orgstruct-make-binding fun nfunc key))
7856 (org-defkey orgstruct-mode-map key cmd))
7858 ;; Special treatment needed for TAB and RET
7859 (org-defkey orgstruct-mode-map [(tab)]
7860 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
7861 (org-defkey orgstruct-mode-map "\C-i"
7862 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
7864 (org-defkey orgstruct-mode-map "\M-\C-m"
7865 (orgstruct-make-binding 'org-insert-heading 105
7866 "\M-\C-m" [(meta return)]))
7867 (org-defkey orgstruct-mode-map [(meta return)]
7868 (orgstruct-make-binding 'org-insert-heading 106
7869 [(meta return)] "\M-\C-m"))
7871 (org-defkey orgstruct-mode-map [(shift meta return)]
7872 (orgstruct-make-binding 'org-insert-todo-heading 107
7873 [(meta return)] "\M-\C-m"))
7875 (unless org-local-vars
7876 (setq org-local-vars (org-get-local-variables)))
7880 (defun orgstruct-make-binding (fun n &rest keys)
7881 "Create a function for binding in the structure minor mode.
7882 FUN is the command to call inside a table. N is used to create a unique
7883 command name. KEYS are keys that should be checked in for a command
7884 to execute outside of tables."
7885 (eval
7886 (list 'defun
7887 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
7888 '(arg)
7889 (concat "In Structure, run `" (symbol-name fun) "'.\n"
7890 "Outside of structure, run the binding of `"
7891 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
7892 "'.")
7893 '(interactive "p")
7894 (list 'if
7895 '(org-context-p 'headline 'item)
7896 (list 'org-run-like-in-org-mode (list 'quote fun))
7897 (list 'let '(orgstruct-mode)
7898 (list 'call-interactively
7899 (append '(or)
7900 (mapcar (lambda (k)
7901 (list 'key-binding k))
7902 keys)
7903 '('orgstruct-error))))))))
7905 (defun org-context-p (&rest contexts)
7906 "Check if local context is and of CONTEXTS.
7907 Possible values in the list of contexts are `table', `headline', and `item'."
7908 (let ((pos (point)))
7909 (goto-char (point-at-bol))
7910 (prog1 (or (and (memq 'table contexts)
7911 (looking-at "[ \t]*|"))
7912 (and (memq 'headline contexts)
7913 (looking-at "\\*+"))
7914 (and (memq 'item contexts)
7915 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)")))
7916 (goto-char pos))))
7918 (defun org-get-local-variables ()
7919 "Return a list of all local variables in an org-mode buffer."
7920 (let (varlist)
7921 (with-current-buffer (get-buffer-create "*Org tmp*")
7922 (erase-buffer)
7923 (org-mode)
7924 (setq varlist (buffer-local-variables)))
7925 (kill-buffer "*Org tmp*")
7926 (delq nil
7927 (mapcar
7928 (lambda (x)
7929 (setq x
7930 (if (symbolp x)
7931 (list x)
7932 (list (car x) (list 'quote (cdr x)))))
7933 (if (string-match
7934 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
7935 (symbol-name (car x)))
7936 x nil))
7937 varlist))))
7939 ;;;###autoload
7940 (defun org-run-like-in-org-mode (cmd)
7941 (unless org-local-vars
7942 (setq org-local-vars (org-get-local-variables)))
7943 (eval (list 'let org-local-vars
7944 (list 'call-interactively (list 'quote cmd)))))
7946 ;;;; Archiving
7948 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
7950 (defun org-archive-subtree (&optional find-done)
7951 "Move the current subtree to the archive.
7952 The archive can be a certain top-level heading in the current file, or in
7953 a different file. The tree will be moved to that location, the subtree
7954 heading be marked DONE, and the current time will be added.
7956 When called with prefix argument FIND-DONE, find whole trees without any
7957 open TODO items and archive them (after getting confirmation from the user).
7958 If the cursor is not at a headline when this comand is called, try all level
7959 1 trees. If the cursor is on a headline, only try the direct children of
7960 this heading."
7961 (interactive "P")
7962 (if find-done
7963 (org-archive-all-done)
7964 ;; Save all relevant TODO keyword-relatex variables
7966 (let ((tr-org-todo-line-regexp org-todo-line-regexp) ; keep despite compiler
7967 (tr-org-todo-keywords-1 org-todo-keywords-1)
7968 (tr-org-todo-kwd-alist org-todo-kwd-alist)
7969 (tr-org-done-keywords org-done-keywords)
7970 (tr-org-todo-regexp org-todo-regexp)
7971 (tr-org-todo-line-regexp org-todo-line-regexp)
7972 (tr-org-odd-levels-only org-odd-levels-only)
7973 (this-buffer (current-buffer))
7974 (org-archive-location org-archive-location)
7975 (re "^#\\+ARCHIVE:[ \t]+\\(\\S-.*\\S-\\)[ \t]*$")
7976 ;; start of variables that will be used for saving context
7977 ;; The compiler complains about them - keep them anyway!
7978 (file (abbreviate-file-name (buffer-file-name)))
7979 (olpath (mapconcat 'identity (org-get-outline-path) "/"))
7980 (time (format-time-string
7981 (substring (cdr org-time-stamp-formats) 1 -1)
7982 (current-time)))
7983 afile heading buffer level newfile-p
7984 category todo priority
7985 ;; start of variables that will be used for savind context
7986 ltags itags prop)
7988 ;; Try to find a local archive location
7989 (save-excursion
7990 (save-restriction
7991 (widen)
7992 (setq prop (org-entry-get nil "ARCHIVE" 'inherit))
7993 (if (and prop (string-match "\\S-" prop))
7994 (setq org-archive-location prop)
7995 (if (or (re-search-backward re nil t)
7996 (re-search-forward re nil t))
7997 (setq org-archive-location (match-string 1))))))
7999 (if (string-match "\\(.*\\)::\\(.*\\)" org-archive-location)
8000 (progn
8001 (setq afile (format (match-string 1 org-archive-location)
8002 (file-name-nondirectory buffer-file-name))
8003 heading (match-string 2 org-archive-location)))
8004 (error "Invalid `org-archive-location'"))
8005 (if (> (length afile) 0)
8006 (setq newfile-p (not (file-exists-p afile))
8007 buffer (find-file-noselect afile))
8008 (setq buffer (current-buffer)))
8009 (unless buffer
8010 (error "Cannot access file \"%s\"" afile))
8011 (if (and (> (length heading) 0)
8012 (string-match "^\\*+" heading))
8013 (setq level (match-end 0))
8014 (setq heading nil level 0))
8015 (save-excursion
8016 (org-back-to-heading t)
8017 ;; Get context information that will be lost by moving the tree
8018 (org-refresh-category-properties)
8019 (setq category (org-get-category)
8020 todo (and (looking-at org-todo-line-regexp)
8021 (match-string 2))
8022 priority (org-get-priority (if (match-end 3) (match-string 3) ""))
8023 ltags (org-get-tags)
8024 itags (org-delete-all ltags (org-get-tags-at)))
8025 (setq ltags (mapconcat 'identity ltags " ")
8026 itags (mapconcat 'identity itags " "))
8027 ;; We first only copy, in case something goes wrong
8028 ;; we need to protect this-command, to avoid kill-region sets it,
8029 ;; which would lead to duplication of subtrees
8030 (let (this-command) (org-copy-subtree))
8031 (set-buffer buffer)
8032 ;; Enforce org-mode for the archive buffer
8033 (if (not (org-mode-p))
8034 ;; Force the mode for future visits.
8035 (let ((org-insert-mode-line-in-empty-file t)
8036 (org-inhibit-startup t))
8037 (call-interactively 'org-mode)))
8038 (when newfile-p
8039 (goto-char (point-max))
8040 (insert (format "\nArchived entries from file %s\n\n"
8041 (buffer-file-name this-buffer))))
8042 ;; Force the TODO keywords of the original buffer
8043 (let ((org-todo-line-regexp tr-org-todo-line-regexp)
8044 (org-todo-keywords-1 tr-org-todo-keywords-1)
8045 (org-todo-kwd-alist tr-org-todo-kwd-alist)
8046 (org-done-keywords tr-org-done-keywords)
8047 (org-todo-regexp tr-org-todo-regexp)
8048 (org-todo-line-regexp tr-org-todo-line-regexp)
8049 (org-odd-levels-only
8050 (if (local-variable-p 'org-odd-levels-only (current-buffer))
8051 org-odd-levels-only
8052 tr-org-odd-levels-only)))
8053 (goto-char (point-min))
8054 (if heading
8055 (progn
8056 (if (re-search-forward
8057 (concat "^" (regexp-quote heading)
8058 (org-re "[ \t]*\\(:[[:alnum:]_@:]+:\\)?[ \t]*\\($\\|\r\\)"))
8059 nil t)
8060 (goto-char (match-end 0))
8061 ;; Heading not found, just insert it at the end
8062 (goto-char (point-max))
8063 (or (bolp) (insert "\n"))
8064 (insert "\n" heading "\n")
8065 (end-of-line 0))
8066 ;; Make the subtree visible
8067 (show-subtree)
8068 (org-end-of-subtree t)
8069 (skip-chars-backward " \t\r\n")
8070 (and (looking-at "[ \t\r\n]*")
8071 (replace-match "\n\n")))
8072 ;; No specific heading, just go to end of file.
8073 (goto-char (point-max)) (insert "\n"))
8074 ;; Paste
8075 (org-paste-subtree (org-get-legal-level level 1))
8077 ;; Mark the entry as done
8078 (when (and org-archive-mark-done
8079 (looking-at org-todo-line-regexp)
8080 (or (not (match-end 2))
8081 (not (member (match-string 2) org-done-keywords))))
8082 (let (org-log-done org-todo-log-states)
8083 (org-todo
8084 (car (or (member org-archive-mark-done org-done-keywords)
8085 org-done-keywords)))))
8087 ;; Add the context info
8088 (when org-archive-save-context-info
8089 (let ((l org-archive-save-context-info) e n v)
8090 (while (setq e (pop l))
8091 (when (and (setq v (symbol-value e))
8092 (stringp v) (string-match "\\S-" v))
8093 (setq n (concat "ARCHIVE_" (upcase (symbol-name e))))
8094 (org-entry-put (point) n v)))))
8096 ;; Save the buffer, if it is not the same buffer.
8097 (if (not (eq this-buffer buffer)) (save-buffer))))
8098 ;; Here we are back in the original buffer. Everything seems to have
8099 ;; worked. So now cut the tree and finish up.
8100 (let (this-command) (org-cut-subtree))
8101 (if (and (not (eobp)) (looking-at "[ \t]*$")) (kill-line))
8102 (message "Subtree archived %s"
8103 (if (eq this-buffer buffer)
8104 (concat "under heading: " heading)
8105 (concat "in file: " (abbreviate-file-name afile)))))))
8107 (defun org-refresh-category-properties ()
8108 "Refresh category text properties in teh buffer."
8109 (let ((def-cat (cond
8110 ((null org-category)
8111 (if buffer-file-name
8112 (file-name-sans-extension
8113 (file-name-nondirectory buffer-file-name))
8114 "???"))
8115 ((symbolp org-category) (symbol-name org-category))
8116 (t org-category)))
8117 beg end cat pos optionp)
8118 (org-unmodified
8119 (save-excursion
8120 (save-restriction
8121 (widen)
8122 (goto-char (point-min))
8123 (put-text-property (point) (point-max) 'org-category def-cat)
8124 (while (re-search-forward
8125 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
8126 (setq pos (match-end 0)
8127 optionp (equal (char-after (match-beginning 0)) ?#)
8128 cat (org-trim (match-string 2)))
8129 (if optionp
8130 (setq beg (point-at-bol) end (point-max))
8131 (org-back-to-heading t)
8132 (setq beg (point) end (org-end-of-subtree t t)))
8133 (put-text-property beg end 'org-category cat)
8134 (goto-char pos)))))))
8136 (defun org-archive-all-done (&optional tag)
8137 "Archive sublevels of the current tree without open TODO items.
8138 If the cursor is not on a headline, try all level 1 trees. If
8139 it is on a headline, try all direct children.
8140 When TAG is non-nil, don't move trees, but mark them with the ARCHIVE tag."
8141 (let ((re (concat "^\\*+ +" org-not-done-regexp)) re1
8142 (rea (concat ".*:" org-archive-tag ":"))
8143 (begm (make-marker))
8144 (endm (make-marker))
8145 (question (if tag "Set ARCHIVE tag (no open TODO items)? "
8146 "Move subtree to archive (no open TODO items)? "))
8147 beg end (cntarch 0))
8148 (if (org-on-heading-p)
8149 (progn
8150 (setq re1 (concat "^" (regexp-quote
8151 (make-string
8152 (1+ (- (match-end 0) (match-beginning 0) 1))
8153 ?*))
8154 " "))
8155 (move-marker begm (point))
8156 (move-marker endm (org-end-of-subtree t)))
8157 (setq re1 "^* ")
8158 (move-marker begm (point-min))
8159 (move-marker endm (point-max)))
8160 (save-excursion
8161 (goto-char begm)
8162 (while (re-search-forward re1 endm t)
8163 (setq beg (match-beginning 0)
8164 end (save-excursion (org-end-of-subtree t) (point)))
8165 (goto-char beg)
8166 (if (re-search-forward re end t)
8167 (goto-char end)
8168 (goto-char beg)
8169 (if (and (or (not tag) (not (looking-at rea)))
8170 (y-or-n-p question))
8171 (progn
8172 (if tag
8173 (org-toggle-tag org-archive-tag 'on)
8174 (org-archive-subtree))
8175 (setq cntarch (1+ cntarch)))
8176 (goto-char end)))))
8177 (message "%d trees archived" cntarch)))
8179 (defun org-cycle-hide-drawers (state)
8180 "Re-hide all drawers after a visibility state change."
8181 (when (and (org-mode-p)
8182 (not (memq state '(overview folded))))
8183 (save-excursion
8184 (let* ((globalp (memq state '(contents all)))
8185 (beg (if globalp (point-min) (point)))
8186 (end (if globalp (point-max) (org-end-of-subtree t))))
8187 (goto-char beg)
8188 (while (re-search-forward org-drawer-regexp end t)
8189 (org-flag-drawer t))))))
8191 (defun org-flag-drawer (flag)
8192 (save-excursion
8193 (beginning-of-line 1)
8194 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
8195 (let ((b (match-end 0))
8196 (outline-regexp org-outline-regexp))
8197 (if (re-search-forward
8198 "^[ \t]*:END:"
8199 (save-excursion (outline-next-heading) (point)) t)
8200 (outline-flag-region b (point-at-eol) flag)
8201 (error ":END: line missing"))))))
8203 (defun org-cycle-hide-archived-subtrees (state)
8204 "Re-hide all archived subtrees after a visibility state change."
8205 (when (and (not org-cycle-open-archived-trees)
8206 (not (memq state '(overview folded))))
8207 (save-excursion
8208 (let* ((globalp (memq state '(contents all)))
8209 (beg (if globalp (point-min) (point)))
8210 (end (if globalp (point-max) (org-end-of-subtree t))))
8211 (org-hide-archived-subtrees beg end)
8212 (goto-char beg)
8213 (if (looking-at (concat ".*:" org-archive-tag ":"))
8214 (message "%s" (substitute-command-keys
8215 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
8217 (defun org-force-cycle-archived ()
8218 "Cycle subtree even if it is archived."
8219 (interactive)
8220 (setq this-command 'org-cycle)
8221 (let ((org-cycle-open-archived-trees t))
8222 (call-interactively 'org-cycle)))
8224 (defun org-hide-archived-subtrees (beg end)
8225 "Re-hide all archived subtrees after a visibility state change."
8226 (save-excursion
8227 (let* ((re (concat ":" org-archive-tag ":")))
8228 (goto-char beg)
8229 (while (re-search-forward re end t)
8230 (and (org-on-heading-p) (hide-subtree))
8231 (org-end-of-subtree t)))))
8233 (defun org-toggle-tag (tag &optional onoff)
8234 "Toggle the tag TAG for the current line.
8235 If ONOFF is `on' or `off', don't toggle but set to this state."
8236 (unless (org-on-heading-p t) (error "Not on headling"))
8237 (let (res current)
8238 (save-excursion
8239 (beginning-of-line)
8240 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t]*$")
8241 (point-at-eol) t)
8242 (progn
8243 (setq current (match-string 1))
8244 (replace-match ""))
8245 (setq current ""))
8246 (setq current (nreverse (org-split-string current ":")))
8247 (cond
8248 ((eq onoff 'on)
8249 (setq res t)
8250 (or (member tag current) (push tag current)))
8251 ((eq onoff 'off)
8252 (or (not (member tag current)) (setq current (delete tag current))))
8253 (t (if (member tag current)
8254 (setq current (delete tag current))
8255 (setq res t)
8256 (push tag current))))
8257 (end-of-line 1)
8258 (if current
8259 (progn
8260 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
8261 (org-set-tags nil t))
8262 (delete-horizontal-space))
8263 (run-hooks 'org-after-tags-change-hook))
8264 res))
8266 (defun org-toggle-archive-tag (&optional arg)
8267 "Toggle the archive tag for the current headline.
8268 With prefix ARG, check all children of current headline and offer tagging
8269 the children that do not contain any open TODO items."
8270 (interactive "P")
8271 (if arg
8272 (org-archive-all-done 'tag)
8273 (let (set)
8274 (save-excursion
8275 (org-back-to-heading t)
8276 (setq set (org-toggle-tag org-archive-tag))
8277 (when set (hide-subtree)))
8278 (and set (beginning-of-line 1))
8279 (message "Subtree %s" (if set "archived" "unarchived")))))
8282 ;;;; Tables
8284 ;;; The table editor
8286 ;; Watch out: Here we are talking about two different kind of tables.
8287 ;; Most of the code is for the tables created with the Org-mode table editor.
8288 ;; Sometimes, we talk about tables created and edited with the table.el
8289 ;; Emacs package. We call the former org-type tables, and the latter
8290 ;; table.el-type tables.
8292 (defun org-before-change-function (beg end)
8293 "Every change indicates that a table might need an update."
8294 (setq org-table-may-need-update t))
8296 (defconst org-table-line-regexp "^[ \t]*|"
8297 "Detects an org-type table line.")
8298 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
8299 "Detects an org-type table line.")
8300 (defconst org-table-auto-recalculate-regexp "^[ \t]*| *# *\\(|\\|$\\)"
8301 "Detects a table line marked for automatic recalculation.")
8302 (defconst org-table-recalculate-regexp "^[ \t]*| *[#*] *\\(|\\|$\\)"
8303 "Detects a table line marked for automatic recalculation.")
8304 (defconst org-table-calculate-mark-regexp "^[ \t]*| *[!$^_#*] *\\(|\\|$\\)"
8305 "Detects a table line marked for automatic recalculation.")
8306 (defconst org-table-hline-regexp "^[ \t]*|-"
8307 "Detects an org-type table hline.")
8308 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
8309 "Detects a table-type table hline.")
8310 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
8311 "Detects an org-type or table-type table.")
8312 (defconst org-table-border-regexp "^[ \t]*[^| \t]"
8313 "Searching from within a table (any type) this finds the first line
8314 outside the table.")
8315 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
8316 "Searching from within a table (any type) this finds the first line
8317 outside the table.")
8319 (defvar org-table-last-highlighted-reference nil)
8320 (defvar org-table-formula-history nil)
8322 (defvar org-table-column-names nil
8323 "Alist with column names, derived from the `!' line.")
8324 (defvar org-table-column-name-regexp nil
8325 "Regular expression matching the current column names.")
8326 (defvar org-table-local-parameters nil
8327 "Alist with parameter names, derived from the `$' line.")
8328 (defvar org-table-named-field-locations nil
8329 "Alist with locations of named fields.")
8331 (defvar org-table-current-line-types nil
8332 "Table row types, non-nil only for the duration of a comand.")
8333 (defvar org-table-current-begin-line nil
8334 "Table begin line, non-nil only for the duration of a comand.")
8335 (defvar org-table-current-begin-pos nil
8336 "Table begin position, non-nil only for the duration of a comand.")
8337 (defvar org-table-dlines nil
8338 "Vector of data line line numbers in the current table.")
8339 (defvar org-table-hlines nil
8340 "Vector of hline line numbers in the current table.")
8342 (defconst org-table-range-regexp
8343 "@\\([-+]?I*[-+]?[0-9]*\\)?\\(\\$[-+]?[0-9]+\\)?\\(\\.\\.@?\\([-+]?I*[-+]?[0-9]*\\)?\\(\\$[-+]?[0-9]+\\)?\\)?"
8344 ;; 1 2 3 4 5
8345 "Regular expression for matching ranges in formulas.")
8347 (defconst org-table-range-regexp2
8348 (concat
8349 "\\(" "@[-0-9I$&]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\|" "\\$[a-zA-Z0-9]+" "\\)"
8350 "\\.\\."
8351 "\\(" "@?[-0-9I$&]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\|" "\\$[a-zA-Z0-9]+" "\\)")
8352 "Match a range for reference display.")
8354 (defconst org-table-translate-regexp
8355 (concat "\\(" "@[-0-9I$]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\)")
8356 "Match a reference that needs translation, for reference display.")
8358 (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
8360 (defun org-table-create-with-table.el ()
8361 "Use the table.el package to insert a new table.
8362 If there is already a table at point, convert between Org-mode tables
8363 and table.el tables."
8364 (interactive)
8365 (require 'table)
8366 (cond
8367 ((org-at-table.el-p)
8368 (if (y-or-n-p "Convert table to Org-mode table? ")
8369 (org-table-convert)))
8370 ((org-at-table-p)
8371 (if (y-or-n-p "Convert table to table.el table? ")
8372 (org-table-convert)))
8373 (t (call-interactively 'table-insert))))
8375 (defun org-table-create-or-convert-from-region (arg)
8376 "Convert region to table, or create an empty table.
8377 If there is an active region, convert it to a table, using the function
8378 `org-table-convert-region'. See the documentation of that function
8379 to learn how the prefix argument is interpreted to determine the field
8380 separator.
8381 If there is no such region, create an empty table with `org-table-create'."
8382 (interactive "P")
8383 (if (org-region-active-p)
8384 (org-table-convert-region (region-beginning) (region-end) arg)
8385 (org-table-create arg)))
8387 (defun org-table-create (&optional size)
8388 "Query for a size and insert a table skeleton.
8389 SIZE is a string Columns x Rows like for example \"3x2\"."
8390 (interactive "P")
8391 (unless size
8392 (setq size (read-string
8393 (concat "Table size Columns x Rows [e.g. "
8394 org-table-default-size "]: ")
8395 "" nil org-table-default-size)))
8397 (let* ((pos (point))
8398 (indent (make-string (current-column) ?\ ))
8399 (split (org-split-string size " *x *"))
8400 (rows (string-to-number (nth 1 split)))
8401 (columns (string-to-number (car split)))
8402 (line (concat (apply 'concat indent "|" (make-list columns " |"))
8403 "\n")))
8404 (if (string-match "^[ \t]*$" (buffer-substring-no-properties
8405 (point-at-bol) (point)))
8406 (beginning-of-line 1)
8407 (newline))
8408 ;; (mapcar (lambda (x) (insert line)) (make-list rows t))
8409 (dotimes (i rows) (insert line))
8410 (goto-char pos)
8411 (if (> rows 1)
8412 ;; Insert a hline after the first row.
8413 (progn
8414 (end-of-line 1)
8415 (insert "\n|-")
8416 (goto-char pos)))
8417 (org-table-align)))
8419 (defun org-table-convert-region (beg0 end0 &optional separator)
8420 "Convert region to a table.
8421 The region goes from BEG0 to END0, but these borders will be moved
8422 slightly, to make sure a beginning of line in the first line is included.
8424 SEPARATOR specifies the field separator in the lines. It can have the
8425 following values:
8427 '(4) Use the comma as a field separator
8428 '(16) Use a TAB as field separator
8429 integer When a number, use that many spaces as field separator
8430 nil When nil, the command tries to be smart and figure out the
8431 separator in the following way:
8432 - when each line contains a TAB, assume TAB-separated material
8433 - when each line contains a comme, assume CSV material
8434 - else, assume one or more SPACE charcters as separator."
8435 (interactive "rP")
8436 (let* ((beg (min beg0 end0))
8437 (end (max beg0 end0))
8439 (goto-char beg)
8440 (beginning-of-line 1)
8441 (setq beg (move-marker (make-marker) (point)))
8442 (goto-char end)
8443 (if (bolp) (backward-char 1) (end-of-line 1))
8444 (setq end (move-marker (make-marker) (point)))
8445 ;; Get the right field separator
8446 (unless separator
8447 (goto-char beg)
8448 (setq separator
8449 (cond
8450 ((not (re-search-forward "^[^\n\t]+$" end t)) '(16))
8451 ((not (re-search-forward "^[^\n,]+$" end t)) '(4))
8452 (t 1))))
8453 (setq re (cond
8454 ((equal separator '(4)) "^\\|\"?[ \t]*,[ \t]*\"?")
8455 ((equal separator '(16)) "^\\|\t")
8456 ((integerp separator)
8457 (format "^ *\\| *\t *\\| \\{%d,\\}" separator))
8458 (t (error "This should not happen"))))
8459 (goto-char beg)
8460 (while (re-search-forward re end t)
8461 (replace-match "| " t t))
8462 (goto-char beg)
8463 (insert " ")
8464 (org-table-align)))
8466 (defun org-table-import (file arg)
8467 "Import FILE as a table.
8468 The file is assumed to be tab-separated. Such files can be produced by most
8469 spreadsheet and database applications. If no tabs (at least one per line)
8470 are found, lines will be split on whitespace into fields."
8471 (interactive "f\nP")
8472 (or (bolp) (newline))
8473 (let ((beg (point))
8474 (pm (point-max)))
8475 (insert-file-contents file)
8476 (org-table-convert-region beg (+ (point) (- (point-max) pm)) arg)))
8478 (defun org-table-export ()
8479 "Export table as a tab-separated file.
8480 Such a file can be imported into a spreadsheet program like Excel."
8481 (interactive)
8482 (let* ((beg (org-table-begin))
8483 (end (org-table-end))
8484 (table (buffer-substring beg end))
8485 (file (read-file-name "Export table to: "))
8486 buf)
8487 (unless (or (not (file-exists-p file))
8488 (y-or-n-p (format "Overwrite file %s? " file)))
8489 (error "Abort"))
8490 (with-current-buffer (find-file-noselect file)
8491 (setq buf (current-buffer))
8492 (erase-buffer)
8493 (fundamental-mode)
8494 (insert table)
8495 (goto-char (point-min))
8496 (while (re-search-forward "^[ \t]*|[ \t]*" nil t)
8497 (replace-match "" t t)
8498 (end-of-line 1))
8499 (goto-char (point-min))
8500 (while (re-search-forward "[ \t]*|[ \t]*$" nil t)
8501 (replace-match "" t t)
8502 (goto-char (min (1+ (point)) (point-max))))
8503 (goto-char (point-min))
8504 (while (re-search-forward "^-[-+]*$" nil t)
8505 (replace-match "")
8506 (if (looking-at "\n")
8507 (delete-char 1)))
8508 (goto-char (point-min))
8509 (while (re-search-forward "[ \t]*|[ \t]*" nil t)
8510 (replace-match "\t" t t))
8511 (save-buffer))
8512 (kill-buffer buf)))
8514 (defvar org-table-aligned-begin-marker (make-marker)
8515 "Marker at the beginning of the table last aligned.
8516 Used to check if cursor still is in that table, to minimize realignment.")
8517 (defvar org-table-aligned-end-marker (make-marker)
8518 "Marker at the end of the table last aligned.
8519 Used to check if cursor still is in that table, to minimize realignment.")
8520 (defvar org-table-last-alignment nil
8521 "List of flags for flushright alignment, from the last re-alignment.
8522 This is being used to correctly align a single field after TAB or RET.")
8523 (defvar org-table-last-column-widths nil
8524 "List of max width of fields in each column.
8525 This is being used to correctly align a single field after TAB or RET.")
8526 (defvar org-table-overlay-coordinates nil
8527 "Overlay coordinates after each align of a table.")
8528 (make-variable-buffer-local 'org-table-overlay-coordinates)
8530 (defvar org-last-recalc-line nil)
8531 (defconst org-narrow-column-arrow "=>"
8532 "Used as display property in narrowed table columns.")
8534 (defun org-table-align ()
8535 "Align the table at point by aligning all vertical bars."
8536 (interactive)
8537 (let* (
8538 ;; Limits of table
8539 (beg (org-table-begin))
8540 (end (org-table-end))
8541 ;; Current cursor position
8542 (linepos (org-current-line))
8543 (colpos (org-table-current-column))
8544 (winstart (window-start))
8545 (winstartline (org-current-line (min winstart (1- (point-max)))))
8546 lines (new "") lengths l typenums ty fields maxfields i
8547 column
8548 (indent "") cnt frac
8549 rfmt hfmt
8550 (spaces '(1 . 1))
8551 (sp1 (car spaces))
8552 (sp2 (cdr spaces))
8553 (rfmt1 (concat
8554 (make-string sp2 ?\ ) "%%%s%ds" (make-string sp1 ?\ ) "|"))
8555 (hfmt1 (concat
8556 (make-string sp2 ?-) "%s" (make-string sp1 ?-) "+"))
8557 emptystrings links dates emph narrow fmax f1 len c e)
8558 (untabify beg end)
8559 (remove-text-properties beg end '(org-cwidth t org-dwidth t display t))
8560 ;; Check if we have links or dates
8561 (goto-char beg)
8562 (setq links (re-search-forward org-bracket-link-regexp end t))
8563 (goto-char beg)
8564 (setq emph (and org-hide-emphasis-markers
8565 (re-search-forward org-emph-re end t)))
8566 (goto-char beg)
8567 (setq dates (and org-display-custom-times
8568 (re-search-forward org-ts-regexp-both end t)))
8569 ;; Make sure the link properties are right
8570 (when links (goto-char beg) (while (org-activate-bracket-links end)))
8571 ;; Make sure the date properties are right
8572 (when dates (goto-char beg) (while (org-activate-dates end)))
8573 (when emph (goto-char beg) (while (org-do-emphasis-faces end)))
8575 ;; Check if we are narrowing any columns
8576 (goto-char beg)
8577 (setq narrow (and org-format-transports-properties-p
8578 (re-search-forward "<[0-9]+>" end t)))
8579 ;; Get the rows
8580 (setq lines (org-split-string
8581 (buffer-substring beg end) "\n"))
8582 ;; Store the indentation of the first line
8583 (if (string-match "^ *" (car lines))
8584 (setq indent (make-string (- (match-end 0) (match-beginning 0)) ?\ )))
8585 ;; Mark the hlines by setting the corresponding element to nil
8586 ;; At the same time, we remove trailing space.
8587 (setq lines (mapcar (lambda (l)
8588 (if (string-match "^ *|-" l)
8590 (if (string-match "[ \t]+$" l)
8591 (substring l 0 (match-beginning 0))
8592 l)))
8593 lines))
8594 ;; Get the data fields by splitting the lines.
8595 (setq fields (mapcar
8596 (lambda (l)
8597 (org-split-string l " *| *"))
8598 (delq nil (copy-sequence lines))))
8599 ;; How many fields in the longest line?
8600 (condition-case nil
8601 (setq maxfields (apply 'max (mapcar 'length fields)))
8602 (error
8603 (kill-region beg end)
8604 (org-table-create org-table-default-size)
8605 (error "Empty table - created default table")))
8606 ;; A list of empty strings to fill any short rows on output
8607 (setq emptystrings (make-list maxfields ""))
8608 ;; Check for special formatting.
8609 (setq i -1)
8610 (while (< (setq i (1+ i)) maxfields) ;; Loop over all columns
8611 (setq column (mapcar (lambda (x) (or (nth i x) "")) fields))
8612 ;; Check if there is an explicit width specified
8613 (when narrow
8614 (setq c column fmax nil)
8615 (while c
8616 (setq e (pop c))
8617 (if (and (stringp e) (string-match "^<\\([0-9]+\\)>$" e))
8618 (setq fmax (string-to-number (match-string 1 e)) c nil)))
8619 ;; Find fields that are wider than fmax, and shorten them
8620 (when fmax
8621 (loop for xx in column do
8622 (when (and (stringp xx)
8623 (> (org-string-width xx) fmax))
8624 (org-add-props xx nil
8625 'help-echo
8626 (concat "Clipped table field, use C-c ` to edit. Full value is:\n" (org-no-properties (copy-sequence xx))))
8627 (setq f1 (min fmax (or (string-match org-bracket-link-regexp xx) fmax)))
8628 (unless (> f1 1)
8629 (error "Cannot narrow field starting with wide link \"%s\""
8630 (match-string 0 xx)))
8631 (add-text-properties f1 (length xx) (list 'org-cwidth t) xx)
8632 (add-text-properties (- f1 2) f1
8633 (list 'display org-narrow-column-arrow)
8634 xx)))))
8635 ;; Get the maximum width for each column
8636 (push (apply 'max 1 (mapcar 'org-string-width column)) lengths)
8637 ;; Get the fraction of numbers, to decide about alignment of the column
8638 (setq cnt 0 frac 0.0)
8639 (loop for x in column do
8640 (if (equal x "")
8642 (setq frac ( / (+ (* frac cnt)
8643 (if (string-match org-table-number-regexp x) 1 0))
8644 (setq cnt (1+ cnt))))))
8645 (push (>= frac org-table-number-fraction) typenums))
8646 (setq lengths (nreverse lengths) typenums (nreverse typenums))
8648 ;; Store the alignment of this table, for later editing of single fields
8649 (setq org-table-last-alignment typenums
8650 org-table-last-column-widths lengths)
8652 ;; With invisible characters, `format' does not get the field width right
8653 ;; So we need to make these fields wide by hand.
8654 (when (or links emph)
8655 (loop for i from 0 upto (1- maxfields) do
8656 (setq len (nth i lengths))
8657 (loop for j from 0 upto (1- (length fields)) do
8658 (setq c (nthcdr i (car (nthcdr j fields))))
8659 (if (and (stringp (car c))
8660 (text-property-any 0 (length (car c)) 'invisible 'org-link (car c))
8661 ; (string-match org-bracket-link-regexp (car c))
8662 (< (org-string-width (car c)) len))
8663 (setcar c (concat (car c) (make-string (- len (org-string-width (car c))) ?\ )))))))
8665 ;; Compute the formats needed for output of the table
8666 (setq rfmt (concat indent "|") hfmt (concat indent "|"))
8667 (while (setq l (pop lengths))
8668 (setq ty (if (pop typenums) "" "-")) ; number types flushright
8669 (setq rfmt (concat rfmt (format rfmt1 ty l))
8670 hfmt (concat hfmt (format hfmt1 (make-string l ?-)))))
8671 (setq rfmt (concat rfmt "\n")
8672 hfmt (concat (substring hfmt 0 -1) "|\n"))
8674 (setq new (mapconcat
8675 (lambda (l)
8676 (if l (apply 'format rfmt
8677 (append (pop fields) emptystrings))
8678 hfmt))
8679 lines ""))
8680 ;; Replace the old one
8681 (delete-region beg end)
8682 (move-marker end nil)
8683 (move-marker org-table-aligned-begin-marker (point))
8684 (insert new)
8685 (move-marker org-table-aligned-end-marker (point))
8686 (when (and orgtbl-mode (not (org-mode-p)))
8687 (goto-char org-table-aligned-begin-marker)
8688 (while (org-hide-wide-columns org-table-aligned-end-marker)))
8689 ;; Try to move to the old location
8690 (goto-line winstartline)
8691 (setq winstart (point-at-bol))
8692 (goto-line linepos)
8693 (set-window-start (selected-window) winstart 'noforce)
8694 (org-table-goto-column colpos)
8695 (and org-table-overlay-coordinates (org-table-overlay-coordinates))
8696 (setq org-table-may-need-update nil)
8699 (defun org-string-width (s)
8700 "Compute width of string, ignoring invisible characters.
8701 This ignores character with invisibility property `org-link', and also
8702 characters with property `org-cwidth', because these will become invisible
8703 upon the next fontification round."
8704 (let (b l)
8705 (when (or (eq t buffer-invisibility-spec)
8706 (assq 'org-link buffer-invisibility-spec))
8707 (while (setq b (text-property-any 0 (length s)
8708 'invisible 'org-link s))
8709 (setq s (concat (substring s 0 b)
8710 (substring s (or (next-single-property-change
8711 b 'invisible s) (length s)))))))
8712 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
8713 (setq s (concat (substring s 0 b)
8714 (substring s (or (next-single-property-change
8715 b 'org-cwidth s) (length s))))))
8716 (setq l (string-width s) b -1)
8717 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
8718 (setq l (- l (get-text-property b 'org-dwidth-n s))))
8721 (defun org-table-begin (&optional table-type)
8722 "Find the beginning of the table and return its position.
8723 With argument TABLE-TYPE, go to the beginning of a table.el-type table."
8724 (save-excursion
8725 (if (not (re-search-backward
8726 (if table-type org-table-any-border-regexp
8727 org-table-border-regexp)
8728 nil t))
8729 (progn (goto-char (point-min)) (point))
8730 (goto-char (match-beginning 0))
8731 (beginning-of-line 2)
8732 (point))))
8734 (defun org-table-end (&optional table-type)
8735 "Find the end of the table and return its position.
8736 With argument TABLE-TYPE, go to the end of a table.el-type table."
8737 (save-excursion
8738 (if (not (re-search-forward
8739 (if table-type org-table-any-border-regexp
8740 org-table-border-regexp)
8741 nil t))
8742 (goto-char (point-max))
8743 (goto-char (match-beginning 0)))
8744 (point-marker)))
8746 (defun org-table-justify-field-maybe (&optional new)
8747 "Justify the current field, text to left, number to right.
8748 Optional argument NEW may specify text to replace the current field content."
8749 (cond
8750 ((and (not new) org-table-may-need-update)) ; Realignment will happen anyway
8751 ((org-at-table-hline-p))
8752 ((and (not new)
8753 (or (not (equal (marker-buffer org-table-aligned-begin-marker)
8754 (current-buffer)))
8755 (< (point) org-table-aligned-begin-marker)
8756 (>= (point) org-table-aligned-end-marker)))
8757 ;; This is not the same table, force a full re-align
8758 (setq org-table-may-need-update t))
8759 (t ;; realign the current field, based on previous full realign
8760 (let* ((pos (point)) s
8761 (col (org-table-current-column))
8762 (num (if (> col 0) (nth (1- col) org-table-last-alignment)))
8763 l f n o e)
8764 (when (> col 0)
8765 (skip-chars-backward "^|\n")
8766 (if (looking-at " *\\([^|\n]*?\\) *\\(|\\|$\\)")
8767 (progn
8768 (setq s (match-string 1)
8769 o (match-string 0)
8770 l (max 1 (- (match-end 0) (match-beginning 0) 3))
8771 e (not (= (match-beginning 2) (match-end 2))))
8772 (setq f (format (if num " %%%ds %s" " %%-%ds %s")
8773 l (if e "|" (setq org-table-may-need-update t) ""))
8774 n (format f s))
8775 (if new
8776 (if (<= (length new) l) ;; FIXME: length -> str-width?
8777 (setq n (format f new))
8778 (setq n (concat new "|") org-table-may-need-update t)))
8779 (or (equal n o)
8780 (let (org-table-may-need-update)
8781 (replace-match n t t))))
8782 (setq org-table-may-need-update t))
8783 (goto-char pos))))))
8785 (defun org-table-next-field ()
8786 "Go to the next field in the current table, creating new lines as needed.
8787 Before doing so, re-align the table if necessary."
8788 (interactive)
8789 (org-table-maybe-eval-formula)
8790 (org-table-maybe-recalculate-line)
8791 (if (and org-table-automatic-realign
8792 org-table-may-need-update)
8793 (org-table-align))
8794 (let ((end (org-table-end)))
8795 (if (org-at-table-hline-p)
8796 (end-of-line 1))
8797 (condition-case nil
8798 (progn
8799 (re-search-forward "|" end)
8800 (if (looking-at "[ \t]*$")
8801 (re-search-forward "|" end))
8802 (if (and (looking-at "-")
8803 org-table-tab-jumps-over-hlines
8804 (re-search-forward "^[ \t]*|\\([^-]\\)" end t))
8805 (goto-char (match-beginning 1)))
8806 (if (looking-at "-")
8807 (progn
8808 (beginning-of-line 0)
8809 (org-table-insert-row 'below))
8810 (if (looking-at " ") (forward-char 1))))
8811 (error
8812 (org-table-insert-row 'below)))))
8814 (defun org-table-previous-field ()
8815 "Go to the previous field in the table.
8816 Before doing so, re-align the table if necessary."
8817 (interactive)
8818 (org-table-justify-field-maybe)
8819 (org-table-maybe-recalculate-line)
8820 (if (and org-table-automatic-realign
8821 org-table-may-need-update)
8822 (org-table-align))
8823 (if (org-at-table-hline-p)
8824 (end-of-line 1))
8825 (re-search-backward "|" (org-table-begin))
8826 (re-search-backward "|" (org-table-begin))
8827 (while (looking-at "|\\(-\\|[ \t]*$\\)")
8828 (re-search-backward "|" (org-table-begin)))
8829 (if (looking-at "| ?")
8830 (goto-char (match-end 0))))
8832 (defun org-table-next-row ()
8833 "Go to the next row (same column) in the current table.
8834 Before doing so, re-align the table if necessary."
8835 (interactive)
8836 (org-table-maybe-eval-formula)
8837 (org-table-maybe-recalculate-line)
8838 (if (or (looking-at "[ \t]*$")
8839 (save-excursion (skip-chars-backward " \t") (bolp)))
8840 (newline)
8841 (if (and org-table-automatic-realign
8842 org-table-may-need-update)
8843 (org-table-align))
8844 (let ((col (org-table-current-column)))
8845 (beginning-of-line 2)
8846 (if (or (not (org-at-table-p))
8847 (org-at-table-hline-p))
8848 (progn
8849 (beginning-of-line 0)
8850 (org-table-insert-row 'below)))
8851 (org-table-goto-column col)
8852 (skip-chars-backward "^|\n\r")
8853 (if (looking-at " ") (forward-char 1)))))
8855 (defun org-table-copy-down (n)
8856 "Copy a field down in the current column.
8857 If the field at the cursor is empty, copy into it the content of the nearest
8858 non-empty field above. With argument N, use the Nth non-empty field.
8859 If the current field is not empty, it is copied down to the next row, and
8860 the cursor is moved with it. Therefore, repeating this command causes the
8861 column to be filled row-by-row.
8862 If the variable `org-table-copy-increment' is non-nil and the field is an
8863 integer or a timestamp, it will be incremented while copying. In the case of
8864 a timestamp, if the cursor is on the year, change the year. If it is on the
8865 month or the day, change that. Point will stay on the current date field
8866 in order to easily repeat the interval."
8867 (interactive "p")
8868 (let* ((colpos (org-table-current-column))
8869 (col (current-column))
8870 (field (org-table-get-field))
8871 (non-empty (string-match "[^ \t]" field))
8872 (beg (org-table-begin))
8873 txt)
8874 (org-table-check-inside-data-field)
8875 (if non-empty
8876 (progn
8877 (setq txt (org-trim field))
8878 (org-table-next-row)
8879 (org-table-blank-field))
8880 (save-excursion
8881 (setq txt
8882 (catch 'exit
8883 (while (progn (beginning-of-line 1)
8884 (re-search-backward org-table-dataline-regexp
8885 beg t))
8886 (org-table-goto-column colpos t)
8887 (if (and (looking-at
8888 "|[ \t]*\\([^| \t][^|]*?\\)[ \t]*|")
8889 (= (setq n (1- n)) 0))
8890 (throw 'exit (match-string 1))))))))
8891 (if txt
8892 (progn
8893 (if (and org-table-copy-increment
8894 (string-match "^[0-9]+$" txt))
8895 (setq txt (format "%d" (+ (string-to-number txt) 1))))
8896 (insert txt)
8897 (move-to-column col)
8898 (if (and org-table-copy-increment (org-at-timestamp-p t))
8899 (org-timestamp-up 1)
8900 (org-table-maybe-recalculate-line))
8901 (org-table-align)
8902 (move-to-column col))
8903 (error "No non-empty field found"))))
8905 (defun org-table-check-inside-data-field ()
8906 "Is point inside a table data field?
8907 I.e. not on a hline or before the first or after the last column?
8908 This actually throws an error, so it aborts the current command."
8909 (if (or (not (org-at-table-p))
8910 (= (org-table-current-column) 0)
8911 (org-at-table-hline-p)
8912 (looking-at "[ \t]*$"))
8913 (error "Not in table data field")))
8915 (defvar org-table-clip nil
8916 "Clipboard for table regions.")
8918 (defun org-table-blank-field ()
8919 "Blank the current table field or active region."
8920 (interactive)
8921 (org-table-check-inside-data-field)
8922 (if (and (interactive-p) (org-region-active-p))
8923 (let (org-table-clip)
8924 (org-table-cut-region (region-beginning) (region-end)))
8925 (skip-chars-backward "^|")
8926 (backward-char 1)
8927 (if (looking-at "|[^|\n]+")
8928 (let* ((pos (match-beginning 0))
8929 (match (match-string 0))
8930 (len (org-string-width match)))
8931 (replace-match (concat "|" (make-string (1- len) ?\ )))
8932 (goto-char (+ 2 pos))
8933 (substring match 1)))))
8935 (defun org-table-get-field (&optional n replace)
8936 "Return the value of the field in column N of current row.
8937 N defaults to current field.
8938 If REPLACE is a string, replace field with this value. The return value
8939 is always the old value."
8940 (and n (org-table-goto-column n))
8941 (skip-chars-backward "^|\n")
8942 (backward-char 1)
8943 (if (looking-at "|[^|\r\n]*")
8944 (let* ((pos (match-beginning 0))
8945 (val (buffer-substring (1+ pos) (match-end 0))))
8946 (if replace
8947 (replace-match (concat "|" replace) t t))
8948 (goto-char (min (point-at-eol) (+ 2 pos)))
8949 val)
8950 (forward-char 1) ""))
8952 (defun org-table-field-info (arg)
8953 "Show info about the current field, and highlight any reference at point."
8954 (interactive "P")
8955 (org-table-get-specials)
8956 (save-excursion
8957 (let* ((pos (point))
8958 (col (org-table-current-column))
8959 (cname (car (rassoc (int-to-string col) org-table-column-names)))
8960 (name (car (rassoc (list (org-current-line) col)
8961 org-table-named-field-locations)))
8962 (eql (org-table-get-stored-formulas))
8963 (dline (org-table-current-dline))
8964 (ref (format "@%d$%d" dline col))
8965 (ref1 (org-table-convert-refs-to-an ref))
8966 (fequation (or (assoc name eql) (assoc ref eql)))
8967 (cequation (assoc (int-to-string col) eql))
8968 (eqn (or fequation cequation)))
8969 (goto-char pos)
8970 (condition-case nil
8971 (org-table-show-reference 'local)
8972 (error nil))
8973 (message "line @%d, col $%s%s, ref @%d$%d or %s%s%s"
8974 dline col
8975 (if cname (concat " or $" cname) "")
8976 dline col ref1
8977 (if name (concat " or $" name) "")
8978 ;; FIXME: formula info not correct if special table line
8979 (if eqn
8980 (concat ", formula: "
8981 (org-table-formula-to-user
8982 (concat
8983 (if (string-match "^[$@]"(car eqn)) "" "$")
8984 (car eqn) "=" (cdr eqn))))
8985 "")))))
8987 (defun org-table-current-column ()
8988 "Find out which column we are in.
8989 When called interactively, column is also displayed in echo area."
8990 (interactive)
8991 (if (interactive-p) (org-table-check-inside-data-field))
8992 (save-excursion
8993 (let ((cnt 0) (pos (point)))
8994 (beginning-of-line 1)
8995 (while (search-forward "|" pos t)
8996 (setq cnt (1+ cnt)))
8997 (if (interactive-p) (message "This is table column %d" cnt))
8998 cnt)))
9000 (defun org-table-current-dline ()
9001 "Find out what table data line we are in.
9002 Only datalins count for this."
9003 (interactive)
9004 (if (interactive-p) (org-table-check-inside-data-field))
9005 (save-excursion
9006 (let ((cnt 0) (pos (point)))
9007 (goto-char (org-table-begin))
9008 (while (<= (point) pos)
9009 (if (looking-at org-table-dataline-regexp) (setq cnt (1+ cnt)))
9010 (beginning-of-line 2))
9011 (if (interactive-p) (message "This is table line %d" cnt))
9012 cnt)))
9014 (defun org-table-goto-column (n &optional on-delim force)
9015 "Move the cursor to the Nth column in the current table line.
9016 With optional argument ON-DELIM, stop with point before the left delimiter
9017 of the field.
9018 If there are less than N fields, just go to after the last delimiter.
9019 However, when FORCE is non-nil, create new columns if necessary."
9020 (interactive "p")
9021 (let ((pos (point-at-eol)))
9022 (beginning-of-line 1)
9023 (when (> n 0)
9024 (while (and (> (setq n (1- n)) -1)
9025 (or (search-forward "|" pos t)
9026 (and force
9027 (progn (end-of-line 1)
9028 (skip-chars-backward "^|")
9029 (insert " | "))))))
9030 ; (backward-char 2) t)))))
9031 (when (and force (not (looking-at ".*|")))
9032 (save-excursion (end-of-line 1) (insert " | ")))
9033 (if on-delim
9034 (backward-char 1)
9035 (if (looking-at " ") (forward-char 1))))))
9037 (defun org-at-table-p (&optional table-type)
9038 "Return t if the cursor is inside an org-type table.
9039 If TABLE-TYPE is non-nil, also check for table.el-type tables."
9040 (if org-enable-table-editor
9041 (save-excursion
9042 (beginning-of-line 1)
9043 (looking-at (if table-type org-table-any-line-regexp
9044 org-table-line-regexp)))
9045 nil))
9047 (defun org-at-table.el-p ()
9048 "Return t if and only if we are at a table.el table."
9049 (and (org-at-table-p 'any)
9050 (save-excursion
9051 (goto-char (org-table-begin 'any))
9052 (looking-at org-table1-hline-regexp))))
9054 (defun org-table-recognize-table.el ()
9055 "If there is a table.el table nearby, recognize it and move into it."
9056 (if org-table-tab-recognizes-table.el
9057 (if (org-at-table.el-p)
9058 (progn
9059 (beginning-of-line 1)
9060 (if (looking-at org-table-dataline-regexp)
9062 (if (looking-at org-table1-hline-regexp)
9063 (progn
9064 (beginning-of-line 2)
9065 (if (looking-at org-table-any-border-regexp)
9066 (beginning-of-line -1)))))
9067 (if (re-search-forward "|" (org-table-end t) t)
9068 (progn
9069 (require 'table)
9070 (if (table--at-cell-p (point))
9072 (message "recognizing table.el table...")
9073 (table-recognize-table)
9074 (message "recognizing table.el table...done")))
9075 (error "This should not happen..."))
9077 nil)
9078 nil))
9080 (defun org-at-table-hline-p ()
9081 "Return t if the cursor is inside a hline in a table."
9082 (if org-enable-table-editor
9083 (save-excursion
9084 (beginning-of-line 1)
9085 (looking-at org-table-hline-regexp))
9086 nil))
9088 (defun org-table-insert-column ()
9089 "Insert a new column into the table."
9090 (interactive)
9091 (if (not (org-at-table-p))
9092 (error "Not at a table"))
9093 (org-table-find-dataline)
9094 (let* ((col (max 1 (org-table-current-column)))
9095 (beg (org-table-begin))
9096 (end (org-table-end))
9097 ;; Current cursor position
9098 (linepos (org-current-line))
9099 (colpos col))
9100 (goto-char beg)
9101 (while (< (point) end)
9102 (if (org-at-table-hline-p)
9104 (org-table-goto-column col t)
9105 (insert "| "))
9106 (beginning-of-line 2))
9107 (move-marker end nil)
9108 (goto-line linepos)
9109 (org-table-goto-column colpos)
9110 (org-table-align)
9111 (org-table-fix-formulas "$" nil (1- col) 1)))
9113 (defun org-table-find-dataline ()
9114 "Find a dataline in the current table, which is needed for column commands."
9115 (if (and (org-at-table-p)
9116 (not (org-at-table-hline-p)))
9118 (let ((col (current-column))
9119 (end (org-table-end)))
9120 (move-to-column col)
9121 (while (and (< (point) end)
9122 (or (not (= (current-column) col))
9123 (org-at-table-hline-p)))
9124 (beginning-of-line 2)
9125 (move-to-column col))
9126 (if (and (org-at-table-p)
9127 (not (org-at-table-hline-p)))
9129 (error
9130 "Please position cursor in a data line for column operations")))))
9132 (defun org-table-delete-column ()
9133 "Delete a column from the table."
9134 (interactive)
9135 (if (not (org-at-table-p))
9136 (error "Not at a table"))
9137 (org-table-find-dataline)
9138 (org-table-check-inside-data-field)
9139 (let* ((col (org-table-current-column))
9140 (beg (org-table-begin))
9141 (end (org-table-end))
9142 ;; Current cursor position
9143 (linepos (org-current-line))
9144 (colpos col))
9145 (goto-char beg)
9146 (while (< (point) end)
9147 (if (org-at-table-hline-p)
9149 (org-table-goto-column col t)
9150 (and (looking-at "|[^|\n]+|")
9151 (replace-match "|")))
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 "$" (list (cons (number-to-string col) "INVALID"))
9158 col -1 col)))
9160 (defun org-table-move-column-right ()
9161 "Move column to the right."
9162 (interactive)
9163 (org-table-move-column nil))
9164 (defun org-table-move-column-left ()
9165 "Move column to the left."
9166 (interactive)
9167 (org-table-move-column 'left))
9169 (defun org-table-move-column (&optional left)
9170 "Move the current column to the right. With arg LEFT, move to the left."
9171 (interactive "P")
9172 (if (not (org-at-table-p))
9173 (error "Not at a table"))
9174 (org-table-find-dataline)
9175 (org-table-check-inside-data-field)
9176 (let* ((col (org-table-current-column))
9177 (col1 (if left (1- col) col))
9178 (beg (org-table-begin))
9179 (end (org-table-end))
9180 ;; Current cursor position
9181 (linepos (org-current-line))
9182 (colpos (if left (1- col) (1+ col))))
9183 (if (and left (= col 1))
9184 (error "Cannot move column further left"))
9185 (if (and (not left) (looking-at "[^|\n]*|[^|\n]*$"))
9186 (error "Cannot move column further right"))
9187 (goto-char beg)
9188 (while (< (point) end)
9189 (if (org-at-table-hline-p)
9191 (org-table-goto-column col1 t)
9192 (and (looking-at "|\\([^|\n]+\\)|\\([^|\n]+\\)|")
9193 (replace-match "|\\2|\\1|")))
9194 (beginning-of-line 2))
9195 (move-marker end nil)
9196 (goto-line linepos)
9197 (org-table-goto-column colpos)
9198 (org-table-align)
9199 (org-table-fix-formulas
9200 "$" (list (cons (number-to-string col) (number-to-string colpos))
9201 (cons (number-to-string colpos) (number-to-string col))))))
9203 (defun org-table-move-row-down ()
9204 "Move table row down."
9205 (interactive)
9206 (org-table-move-row nil))
9207 (defun org-table-move-row-up ()
9208 "Move table row up."
9209 (interactive)
9210 (org-table-move-row 'up))
9212 (defun org-table-move-row (&optional up)
9213 "Move the current table line down. With arg UP, move it up."
9214 (interactive "P")
9215 (let* ((col (current-column))
9216 (pos (point))
9217 (hline1p (save-excursion (beginning-of-line 1)
9218 (looking-at org-table-hline-regexp)))
9219 (dline1 (org-table-current-dline))
9220 (dline2 (+ dline1 (if up -1 1)))
9221 (tonew (if up 0 2))
9222 txt hline2p)
9223 (beginning-of-line tonew)
9224 (unless (org-at-table-p)
9225 (goto-char pos)
9226 (error "Cannot move row further"))
9227 (setq hline2p (looking-at org-table-hline-regexp))
9228 (goto-char pos)
9229 (beginning-of-line 1)
9230 (setq pos (point))
9231 (setq txt (buffer-substring (point) (1+ (point-at-eol))))
9232 (delete-region (point) (1+ (point-at-eol)))
9233 (beginning-of-line tonew)
9234 (insert txt)
9235 (beginning-of-line 0)
9236 (move-to-column col)
9237 (unless (or hline1p hline2p)
9238 (org-table-fix-formulas
9239 "@" (list (cons (number-to-string dline1) (number-to-string dline2))
9240 (cons (number-to-string dline2) (number-to-string dline1)))))))
9242 (defun org-table-insert-row (&optional arg)
9243 "Insert a new row above the current line into the table.
9244 With prefix ARG, insert below the current line."
9245 (interactive "P")
9246 (if (not (org-at-table-p))
9247 (error "Not at a table"))
9248 (let* ((line (buffer-substring (point-at-bol) (point-at-eol)))
9249 (new (org-table-clean-line line)))
9250 ;; Fix the first field if necessary
9251 (if (string-match "^[ \t]*| *[#$] *|" line)
9252 (setq new (replace-match (match-string 0 line) t t new)))
9253 (beginning-of-line (if arg 2 1))
9254 (let (org-table-may-need-update) (insert-before-markers new "\n"))
9255 (beginning-of-line 0)
9256 (re-search-forward "| ?" (point-at-eol) t)
9257 (and (or org-table-may-need-update org-table-overlay-coordinates)
9258 (org-table-align))
9259 (org-table-fix-formulas "@" nil (1- (org-table-current-dline)) 1)))
9261 (defun org-table-insert-hline (&optional above)
9262 "Insert a horizontal-line below the current line into the table.
9263 With prefix ABOVE, insert above the current line."
9264 (interactive "P")
9265 (if (not (org-at-table-p))
9266 (error "Not at a table"))
9267 (let ((line (org-table-clean-line
9268 (buffer-substring (point-at-bol) (point-at-eol))))
9269 (col (current-column)))
9270 (while (string-match "|\\( +\\)|" line)
9271 (setq line (replace-match
9272 (concat "+" (make-string (- (match-end 1) (match-beginning 1))
9273 ?-) "|") t t line)))
9274 (and (string-match "\\+" line) (setq line (replace-match "|" t t line)))
9275 (beginning-of-line (if above 1 2))
9276 (insert line "\n")
9277 (beginning-of-line (if above 1 -1))
9278 (move-to-column col)
9279 (and org-table-overlay-coordinates (org-table-align))))
9281 (defun org-table-hline-and-move (&optional same-column)
9282 "Insert a hline and move to the row below that line."
9283 (interactive "P")
9284 (let ((col (org-table-current-column)))
9285 (org-table-maybe-eval-formula)
9286 (org-table-maybe-recalculate-line)
9287 (org-table-insert-hline)
9288 (end-of-line 2)
9289 (if (looking-at "\n[ \t]*|-")
9290 (progn (insert "\n|") (org-table-align))
9291 (org-table-next-field))
9292 (if same-column (org-table-goto-column col))))
9294 (defun org-table-clean-line (s)
9295 "Convert a table line S into a string with only \"|\" and space.
9296 In particular, this does handle wide and invisible characters."
9297 (if (string-match "^[ \t]*|-" s)
9298 ;; It's a hline, just map the characters
9299 (setq s (mapconcat (lambda (x) (if (member x '(?| ?+)) "|" " ")) s ""))
9300 (while (string-match "|\\([ \t]*?[^ \t\r\n|][^\r\n|]*\\)|" s)
9301 (setq s (replace-match
9302 (concat "|" (make-string (org-string-width (match-string 1 s))
9303 ?\ ) "|")
9304 t t s)))
9307 (defun org-table-kill-row ()
9308 "Delete the current row or horizontal line from the table."
9309 (interactive)
9310 (if (not (org-at-table-p))
9311 (error "Not at a table"))
9312 (let ((col (current-column))
9313 (dline (org-table-current-dline)))
9314 (kill-region (point-at-bol) (min (1+ (point-at-eol)) (point-max)))
9315 (if (not (org-at-table-p)) (beginning-of-line 0))
9316 (move-to-column col)
9317 (org-table-fix-formulas "@" (list (cons (number-to-string dline) "INVALID"))
9318 dline -1 dline)))
9320 (defun org-table-sort-lines (with-case &optional sorting-type)
9321 "Sort table lines according to the column at point.
9323 The position of point indicates the column to be used for
9324 sorting, and the range of lines is the range between the nearest
9325 horizontal separator lines, or the entire table of no such lines
9326 exist. If point is before the first column, you will be prompted
9327 for the sorting column. If there is an active region, the mark
9328 specifies the first line and the sorting column, while point
9329 should be in the last line to be included into the sorting.
9331 The command then prompts for the sorting type which can be
9332 alphabetically, numerically, or by time (as given in a time stamp
9333 in the field). Sorting in reverse order is also possible.
9335 With prefix argument WITH-CASE, alphabetic sorting will be case-sensitive.
9337 If SORTING-TYPE is specified when this function is called from a Lisp
9338 program, no prompting will take place. SORTING-TYPE must be a character,
9339 any of (?a ?A ?n ?N ?t ?T) where the capital letter indicate that sorting
9340 should be done in reverse order."
9341 (interactive "P")
9342 (let* ((thisline (org-current-line))
9343 (thiscol (org-table-current-column))
9344 beg end bcol ecol tend tbeg column lns pos)
9345 (when (equal thiscol 0)
9346 (if (interactive-p)
9347 (setq thiscol
9348 (string-to-number
9349 (read-string "Use column N for sorting: ")))
9350 (setq thiscol 1))
9351 (org-table-goto-column thiscol))
9352 (org-table-check-inside-data-field)
9353 (if (org-region-active-p)
9354 (progn
9355 (setq beg (region-beginning) end (region-end))
9356 (goto-char beg)
9357 (setq column (org-table-current-column)
9358 beg (point-at-bol))
9359 (goto-char end)
9360 (setq end (point-at-bol 2)))
9361 (setq column (org-table-current-column)
9362 pos (point)
9363 tbeg (org-table-begin)
9364 tend (org-table-end))
9365 (if (re-search-backward org-table-hline-regexp tbeg t)
9366 (setq beg (point-at-bol 2))
9367 (goto-char tbeg)
9368 (setq beg (point-at-bol 1)))
9369 (goto-char pos)
9370 (if (re-search-forward org-table-hline-regexp tend t)
9371 (setq end (point-at-bol 1))
9372 (goto-char tend)
9373 (setq end (point-at-bol))))
9374 (setq beg (move-marker (make-marker) beg)
9375 end (move-marker (make-marker) end))
9376 (untabify beg end)
9377 (goto-char beg)
9378 (org-table-goto-column column)
9379 (skip-chars-backward "^|")
9380 (setq bcol (current-column))
9381 (org-table-goto-column (1+ column))
9382 (skip-chars-backward "^|")
9383 (setq ecol (1- (current-column)))
9384 (org-table-goto-column column)
9385 (setq lns (mapcar (lambda(x) (cons
9386 (org-sort-remove-invisible
9387 (nth (1- column)
9388 (org-split-string x "[ \t]*|[ \t]*")))
9390 (org-split-string (buffer-substring beg end) "\n")))
9391 (setq lns (org-do-sort lns "Table" with-case sorting-type))
9392 (delete-region beg end)
9393 (move-marker beg nil)
9394 (move-marker end nil)
9395 (insert (mapconcat 'cdr lns "\n") "\n")
9396 (goto-line thisline)
9397 (org-table-goto-column thiscol)
9398 (message "%d lines sorted, based on column %d" (length lns) column)))
9400 ;; FIXME: maybe we will not need this? Table sorting is broken....
9401 (defun org-sort-remove-invisible (s)
9402 (remove-text-properties 0 (length s) org-rm-props s)
9403 (while (string-match org-bracket-link-regexp s)
9404 (setq s (replace-match (if (match-end 2)
9405 (match-string 3 s)
9406 (match-string 1 s)) t t s)))
9409 (defun org-table-cut-region (beg end)
9410 "Copy region in table to the clipboard and blank all relevant fields."
9411 (interactive "r")
9412 (org-table-copy-region beg end 'cut))
9414 (defun org-table-copy-region (beg end &optional cut)
9415 "Copy rectangular region in table to clipboard.
9416 A special clipboard is used which can only be accessed
9417 with `org-table-paste-rectangle'."
9418 (interactive "rP")
9419 (let* (l01 c01 l02 c02 l1 c1 l2 c2 ic1 ic2
9420 region cols
9421 (rpl (if cut " " nil)))
9422 (goto-char beg)
9423 (org-table-check-inside-data-field)
9424 (setq l01 (org-current-line)
9425 c01 (org-table-current-column))
9426 (goto-char end)
9427 (org-table-check-inside-data-field)
9428 (setq l02 (org-current-line)
9429 c02 (org-table-current-column))
9430 (setq l1 (min l01 l02) l2 (max l01 l02)
9431 c1 (min c01 c02) c2 (max c01 c02))
9432 (catch 'exit
9433 (while t
9434 (catch 'nextline
9435 (if (> l1 l2) (throw 'exit t))
9436 (goto-line l1)
9437 (if (org-at-table-hline-p) (throw 'nextline (setq l1 (1+ l1))))
9438 (setq cols nil ic1 c1 ic2 c2)
9439 (while (< ic1 (1+ ic2))
9440 (push (org-table-get-field ic1 rpl) cols)
9441 (setq ic1 (1+ ic1)))
9442 (push (nreverse cols) region)
9443 (setq l1 (1+ l1)))))
9444 (setq org-table-clip (nreverse region))
9445 (if cut (org-table-align))
9446 org-table-clip))
9448 (defun org-table-paste-rectangle ()
9449 "Paste a rectangular region into a table.
9450 The upper right corner ends up in the current field. All involved fields
9451 will be overwritten. If the rectangle does not fit into the present table,
9452 the table is enlarged as needed. The process ignores horizontal separator
9453 lines."
9454 (interactive)
9455 (unless (and org-table-clip (listp org-table-clip))
9456 (error "First cut/copy a region to paste!"))
9457 (org-table-check-inside-data-field)
9458 (let* ((clip org-table-clip)
9459 (line (org-current-line))
9460 (col (org-table-current-column))
9461 (org-enable-table-editor t)
9462 (org-table-automatic-realign nil)
9463 c cols field)
9464 (while (setq cols (pop clip))
9465 (while (org-at-table-hline-p) (beginning-of-line 2))
9466 (if (not (org-at-table-p))
9467 (progn (end-of-line 0) (org-table-next-field)))
9468 (setq c col)
9469 (while (setq field (pop cols))
9470 (org-table-goto-column c nil 'force)
9471 (org-table-get-field nil field)
9472 (setq c (1+ c)))
9473 (beginning-of-line 2))
9474 (goto-line line)
9475 (org-table-goto-column col)
9476 (org-table-align)))
9478 (defun org-table-convert ()
9479 "Convert from `org-mode' table to table.el and back.
9480 Obviously, this only works within limits. When an Org-mode table is
9481 converted to table.el, all horizontal separator lines get lost, because
9482 table.el uses these as cell boundaries and has no notion of horizontal lines.
9483 A table.el table can be converted to an Org-mode table only if it does not
9484 do row or column spanning. Multiline cells will become multiple cells.
9485 Beware, Org-mode does not test if the table can be successfully converted - it
9486 blindly applies a recipe that works for simple tables."
9487 (interactive)
9488 (require 'table)
9489 (if (org-at-table.el-p)
9490 ;; convert to Org-mode table
9491 (let ((beg (move-marker (make-marker) (org-table-begin t)))
9492 (end (move-marker (make-marker) (org-table-end t))))
9493 (table-unrecognize-region beg end)
9494 (goto-char beg)
9495 (while (re-search-forward "^\\([ \t]*\\)\\+-.*\n" end t)
9496 (replace-match ""))
9497 (goto-char beg))
9498 (if (org-at-table-p)
9499 ;; convert to table.el table
9500 (let ((beg (move-marker (make-marker) (org-table-begin)))
9501 (end (move-marker (make-marker) (org-table-end))))
9502 ;; first, get rid of all horizontal lines
9503 (goto-char beg)
9504 (while (re-search-forward "^\\([ \t]*\\)|-.*\n" end t)
9505 (replace-match ""))
9506 ;; insert a hline before first
9507 (goto-char beg)
9508 (org-table-insert-hline 'above)
9509 (beginning-of-line -1)
9510 ;; insert a hline after each line
9511 (while (progn (beginning-of-line 3) (< (point) end))
9512 (org-table-insert-hline))
9513 (goto-char beg)
9514 (setq end (move-marker end (org-table-end)))
9515 ;; replace "+" at beginning and ending of hlines
9516 (while (re-search-forward "^\\([ \t]*\\)|-" end t)
9517 (replace-match "\\1+-"))
9518 (goto-char beg)
9519 (while (re-search-forward "-|[ \t]*$" end t)
9520 (replace-match "-+"))
9521 (goto-char beg)))))
9523 (defun org-table-wrap-region (arg)
9524 "Wrap several fields in a column like a paragraph.
9525 This is useful if you'd like to spread the contents of a field over several
9526 lines, in order to keep the table compact.
9528 If there is an active region, and both point and mark are in the same column,
9529 the text in the column is wrapped to minimum width for the given number of
9530 lines. Generally, this makes the table more compact. A prefix ARG may be
9531 used to change the number of desired lines. For example, `C-2 \\[org-table-wrap]'
9532 formats the selected text to two lines. If the region was longer than two
9533 lines, the remaining lines remain empty. A negative prefix argument reduces
9534 the current number of lines by that amount. The wrapped text is pasted back
9535 into the table. If you formatted it to more lines than it was before, fields
9536 further down in the table get overwritten - so you might need to make space in
9537 the table first.
9539 If there is no region, the current field is split at the cursor position and
9540 the text fragment to the right of the cursor is prepended to the field one
9541 line down.
9543 If there is no region, but you specify a prefix ARG, the current field gets
9544 blank, and the content is appended to the field above."
9545 (interactive "P")
9546 (org-table-check-inside-data-field)
9547 (if (org-region-active-p)
9548 ;; There is a region: fill as a paragraph
9549 (let* ((beg (region-beginning))
9550 (cline (save-excursion (goto-char beg) (org-current-line)))
9551 (ccol (save-excursion (goto-char beg) (org-table-current-column)))
9552 nlines)
9553 (org-table-cut-region (region-beginning) (region-end))
9554 (if (> (length (car org-table-clip)) 1)
9555 (error "Region must be limited to single column"))
9556 (setq nlines (if arg
9557 (if (< arg 1)
9558 (+ (length org-table-clip) arg)
9559 arg)
9560 (length org-table-clip)))
9561 (setq org-table-clip
9562 (mapcar 'list (org-wrap (mapconcat 'car org-table-clip " ")
9563 nil nlines)))
9564 (goto-line cline)
9565 (org-table-goto-column ccol)
9566 (org-table-paste-rectangle))
9567 ;; No region, split the current field at point
9568 (unless (org-get-alist-option org-M-RET-may-split-line 'table)
9569 (skip-chars-forward "^\r\n|"))
9570 (if arg
9571 ;; combine with field above
9572 (let ((s (org-table-blank-field))
9573 (col (org-table-current-column)))
9574 (beginning-of-line 0)
9575 (while (org-at-table-hline-p) (beginning-of-line 0))
9576 (org-table-goto-column col)
9577 (skip-chars-forward "^|")
9578 (skip-chars-backward " ")
9579 (insert " " (org-trim s))
9580 (org-table-align))
9581 ;; split field
9582 (if (looking-at "\\([^|]+\\)+|")
9583 (let ((s (match-string 1)))
9584 (replace-match " |")
9585 (goto-char (match-beginning 0))
9586 (org-table-next-row)
9587 (insert (org-trim s) " ")
9588 (org-table-align))
9589 (org-table-next-row)))))
9591 (defvar org-field-marker nil)
9593 (defun org-table-edit-field (arg)
9594 "Edit table field in a different window.
9595 This is mainly useful for fields that contain hidden parts.
9596 When called with a \\[universal-argument] prefix, just make the full field visible so that
9597 it can be edited in place."
9598 (interactive "P")
9599 (if arg
9600 (let ((b (save-excursion (skip-chars-backward "^|") (point)))
9601 (e (save-excursion (skip-chars-forward "^|\r\n") (point))))
9602 (remove-text-properties b e '(org-cwidth t invisible t
9603 display t intangible t))
9604 (if (and (boundp 'font-lock-mode) font-lock-mode)
9605 (font-lock-fontify-block)))
9606 (let ((pos (move-marker (make-marker) (point)))
9607 (field (org-table-get-field))
9608 (cw (current-window-configuration))
9610 (org-switch-to-buffer-other-window "*Org tmp*")
9611 (erase-buffer)
9612 (insert "#\n# Edit field and finish with C-c C-c\n#\n")
9613 (let ((org-inhibit-startup t)) (org-mode))
9614 (goto-char (setq p (point-max)))
9615 (insert (org-trim field))
9616 (remove-text-properties p (point-max)
9617 '(invisible t org-cwidth t display t
9618 intangible t))
9619 (goto-char p)
9620 (org-set-local 'org-finish-function 'org-table-finish-edit-field)
9621 (org-set-local 'org-window-configuration cw)
9622 (org-set-local 'org-field-marker pos)
9623 (message "Edit and finish with C-c C-c"))))
9625 (defun org-table-finish-edit-field ()
9626 "Finish editing a table data field.
9627 Remove all newline characters, insert the result into the table, realign
9628 the table and kill the editing buffer."
9629 (let ((pos org-field-marker)
9630 (cw org-window-configuration)
9631 (cb (current-buffer))
9632 text)
9633 (goto-char (point-min))
9634 (while (re-search-forward "^#.*\n?" nil t) (replace-match ""))
9635 (while (re-search-forward "\\([ \t]*\n[ \t]*\\)+" nil t)
9636 (replace-match " "))
9637 (setq text (org-trim (buffer-string)))
9638 (set-window-configuration cw)
9639 (kill-buffer cb)
9640 (select-window (get-buffer-window (marker-buffer pos)))
9641 (goto-char pos)
9642 (move-marker pos nil)
9643 (org-table-check-inside-data-field)
9644 (org-table-get-field nil text)
9645 (org-table-align)
9646 (message "New field value inserted")))
9648 (defun org-trim (s)
9649 "Remove whitespace at beginning and end of string."
9650 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
9651 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
9654 (defun org-wrap (string &optional width lines)
9655 "Wrap string to either a number of lines, or a width in characters.
9656 If WIDTH is non-nil, the string is wrapped to that width, however many lines
9657 that costs. If there is a word longer than WIDTH, the text is actually
9658 wrapped to the length of that word.
9659 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
9660 many lines, whatever width that takes.
9661 The return value is a list of lines, without newlines at the end."
9662 (let* ((words (org-split-string string "[ \t\n]+"))
9663 (maxword (apply 'max (mapcar 'org-string-width words)))
9664 w ll)
9665 (cond (width
9666 (org-do-wrap words (max maxword width)))
9667 (lines
9668 (setq w maxword)
9669 (setq ll (org-do-wrap words maxword))
9670 (if (<= (length ll) lines)
9672 (setq ll words)
9673 (while (> (length ll) lines)
9674 (setq w (1+ w))
9675 (setq ll (org-do-wrap words w)))
9676 ll))
9677 (t (error "Cannot wrap this")))))
9680 (defun org-do-wrap (words width)
9681 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
9682 (let (lines line)
9683 (while words
9684 (setq line (pop words))
9685 (while (and words (< (+ (length line) (length (car words))) width))
9686 (setq line (concat line " " (pop words))))
9687 (setq lines (push line lines)))
9688 (nreverse lines)))
9690 (defun org-split-string (string &optional separators)
9691 "Splits STRING into substrings at SEPARATORS.
9692 No empty strings are returned if there are matches at the beginning
9693 and end of string."
9694 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
9695 (start 0)
9696 notfirst
9697 (list nil))
9698 (while (and (string-match rexp string
9699 (if (and notfirst
9700 (= start (match-beginning 0))
9701 (< start (length string)))
9702 (1+ start) start))
9703 (< (match-beginning 0) (length string)))
9704 (setq notfirst t)
9705 (or (eq (match-beginning 0) 0)
9706 (and (eq (match-beginning 0) (match-end 0))
9707 (eq (match-beginning 0) start))
9708 (setq list
9709 (cons (substring string start (match-beginning 0))
9710 list)))
9711 (setq start (match-end 0)))
9712 (or (eq start (length string))
9713 (setq list
9714 (cons (substring string start)
9715 list)))
9716 (nreverse list)))
9718 (defun org-table-map-tables (function)
9719 "Apply FUNCTION to the start of all tables in the buffer."
9720 (save-excursion
9721 (save-restriction
9722 (widen)
9723 (goto-char (point-min))
9724 (while (re-search-forward org-table-any-line-regexp nil t)
9725 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
9726 (beginning-of-line 1)
9727 (if (looking-at org-table-line-regexp)
9728 (save-excursion (funcall function)))
9729 (re-search-forward org-table-any-border-regexp nil 1))))
9730 (message "Mapping tables: done"))
9732 (defvar org-timecnt) ; dynamically scoped parameter
9734 (defun org-table-sum (&optional beg end nlast)
9735 "Sum numbers in region of current table column.
9736 The result will be displayed in the echo area, and will be available
9737 as kill to be inserted with \\[yank].
9739 If there is an active region, it is interpreted as a rectangle and all
9740 numbers in that rectangle will be summed. If there is no active
9741 region and point is located in a table column, sum all numbers in that
9742 column.
9744 If at least one number looks like a time HH:MM or HH:MM:SS, all other
9745 numbers are assumed to be times as well (in decimal hours) and the
9746 numbers are added as such.
9748 If NLAST is a number, only the NLAST fields will actually be summed."
9749 (interactive)
9750 (save-excursion
9751 (let (col (org-timecnt 0) diff h m s org-table-clip)
9752 (cond
9753 ((and beg end)) ; beg and end given explicitly
9754 ((org-region-active-p)
9755 (setq beg (region-beginning) end (region-end)))
9757 (setq col (org-table-current-column))
9758 (goto-char (org-table-begin))
9759 (unless (re-search-forward "^[ \t]*|[^-]" nil t)
9760 (error "No table data"))
9761 (org-table-goto-column col)
9762 (setq beg (point))
9763 (goto-char (org-table-end))
9764 (unless (re-search-backward "^[ \t]*|[^-]" nil t)
9765 (error "No table data"))
9766 (org-table-goto-column col)
9767 (setq end (point))))
9768 (let* ((items (apply 'append (org-table-copy-region beg end)))
9769 (items1 (cond ((not nlast) items)
9770 ((>= nlast (length items)) items)
9771 (t (setq items (reverse items))
9772 (setcdr (nthcdr (1- nlast) items) nil)
9773 (nreverse items))))
9774 (numbers (delq nil (mapcar 'org-table-get-number-for-summing
9775 items1)))
9776 (res (apply '+ numbers))
9777 (sres (if (= org-timecnt 0)
9778 (format "%g" res)
9779 (setq diff (* 3600 res)
9780 h (floor (/ diff 3600)) diff (mod diff 3600)
9781 m (floor (/ diff 60)) diff (mod diff 60)
9782 s diff)
9783 (format "%d:%02d:%02d" h m s))))
9784 (kill-new sres)
9785 (if (interactive-p)
9786 (message "%s"
9787 (substitute-command-keys
9788 (format "Sum of %d items: %-20s (\\[yank] will insert result into buffer)"
9789 (length numbers) sres))))
9790 sres))))
9792 (defun org-table-get-number-for-summing (s)
9793 (let (n)
9794 (if (string-match "^ *|? *" s)
9795 (setq s (replace-match "" nil nil s)))
9796 (if (string-match " *|? *$" s)
9797 (setq s (replace-match "" nil nil s)))
9798 (setq n (string-to-number s))
9799 (cond
9800 ((and (string-match "0" s)
9801 (string-match "\\`[-+ \t0.edED]+\\'" s)) 0)
9802 ((string-match "\\`[ \t]+\\'" s) nil)
9803 ((string-match "\\`\\([0-9]+\\):\\([0-9]+\\)\\(:\\([0-9]+\\)\\)?\\'" s)
9804 (let ((h (string-to-number (or (match-string 1 s) "0")))
9805 (m (string-to-number (or (match-string 2 s) "0")))
9806 (s (string-to-number (or (match-string 4 s) "0"))))
9807 (if (boundp 'org-timecnt) (setq org-timecnt (1+ org-timecnt)))
9808 (* 1.0 (+ h (/ m 60.0) (/ s 3600.0)))))
9809 ((equal n 0) nil)
9810 (t n))))
9812 (defun org-table-current-field-formula (&optional key noerror)
9813 "Return the formula active for the current field.
9814 Assumes that specials are in place.
9815 If KEY is given, return the key to this formula.
9816 Otherwise return the formula preceeded with \"=\" or \":=\"."
9817 (let* ((name (car (rassoc (list (org-current-line)
9818 (org-table-current-column))
9819 org-table-named-field-locations)))
9820 (col (org-table-current-column))
9821 (scol (int-to-string col))
9822 (ref (format "@%d$%d" (org-table-current-dline) col))
9823 (stored-list (org-table-get-stored-formulas noerror))
9824 (ass (or (assoc name stored-list)
9825 (assoc ref stored-list)
9826 (assoc scol stored-list))))
9827 (if key
9828 (car ass)
9829 (if ass (concat (if (string-match "^[0-9]+$" (car ass)) "=" ":=")
9830 (cdr ass))))))
9832 (defun org-table-get-formula (&optional equation named)
9833 "Read a formula from the minibuffer, offer stored formula as default.
9834 When NAMED is non-nil, look for a named equation."
9835 (let* ((stored-list (org-table-get-stored-formulas))
9836 (name (car (rassoc (list (org-current-line)
9837 (org-table-current-column))
9838 org-table-named-field-locations)))
9839 (ref (format "@%d$%d" (org-table-current-dline)
9840 (org-table-current-column)))
9841 (refass (assoc ref stored-list))
9842 (scol (if named
9843 (if name name ref)
9844 (int-to-string (org-table-current-column))))
9845 (dummy (and (or name refass) (not named)
9846 (not (y-or-n-p "Replace field formula with column formula? " ))
9847 (error "Abort")))
9848 (name (or name ref))
9849 (org-table-may-need-update nil)
9850 (stored (cdr (assoc scol stored-list)))
9851 (eq (cond
9852 ((and stored equation (string-match "^ *=? *$" equation))
9853 stored)
9854 ((stringp equation)
9855 equation)
9856 (t (org-table-formula-from-user
9857 (read-string
9858 (org-table-formula-to-user
9859 (format "%s formula %s%s="
9860 (if named "Field" "Column")
9861 (if (member (string-to-char scol) '(?$ ?@)) "" "$")
9862 scol))
9863 (if stored (org-table-formula-to-user stored) "")
9864 'org-table-formula-history
9865 )))))
9866 mustsave)
9867 (when (not (string-match "\\S-" eq))
9868 ;; remove formula
9869 (setq stored-list (delq (assoc scol stored-list) stored-list))
9870 (org-table-store-formulas stored-list)
9871 (error "Formula removed"))
9872 (if (string-match "^ *=?" eq) (setq eq (replace-match "" t t eq)))
9873 (if (string-match " *$" eq) (setq eq (replace-match "" t t eq)))
9874 (if (and name (not named))
9875 ;; We set the column equation, delete the named one.
9876 (setq stored-list (delq (assoc name stored-list) stored-list)
9877 mustsave t))
9878 (if stored
9879 (setcdr (assoc scol stored-list) eq)
9880 (setq stored-list (cons (cons scol eq) stored-list)))
9881 (if (or mustsave (not (equal stored eq)))
9882 (org-table-store-formulas stored-list))
9883 eq))
9885 (defun org-table-store-formulas (alist)
9886 "Store the list of formulas below the current table."
9887 (setq alist (sort alist 'org-table-formula-less-p))
9888 (save-excursion
9889 (goto-char (org-table-end))
9890 (if (looking-at "\\([ \t]*\n\\)*#\\+TBLFM:\\(.*\n?\\)")
9891 (progn
9892 ;; don't overwrite TBLFM, we might use text properties to store stuff
9893 (goto-char (match-beginning 2))
9894 (delete-region (match-beginning 2) (match-end 0)))
9895 (insert "#+TBLFM:"))
9896 (insert " "
9897 (mapconcat (lambda (x)
9898 (concat
9899 (if (equal (string-to-char (car x)) ?@) "" "$")
9900 (car x) "=" (cdr x)))
9901 alist "::")
9902 "\n")))
9904 (defsubst org-table-formula-make-cmp-string (a)
9905 (when (string-match "^\\(@\\([0-9]+\\)\\)?\\(\\$?\\([0-9]+\\)\\)?\\(\\$?[a-zA-Z0-9]+\\)?" a)
9906 (concat
9907 (if (match-end 2) (format "@%05d" (string-to-number (match-string 2 a))) "")
9908 (if (match-end 4) (format "$%05d" (string-to-number (match-string 4 a))) "")
9909 (if (match-end 5) (concat "@@" (match-string 5 a))))))
9911 (defun org-table-formula-less-p (a b)
9912 "Compare two formulas for sorting."
9913 (let ((as (org-table-formula-make-cmp-string (car a)))
9914 (bs (org-table-formula-make-cmp-string (car b))))
9915 (and as bs (string< as bs))))
9917 (defun org-table-get-stored-formulas (&optional noerror)
9918 "Return an alist with the stored formulas directly after current table."
9919 (interactive)
9920 (let (scol eq eq-alist strings string seen)
9921 (save-excursion
9922 (goto-char (org-table-end))
9923 (when (looking-at "\\([ \t]*\n\\)*#\\+TBLFM: *\\(.*\\)")
9924 (setq strings (org-split-string (match-string 2) " *:: *"))
9925 (while (setq string (pop strings))
9926 (when (string-match "\\(@[0-9]+\\$[0-9]+\\|\\$\\([a-zA-Z0-9]+\\)\\) *= *\\(.*[^ \t]\\)" string)
9927 (setq scol (if (match-end 2)
9928 (match-string 2 string)
9929 (match-string 1 string))
9930 eq (match-string 3 string)
9931 eq-alist (cons (cons scol eq) eq-alist))
9932 (if (member scol seen)
9933 (if noerror
9934 (progn
9935 (message "Double definition `$%s=' in TBLFM line, please fix by hand" scol)
9936 (ding)
9937 (sit-for 2))
9938 (error "Double definition `$%s=' in TBLFM line, please fix by hand" scol))
9939 (push scol seen))))))
9940 (nreverse eq-alist)))
9942 (defun org-table-fix-formulas (key replace &optional limit delta remove)
9943 "Modify the equations after the table structure has been edited.
9944 KEY is \"@\" or \"$\". REPLACE is an alist of numbers to replace.
9945 For all numbers larger than LIMIT, shift them by DELTA."
9946 (save-excursion
9947 (goto-char (org-table-end))
9948 (when (looking-at "#\\+TBLFM:")
9949 (let ((re (concat key "\\([0-9]+\\)"))
9950 (re2
9951 (when remove
9952 (if (equal key "$")
9953 (format "\\(@[0-9]+\\)?\\$%d=.*?\\(::\\|$\\)" remove)
9954 (format "@%d\\$[0-9]+=.*?\\(::\\|$\\)" remove))))
9955 s n a)
9956 (when remove
9957 (while (re-search-forward re2 (point-at-eol) t)
9958 (replace-match "")))
9959 (while (re-search-forward re (point-at-eol) t)
9960 (setq s (match-string 1) n (string-to-number s))
9961 (cond
9962 ((setq a (assoc s replace))
9963 (replace-match (concat key (cdr a)) t t))
9964 ((and limit (> n limit))
9965 (replace-match (concat key (int-to-string (+ n delta))) t t))))))))
9967 (defun org-table-get-specials ()
9968 "Get the column names and local parameters for this table."
9969 (save-excursion
9970 (let ((beg (org-table-begin)) (end (org-table-end))
9971 names name fields fields1 field cnt
9972 c v l line col types dlines hlines)
9973 (setq org-table-column-names nil
9974 org-table-local-parameters nil
9975 org-table-named-field-locations nil
9976 org-table-current-begin-line nil
9977 org-table-current-begin-pos nil
9978 org-table-current-line-types nil)
9979 (goto-char beg)
9980 (when (re-search-forward "^[ \t]*| *! *\\(|.*\\)" end t)
9981 (setq names (org-split-string (match-string 1) " *| *")
9982 cnt 1)
9983 (while (setq name (pop names))
9984 (setq cnt (1+ cnt))
9985 (if (string-match "^[a-zA-Z][a-zA-Z0-9]*$" name)
9986 (push (cons name (int-to-string cnt)) org-table-column-names))))
9987 (setq org-table-column-names (nreverse org-table-column-names))
9988 (setq org-table-column-name-regexp
9989 (concat "\\$\\(" (mapconcat 'car org-table-column-names "\\|") "\\)\\>"))
9990 (goto-char beg)
9991 (while (re-search-forward "^[ \t]*| *\\$ *\\(|.*\\)" end t)
9992 (setq fields (org-split-string (match-string 1) " *| *"))
9993 (while (setq field (pop fields))
9994 (if (string-match "^\\([a-zA-Z][_a-zA-Z0-9]*\\|%\\) *= *\\(.*\\)" field)
9995 (push (cons (match-string 1 field) (match-string 2 field))
9996 org-table-local-parameters))))
9997 (goto-char beg)
9998 (while (re-search-forward "^[ \t]*| *\\([_^]\\) *\\(|.*\\)" end t)
9999 (setq c (match-string 1)
10000 fields (org-split-string (match-string 2) " *| *"))
10001 (save-excursion
10002 (beginning-of-line (if (equal c "_") 2 0))
10003 (setq line (org-current-line) col 1)
10004 (and (looking-at "^[ \t]*|[^|]*\\(|.*\\)")
10005 (setq fields1 (org-split-string (match-string 1) " *| *"))))
10006 (while (and fields1 (setq field (pop fields)))
10007 (setq v (pop fields1) col (1+ col))
10008 (when (and (stringp field) (stringp v)
10009 (string-match "^[a-zA-Z][a-zA-Z0-9]*$" field))
10010 (push (cons field v) org-table-local-parameters)
10011 (push (list field line col) org-table-named-field-locations))))
10012 ;; Analyse the line types
10013 (goto-char beg)
10014 (setq org-table-current-begin-line (org-current-line)
10015 org-table-current-begin-pos (point)
10016 l org-table-current-begin-line)
10017 (while (looking-at "[ \t]*|\\(-\\)?")
10018 (push (if (match-end 1) 'hline 'dline) types)
10019 (if (match-end 1) (push l hlines) (push l dlines))
10020 (beginning-of-line 2)
10021 (setq l (1+ l)))
10022 (setq org-table-current-line-types (apply 'vector (nreverse types))
10023 org-table-dlines (apply 'vector (cons nil (nreverse dlines)))
10024 org-table-hlines (apply 'vector (cons nil (nreverse hlines)))))))
10026 (defun org-table-maybe-eval-formula ()
10027 "Check if the current field starts with \"=\" or \":=\".
10028 If yes, store the formula and apply it."
10029 ;; We already know we are in a table. Get field will only return a formula
10030 ;; when appropriate. It might return a separator line, but no problem.
10031 (when org-table-formula-evaluate-inline
10032 (let* ((field (org-trim (or (org-table-get-field) "")))
10033 named eq)
10034 (when (string-match "^:?=\\(.*\\)" field)
10035 (setq named (equal (string-to-char field) ?:)
10036 eq (match-string 1 field))
10037 (if (or (fboundp 'calc-eval)
10038 (equal (substring eq 0 (min 2 (length eq))) "'("))
10039 (org-table-eval-formula (if named '(4) nil)
10040 (org-table-formula-from-user eq))
10041 (error "Calc does not seem to be installed, and is needed to evaluate the formula"))))))
10043 (defvar org-recalc-commands nil
10044 "List of commands triggering the recalculation of a line.
10045 Will be filled automatically during use.")
10047 (defvar org-recalc-marks
10048 '((" " . "Unmarked: no special line, no automatic recalculation")
10049 ("#" . "Automatically recalculate this line upon TAB, RET, and C-c C-c in the line")
10050 ("*" . "Recalculate only when entire table is recalculated with `C-u C-c *'")
10051 ("!" . "Column name definition line. Reference in formula as $name.")
10052 ("$" . "Parameter definition line name=value. Reference in formula as $name.")
10053 ("_" . "Names for values in row below this one.")
10054 ("^" . "Names for values in row above this one.")))
10056 (defun org-table-rotate-recalc-marks (&optional newchar)
10057 "Rotate the recalculation mark in the first column.
10058 If in any row, the first field is not consistent with a mark,
10059 insert a new column for the markers.
10060 When there is an active region, change all the lines in the region,
10061 after prompting for the marking character.
10062 After each change, a message will be displayed indicating the meaning
10063 of the new mark."
10064 (interactive)
10065 (unless (org-at-table-p) (error "Not at a table"))
10066 (let* ((marks (append (mapcar 'car org-recalc-marks) '(" ")))
10067 (beg (org-table-begin))
10068 (end (org-table-end))
10069 (l (org-current-line))
10070 (l1 (if (org-region-active-p) (org-current-line (region-beginning))))
10071 (l2 (if (org-region-active-p) (org-current-line (region-end))))
10072 (have-col
10073 (save-excursion
10074 (goto-char beg)
10075 (not (re-search-forward "^[ \t]*|[^-|][^|]*[^#!$*_^| \t][^|]*|" end t))))
10076 (col (org-table-current-column))
10077 (forcenew (car (assoc newchar org-recalc-marks)))
10078 epos new)
10079 (when l1
10080 (message "Change region to what mark? Type # * ! $ or SPC: ")
10081 (setq newchar (char-to-string (read-char-exclusive))
10082 forcenew (car (assoc newchar org-recalc-marks))))
10083 (if (and newchar (not forcenew))
10084 (error "Invalid NEWCHAR `%s' in `org-table-rotate-recalc-marks'"
10085 newchar))
10086 (if l1 (goto-line l1))
10087 (save-excursion
10088 (beginning-of-line 1)
10089 (unless (looking-at org-table-dataline-regexp)
10090 (error "Not at a table data line")))
10091 (unless have-col
10092 (org-table-goto-column 1)
10093 (org-table-insert-column)
10094 (org-table-goto-column (1+ col)))
10095 (setq epos (point-at-eol))
10096 (save-excursion
10097 (beginning-of-line 1)
10098 (org-table-get-field
10099 1 (if (looking-at "^[ \t]*| *\\([#!$*^_ ]\\) *|")
10100 (concat " "
10101 (setq new (or forcenew
10102 (cadr (member (match-string 1) marks))))
10103 " ")
10104 " # ")))
10105 (if (and l1 l2)
10106 (progn
10107 (goto-line l1)
10108 (while (progn (beginning-of-line 2) (not (= (org-current-line) l2)))
10109 (and (looking-at org-table-dataline-regexp)
10110 (org-table-get-field 1 (concat " " new " "))))
10111 (goto-line l1)))
10112 (if (not (= epos (point-at-eol))) (org-table-align))
10113 (goto-line l)
10114 (and (interactive-p) (message "%s" (cdr (assoc new org-recalc-marks))))))
10116 (defun org-table-maybe-recalculate-line ()
10117 "Recompute the current line if marked for it, and if we haven't just done it."
10118 (interactive)
10119 (and org-table-allow-automatic-line-recalculation
10120 (not (and (memq last-command org-recalc-commands)
10121 (equal org-last-recalc-line (org-current-line))))
10122 (save-excursion (beginning-of-line 1)
10123 (looking-at org-table-auto-recalculate-regexp))
10124 (org-table-recalculate) t))
10126 (defvar org-table-formula-debug nil
10127 "Non-nil means, debug table formulas.
10128 When nil, simply write \"#ERROR\" in corrupted fields.")
10129 (make-variable-buffer-local 'org-table-formula-debug)
10131 (defvar modes)
10132 (defsubst org-set-calc-mode (var &optional value)
10133 (if (stringp var)
10134 (setq var (assoc var '(("D" calc-angle-mode deg)
10135 ("R" calc-angle-mode rad)
10136 ("F" calc-prefer-frac t)
10137 ("S" calc-symbolic-mode t)))
10138 value (nth 2 var) var (nth 1 var)))
10139 (if (memq var modes)
10140 (setcar (cdr (memq var modes)) value)
10141 (cons var (cons value modes)))
10142 modes)
10144 (defun org-table-eval-formula (&optional arg equation
10145 suppress-align suppress-const
10146 suppress-store suppress-analysis)
10147 "Replace the table field value at the cursor by the result of a calculation.
10149 This function makes use of Dave Gillespie's Calc package, in my view the
10150 most exciting program ever written for GNU Emacs. So you need to have Calc
10151 installed in order to use this function.
10153 In a table, this command replaces the value in the current field with the
10154 result of a formula. It also installs the formula as the \"current\" column
10155 formula, by storing it in a special line below the table. When called
10156 with a `C-u' prefix, the current field must ba a named field, and the
10157 formula is installed as valid in only this specific field.
10159 When called with two `C-u' prefixes, insert the active equation
10160 for the field back into the current field, so that it can be
10161 edited there. This is useful in order to use \\[org-table-show-reference]
10162 to check the referenced fields.
10164 When called, the command first prompts for a formula, which is read in
10165 the minibuffer. Previously entered formulas are available through the
10166 history list, and the last used formula is offered as a default.
10167 These stored formulas are adapted correctly when moving, inserting, or
10168 deleting columns with the corresponding commands.
10170 The formula can be any algebraic expression understood by the Calc package.
10171 For details, see the Org-mode manual.
10173 This function can also be called from Lisp programs and offers
10174 additional arguments: EQUATION can be the formula to apply. If this
10175 argument is given, the user will not be prompted. SUPPRESS-ALIGN is
10176 used to speed-up recursive calls by by-passing unnecessary aligns.
10177 SUPPRESS-CONST suppresses the interpretation of constants in the
10178 formula, assuming that this has been done already outside the function.
10179 SUPPRESS-STORE means the formula should not be stored, either because
10180 it is already stored, or because it is a modified equation that should
10181 not overwrite the stored one."
10182 (interactive "P")
10183 (org-table-check-inside-data-field)
10184 (or suppress-analysis (org-table-get-specials))
10185 (if (equal arg '(16))
10186 (let ((eq (org-table-current-field-formula)))
10187 (or eq (error "No equation active for current field"))
10188 (org-table-get-field nil eq)
10189 (org-table-align)
10190 (setq org-table-may-need-update t))
10191 (let* (fields
10192 (ndown (if (integerp arg) arg 1))
10193 (org-table-automatic-realign nil)
10194 (case-fold-search nil)
10195 (down (> ndown 1))
10196 (formula (if (and equation suppress-store)
10197 equation
10198 (org-table-get-formula equation (equal arg '(4)))))
10199 (n0 (org-table-current-column))
10200 (modes (copy-sequence org-calc-default-modes))
10201 (numbers nil) ; was a variable, now fixed default
10202 (keep-empty nil)
10203 n form form0 bw fmt x ev orig c lispp literal)
10204 ;; Parse the format string. Since we have a lot of modes, this is
10205 ;; a lot of work. However, I think calc still uses most of the time.
10206 (if (string-match ";" formula)
10207 (let ((tmp (org-split-string formula ";")))
10208 (setq formula (car tmp)
10209 fmt (concat (cdr (assoc "%" org-table-local-parameters))
10210 (nth 1 tmp)))
10211 (while (string-match "\\([pnfse]\\)\\(-?[0-9]+\\)" fmt)
10212 (setq c (string-to-char (match-string 1 fmt))
10213 n (string-to-number (match-string 2 fmt)))
10214 (if (= c ?p)
10215 (setq modes (org-set-calc-mode 'calc-internal-prec n))
10216 (setq modes (org-set-calc-mode
10217 'calc-float-format
10218 (list (cdr (assoc c '((?n . float) (?f . fix)
10219 (?s . sci) (?e . eng))))
10220 n))))
10221 (setq fmt (replace-match "" t t fmt)))
10222 (if (string-match "[NT]" fmt)
10223 (setq numbers (equal (match-string 0 fmt) "N")
10224 fmt (replace-match "" t t fmt)))
10225 (if (string-match "L" fmt)
10226 (setq literal t
10227 fmt (replace-match "" t t fmt)))
10228 (if (string-match "E" fmt)
10229 (setq keep-empty t
10230 fmt (replace-match "" t t fmt)))
10231 (while (string-match "[DRFS]" fmt)
10232 (setq modes (org-set-calc-mode (match-string 0 fmt)))
10233 (setq fmt (replace-match "" t t fmt)))
10234 (unless (string-match "\\S-" fmt)
10235 (setq fmt nil))))
10236 (if (and (not suppress-const) org-table-formula-use-constants)
10237 (setq formula (org-table-formula-substitute-names formula)))
10238 (setq orig (or (get-text-property 1 :orig-formula formula) "?"))
10239 (while (> ndown 0)
10240 (setq fields (org-split-string
10241 (org-no-properties
10242 (buffer-substring (point-at-bol) (point-at-eol)))
10243 " *| *"))
10244 (if (eq numbers t)
10245 (setq fields (mapcar
10246 (lambda (x) (number-to-string (string-to-number x)))
10247 fields)))
10248 (setq ndown (1- ndown))
10249 (setq form (copy-sequence formula)
10250 lispp (and (> (length form) 2)(equal (substring form 0 2) "'(")))
10251 (if (and lispp literal) (setq lispp 'literal))
10252 ;; Check for old vertical references
10253 (setq form (org-rewrite-old-row-references form))
10254 ;; Insert complex ranges
10255 (while (string-match org-table-range-regexp form)
10256 (setq form
10257 (replace-match
10258 (save-match-data
10259 (org-table-make-reference
10260 (org-table-get-range (match-string 0 form) nil n0)
10261 keep-empty numbers lispp))
10262 t t form)))
10263 ;; Insert simple ranges
10264 (while (string-match "\\$\\([0-9]+\\)\\.\\.\\$\\([0-9]+\\)" form)
10265 (setq form
10266 (replace-match
10267 (save-match-data
10268 (org-table-make-reference
10269 (org-sublist
10270 fields (string-to-number (match-string 1 form))
10271 (string-to-number (match-string 2 form)))
10272 keep-empty numbers lispp))
10273 t t form)))
10274 (setq form0 form)
10275 ;; Insert the references to fields in same row
10276 (while (string-match "\\$\\([0-9]+\\)" form)
10277 (setq n (string-to-number (match-string 1 form))
10278 x (nth (1- (if (= n 0) n0 n)) fields))
10279 (unless x (error "Invalid field specifier \"%s\""
10280 (match-string 0 form)))
10281 (setq form (replace-match
10282 (save-match-data
10283 (org-table-make-reference x nil numbers lispp))
10284 t t form)))
10286 (if lispp
10287 (setq ev (condition-case nil
10288 (eval (eval (read form)))
10289 (error "#ERROR"))
10290 ev (if (numberp ev) (number-to-string ev) ev))
10291 (or (fboundp 'calc-eval)
10292 (error "Calc does not seem to be installed, and is needed to evaluate the formula"))
10293 (setq ev (calc-eval (cons form modes)
10294 (if numbers 'num))))
10296 (when org-table-formula-debug
10297 (with-output-to-temp-buffer "*Substitution History*"
10298 (princ (format "Substitution history of formula
10299 Orig: %s
10300 $xyz-> %s
10301 @r$c-> %s
10302 $1-> %s\n" orig formula form0 form))
10303 (if (listp ev)
10304 (princ (format " %s^\nError: %s"
10305 (make-string (car ev) ?\-) (nth 1 ev)))
10306 (princ (format "Result: %s\nFormat: %s\nFinal: %s"
10307 ev (or fmt "NONE")
10308 (if fmt (format fmt (string-to-number ev)) ev)))))
10309 (setq bw (get-buffer-window "*Substitution History*"))
10310 (shrink-window-if-larger-than-buffer bw)
10311 (unless (and (interactive-p) (not ndown))
10312 (unless (let (inhibit-redisplay)
10313 (y-or-n-p "Debugging Formula. Continue to next? "))
10314 (org-table-align)
10315 (error "Abort"))
10316 (delete-window bw)
10317 (message "")))
10318 (if (listp ev) (setq fmt nil ev "#ERROR"))
10319 (org-table-justify-field-maybe
10320 (if fmt (format fmt (string-to-number ev)) ev))
10321 (if (and down (> ndown 0) (looking-at ".*\n[ \t]*|[^-]"))
10322 (call-interactively 'org-return)
10323 (setq ndown 0)))
10324 (and down (org-table-maybe-recalculate-line))
10325 (or suppress-align (and org-table-may-need-update
10326 (org-table-align))))))
10328 (defun org-table-put-field-property (prop value)
10329 (save-excursion
10330 (put-text-property (progn (skip-chars-backward "^|") (point))
10331 (progn (skip-chars-forward "^|") (point))
10332 prop value)))
10334 (defun org-table-get-range (desc &optional tbeg col highlight)
10335 "Get a calc vector from a column, accorting to descriptor DESC.
10336 Optional arguments TBEG and COL can give the beginning of the table and
10337 the current column, to avoid unnecessary parsing.
10338 HIGHLIGHT means, just highlight the range."
10339 (if (not (equal (string-to-char desc) ?@))
10340 (setq desc (concat "@" desc)))
10341 (save-excursion
10342 (or tbeg (setq tbeg (org-table-begin)))
10343 (or col (setq col (org-table-current-column)))
10344 (let ((thisline (org-current-line))
10345 beg end c1 c2 r1 r2 rangep tmp)
10346 (unless (string-match org-table-range-regexp desc)
10347 (error "Invalid table range specifier `%s'" desc))
10348 (setq rangep (match-end 3)
10349 r1 (and (match-end 1) (match-string 1 desc))
10350 r2 (and (match-end 4) (match-string 4 desc))
10351 c1 (and (match-end 2) (substring (match-string 2 desc) 1))
10352 c2 (and (match-end 5) (substring (match-string 5 desc) 1)))
10354 (and c1 (setq c1 (+ (string-to-number c1)
10355 (if (memq (string-to-char c1) '(?- ?+)) col 0))))
10356 (and c2 (setq c2 (+ (string-to-number c2)
10357 (if (memq (string-to-char c2) '(?- ?+)) col 0))))
10358 (if (equal r1 "") (setq r1 nil))
10359 (if (equal r2 "") (setq r2 nil))
10360 (if r1 (setq r1 (org-table-get-descriptor-line r1)))
10361 (if r2 (setq r2 (org-table-get-descriptor-line r2)))
10362 ; (setq r2 (or r2 r1) c2 (or c2 c1))
10363 (if (not r1) (setq r1 thisline))
10364 (if (not r2) (setq r2 thisline))
10365 (if (not c1) (setq c1 col))
10366 (if (not c2) (setq c2 col))
10367 (if (or (not rangep) (and (= r1 r2) (= c1 c2)))
10368 ;; just one field
10369 (progn
10370 (goto-line r1)
10371 (while (not (looking-at org-table-dataline-regexp))
10372 (beginning-of-line 2))
10373 (prog1 (org-trim (org-table-get-field c1))
10374 (if highlight (org-table-highlight-rectangle (point) (point)))))
10375 ;; A range, return a vector
10376 ;; First sort the numbers to get a regular ractangle
10377 (if (< r2 r1) (setq tmp r1 r1 r2 r2 tmp))
10378 (if (< c2 c1) (setq tmp c1 c1 c2 c2 tmp))
10379 (goto-line r1)
10380 (while (not (looking-at org-table-dataline-regexp))
10381 (beginning-of-line 2))
10382 (org-table-goto-column c1)
10383 (setq beg (point))
10384 (goto-line r2)
10385 (while (not (looking-at org-table-dataline-regexp))
10386 (beginning-of-line 0))
10387 (org-table-goto-column c2)
10388 (setq end (point))
10389 (if highlight
10390 (org-table-highlight-rectangle
10391 beg (progn (skip-chars-forward "^|\n") (point))))
10392 ;; return string representation of calc vector
10393 (mapcar 'org-trim
10394 (apply 'append (org-table-copy-region beg end)))))))
10396 (defun org-table-get-descriptor-line (desc &optional cline bline table)
10397 "Analyze descriptor DESC and retrieve the corresponding line number.
10398 The cursor is currently in line CLINE, the table begins in line BLINE,
10399 and TABLE is a vector with line types."
10400 (if (string-match "^[0-9]+$" desc)
10401 (aref org-table-dlines (string-to-number desc))
10402 (setq cline (or cline (org-current-line))
10403 bline (or bline org-table-current-begin-line)
10404 table (or table org-table-current-line-types))
10405 (if (or
10406 (not (string-match "^\\(\\([-+]\\)?\\(I+\\)\\)?\\(\\([-+]\\)?\\([0-9]+\\)\\)?" desc))
10407 ;; 1 2 3 4 5 6
10408 (and (not (match-end 3)) (not (match-end 6)))
10409 (and (match-end 3) (match-end 6) (not (match-end 5))))
10410 (error "invalid row descriptor `%s'" desc))
10411 (let* ((hdir (and (match-end 2) (match-string 2 desc)))
10412 (hn (if (match-end 3) (- (match-end 3) (match-beginning 3)) nil))
10413 (odir (and (match-end 5) (match-string 5 desc)))
10414 (on (if (match-end 6) (string-to-number (match-string 6 desc))))
10415 (i (- cline bline))
10416 (rel (and (match-end 6)
10417 (or (and (match-end 1) (not (match-end 3)))
10418 (match-end 5)))))
10419 (if (and hn (not hdir))
10420 (progn
10421 (setq i 0 hdir "+")
10422 (if (eq (aref table 0) 'hline) (setq hn (1- hn)))))
10423 (if (and (not hn) on (not odir))
10424 (error "should never happen");;(aref org-table-dlines on)
10425 (if (and hn (> hn 0))
10426 (setq i (org-find-row-type table i 'hline (equal hdir "-") nil hn)))
10427 (if on
10428 (setq i (org-find-row-type table i 'dline (equal odir "-") rel on)))
10429 (+ bline i)))))
10431 (defun org-find-row-type (table i type backwards relative n)
10432 (let ((l (length table)))
10433 (while (> n 0)
10434 (while (and (setq i (+ i (if backwards -1 1)))
10435 (>= i 0) (< i l)
10436 (not (eq (aref table i) type))
10437 (if (and relative (eq (aref table i) 'hline))
10438 (progn (setq i (- i (if backwards -1 1)) n 1) nil)
10439 t)))
10440 (setq n (1- n)))
10441 (if (or (< i 0) (>= i l))
10442 (error "Row descriptior leads outside table")
10443 i)))
10445 (defun org-rewrite-old-row-references (s)
10446 (if (string-match "&[-+0-9I]" s)
10447 (error "Formula contains old &row reference, please rewrite using @-syntax")
10450 (defun org-table-make-reference (elements keep-empty numbers lispp)
10451 "Convert list ELEMENTS to something appropriate to insert into formula.
10452 KEEP-EMPTY indicated to keep empty fields, default is to skip them.
10453 NUMBERS indicates that everything should be converted to numbers.
10454 LISPP means to return something appropriate for a Lisp list."
10455 (if (stringp elements) ; just a single val
10456 (if lispp
10457 (if (eq lispp 'literal)
10458 elements
10459 (prin1-to-string (if numbers (string-to-number elements) elements)))
10460 (if (equal elements "") (setq elements "0"))
10461 (if numbers (number-to-string (string-to-number elements)) elements))
10462 (unless keep-empty
10463 (setq elements
10464 (delq nil
10465 (mapcar (lambda (x) (if (string-match "\\S-" x) x nil))
10466 elements))))
10467 (setq elements (or elements '("0")))
10468 (if lispp
10469 (mapconcat
10470 (lambda (x)
10471 (if (eq lispp 'literal)
10473 (prin1-to-string (if numbers (string-to-number x) x))))
10474 elements " ")
10475 (concat "[" (mapconcat
10476 (lambda (x)
10477 (if numbers (number-to-string (string-to-number x)) x))
10478 elements
10479 ",") "]"))))
10481 (defun org-table-recalculate (&optional all noalign)
10482 "Recalculate the current table line by applying all stored formulas.
10483 With prefix arg ALL, do this for all lines in the table."
10484 (interactive "P")
10485 (or (memq this-command org-recalc-commands)
10486 (setq org-recalc-commands (cons this-command org-recalc-commands)))
10487 (unless (org-at-table-p) (error "Not at a table"))
10488 (if (equal all '(16))
10489 (org-table-iterate)
10490 (org-table-get-specials)
10491 (let* ((eqlist (sort (org-table-get-stored-formulas)
10492 (lambda (a b) (string< (car a) (car b)))))
10493 (inhibit-redisplay (not debug-on-error))
10494 (line-re org-table-dataline-regexp)
10495 (thisline (org-current-line))
10496 (thiscol (org-table-current-column))
10497 beg end entry eqlnum eqlname eqlname1 eql (cnt 0) eq a name)
10498 ;; Insert constants in all formulas
10499 (setq eqlist
10500 (mapcar (lambda (x)
10501 (setcdr x (org-table-formula-substitute-names (cdr x)))
10503 eqlist))
10504 ;; Split the equation list
10505 (while (setq eq (pop eqlist))
10506 (if (<= (string-to-char (car eq)) ?9)
10507 (push eq eqlnum)
10508 (push eq eqlname)))
10509 (setq eqlnum (nreverse eqlnum) eqlname (nreverse eqlname))
10510 (if all
10511 (progn
10512 (setq end (move-marker (make-marker) (1+ (org-table-end))))
10513 (goto-char (setq beg (org-table-begin)))
10514 (if (re-search-forward org-table-calculate-mark-regexp end t)
10515 ;; This is a table with marked lines, compute selected lines
10516 (setq line-re org-table-recalculate-regexp)
10517 ;; Move forward to the first non-header line
10518 (if (and (re-search-forward org-table-dataline-regexp end t)
10519 (re-search-forward org-table-hline-regexp end t)
10520 (re-search-forward org-table-dataline-regexp end t))
10521 (setq beg (match-beginning 0))
10522 nil))) ;; just leave beg where it is
10523 (setq beg (point-at-bol)
10524 end (move-marker (make-marker) (1+ (point-at-eol)))))
10525 (goto-char beg)
10526 (and all (message "Re-applying formulas to full table..."))
10528 ;; First find the named fields, and mark them untouchanble
10529 (remove-text-properties beg end '(org-untouchable t))
10530 (while (setq eq (pop eqlname))
10531 (setq name (car eq)
10532 a (assoc name org-table-named-field-locations))
10533 (and (not a)
10534 (string-match "@\\([0-9]+\\)\\$\\([0-9]+\\)" name)
10535 (setq a (list name
10536 (aref org-table-dlines
10537 (string-to-number (match-string 1 name)))
10538 (string-to-number (match-string 2 name)))))
10539 (when (and a (or all (equal (nth 1 a) thisline)))
10540 (message "Re-applying formula to field: %s" name)
10541 (goto-line (nth 1 a))
10542 (org-table-goto-column (nth 2 a))
10543 (push (append a (list (cdr eq))) eqlname1)
10544 (org-table-put-field-property :org-untouchable t)))
10546 ;; Now evauluate the column formulas, but skip fields covered by
10547 ;; field formulas
10548 (goto-char beg)
10549 (while (re-search-forward line-re end t)
10550 (unless (string-match "^ *[_^!$/] *$" (org-table-get-field 1))
10551 ;; Unprotected line, recalculate
10552 (and all (message "Re-applying formulas to full table...(line %d)"
10553 (setq cnt (1+ cnt))))
10554 (setq org-last-recalc-line (org-current-line))
10555 (setq eql eqlnum)
10556 (while (setq entry (pop eql))
10557 (goto-line org-last-recalc-line)
10558 (org-table-goto-column (string-to-number (car entry)) nil 'force)
10559 (unless (get-text-property (point) :org-untouchable)
10560 (org-table-eval-formula nil (cdr entry)
10561 'noalign 'nocst 'nostore 'noanalysis)))))
10563 ;; Now evaluate the field formulas
10564 (while (setq eq (pop eqlname1))
10565 (message "Re-applying formula to field: %s" (car eq))
10566 (goto-line (nth 1 eq))
10567 (org-table-goto-column (nth 2 eq))
10568 (org-table-eval-formula nil (nth 3 eq) 'noalign 'nocst
10569 'nostore 'noanalysis))
10571 (goto-line thisline)
10572 (org-table-goto-column thiscol)
10573 (remove-text-properties (point-min) (point-max) '(org-untouchable t))
10574 (or noalign (and org-table-may-need-update (org-table-align))
10575 (and all (message "Re-applying formulas to %d lines...done" cnt)))
10577 ;; back to initial position
10578 (message "Re-applying formulas...done")
10579 (goto-line thisline)
10580 (org-table-goto-column thiscol)
10581 (or noalign (and org-table-may-need-update (org-table-align))
10582 (and all (message "Re-applying formulas...done"))))))
10584 (defun org-table-iterate (&optional arg)
10585 "Recalculate the table until it does not change anymore."
10586 (interactive "P")
10587 (let ((imax (if arg (prefix-numeric-value arg) 10))
10588 (i 0)
10589 (lasttbl (buffer-substring (org-table-begin) (org-table-end)))
10590 thistbl)
10591 (catch 'exit
10592 (while (< i imax)
10593 (setq i (1+ i))
10594 (org-table-recalculate 'all)
10595 (setq thistbl (buffer-substring (org-table-begin) (org-table-end)))
10596 (if (not (string= lasttbl thistbl))
10597 (setq lasttbl thistbl)
10598 (if (> i 1)
10599 (message "Convergence after %d iterations" i)
10600 (message "Table was already stable"))
10601 (throw 'exit t)))
10602 (error "No convergence after %d iterations" i))))
10604 (defun org-table-formula-substitute-names (f)
10605 "Replace $const with values in string F."
10606 (let ((start 0) a (f1 f) (pp (/= (string-to-char f) ?')))
10607 ;; First, check for column names
10608 (while (setq start (string-match org-table-column-name-regexp f start))
10609 (setq start (1+ start))
10610 (setq a (assoc (match-string 1 f) org-table-column-names))
10611 (setq f (replace-match (concat "$" (cdr a)) t t f)))
10612 ;; Parameters and constants
10613 (setq start 0)
10614 (while (setq start (string-match "\\$\\([a-zA-Z][_a-zA-Z0-9]*\\)" f start))
10615 (setq start (1+ start))
10616 (if (setq a (save-match-data
10617 (org-table-get-constant (match-string 1 f))))
10618 (setq f (replace-match
10619 (concat (if pp "(") a (if pp ")")) t t f))))
10620 (if org-table-formula-debug
10621 (put-text-property 0 (length f) :orig-formula f1 f))
10624 (defun org-table-get-constant (const)
10625 "Find the value for a parameter or constant in a formula.
10626 Parameters get priority."
10627 (or (cdr (assoc const org-table-local-parameters))
10628 (cdr (assoc const org-table-formula-constants-local))
10629 (cdr (assoc const org-table-formula-constants))
10630 (and (fboundp 'constants-get) (constants-get const))
10631 (and (string= (substring const 0 (min 5 (length const))) "PROP_")
10632 (org-entry-get nil (substring const 5) 'inherit))
10633 "#UNDEFINED_NAME"))
10635 (defvar org-table-fedit-map
10636 (let ((map (make-sparse-keymap)))
10637 (org-defkey map "\C-x\C-s" 'org-table-fedit-finish)
10638 (org-defkey map "\C-c\C-s" 'org-table-fedit-finish)
10639 (org-defkey map "\C-c\C-c" 'org-table-fedit-finish)
10640 (org-defkey map "\C-c\C-q" 'org-table-fedit-abort)
10641 (org-defkey map "\C-c?" 'org-table-show-reference)
10642 (org-defkey map [(meta shift up)] 'org-table-fedit-line-up)
10643 (org-defkey map [(meta shift down)] 'org-table-fedit-line-down)
10644 (org-defkey map [(shift up)] 'org-table-fedit-ref-up)
10645 (org-defkey map [(shift down)] 'org-table-fedit-ref-down)
10646 (org-defkey map [(shift left)] 'org-table-fedit-ref-left)
10647 (org-defkey map [(shift right)] 'org-table-fedit-ref-right)
10648 (org-defkey map [(meta up)] 'org-table-fedit-scroll-down)
10649 (org-defkey map [(meta down)] 'org-table-fedit-scroll)
10650 (org-defkey map [(meta tab)] 'lisp-complete-symbol)
10651 (org-defkey map "\M-\C-i" 'lisp-complete-symbol)
10652 (org-defkey map [(tab)] 'org-table-fedit-lisp-indent)
10653 (org-defkey map "\C-i" 'org-table-fedit-lisp-indent)
10654 (org-defkey map "\C-c\C-r" 'org-table-fedit-toggle-ref-type)
10655 (org-defkey map "\C-c}" 'org-table-fedit-toggle-coordinates)
10656 map))
10658 (easy-menu-define org-table-fedit-menu org-table-fedit-map "Org Edit Formulas Menu"
10659 '("Edit-Formulas"
10660 ["Finish and Install" org-table-fedit-finish t]
10661 ["Finish, Install, and Apply" (org-table-fedit-finish t) :keys "C-u C-c C-c"]
10662 ["Abort" org-table-fedit-abort t]
10663 "--"
10664 ["Pretty-Print Lisp Formula" org-table-fedit-lisp-indent t]
10665 ["Complete Lisp Symbol" lisp-complete-symbol t]
10666 "--"
10667 "Shift Reference at Point"
10668 ["Up" org-table-fedit-ref-up t]
10669 ["Down" org-table-fedit-ref-down t]
10670 ["Left" org-table-fedit-ref-left t]
10671 ["Right" org-table-fedit-ref-right t]
10673 "Change Test Row for Column Formulas"
10674 ["Up" org-table-fedit-line-up t]
10675 ["Down" org-table-fedit-line-down t]
10676 "--"
10677 ["Scroll Table Window" org-table-fedit-scroll t]
10678 ["Scroll Table Window down" org-table-fedit-scroll-down t]
10679 ["Show Table Grid" org-table-fedit-toggle-coordinates
10680 :style toggle :selected (with-current-buffer (marker-buffer org-pos)
10681 org-table-overlay-coordinates)]
10682 "--"
10683 ["Standard Refs (B3 instead of @3$2)" org-table-fedit-toggle-ref-type
10684 :style toggle :selected org-table-buffer-is-an]))
10686 (defvar org-pos)
10688 (defun org-table-edit-formulas ()
10689 "Edit the formulas of the current table in a separate buffer."
10690 (interactive)
10691 (when (save-excursion (beginning-of-line 1) (looking-at "#\\+TBLFM"))
10692 (beginning-of-line 0))
10693 (unless (org-at-table-p) (error "Not at a table"))
10694 (org-table-get-specials)
10695 (let ((key (org-table-current-field-formula 'key 'noerror))
10696 (eql (sort (org-table-get-stored-formulas 'noerror)
10697 'org-table-formula-less-p))
10698 (pos (move-marker (make-marker) (point)))
10699 (startline 1)
10700 (wc (current-window-configuration))
10701 (titles '((column . "# Column Formulas\n")
10702 (field . "# Field Formulas\n")
10703 (named . "# Named Field Formulas\n")))
10704 entry s type title)
10705 (org-switch-to-buffer-other-window "*Edit Formulas*")
10706 (erase-buffer)
10707 ;; Keep global-font-lock-mode from turning on font-lock-mode
10708 (let ((font-lock-global-modes '(not fundamental-mode)))
10709 (fundamental-mode))
10710 (org-set-local 'font-lock-global-modes (list 'not major-mode))
10711 (org-set-local 'org-pos pos)
10712 (org-set-local 'org-window-configuration wc)
10713 (use-local-map org-table-fedit-map)
10714 (org-add-hook 'post-command-hook 'org-table-fedit-post-command t t)
10715 (easy-menu-add org-table-fedit-menu)
10716 (setq startline (org-current-line))
10717 (while (setq entry (pop eql))
10718 (setq type (cond
10719 ((equal (string-to-char (car entry)) ?@) 'field)
10720 ((string-match "^[0-9]" (car entry)) 'column)
10721 (t 'named)))
10722 (when (setq title (assq type titles))
10723 (or (bobp) (insert "\n"))
10724 (insert (org-add-props (cdr title) nil 'face font-lock-comment-face))
10725 (setq titles (delq title titles)))
10726 (if (equal key (car entry)) (setq startline (org-current-line)))
10727 (setq s (concat (if (equal (string-to-char (car entry)) ?@) "" "$")
10728 (car entry) " = " (cdr entry) "\n"))
10729 (remove-text-properties 0 (length s) '(face nil) s)
10730 (insert s))
10731 (if (eq org-table-use-standard-references t)
10732 (org-table-fedit-toggle-ref-type))
10733 (goto-line startline)
10734 (message "Edit formulas and finish with `C-c C-c'. See menu for more commands.")))
10736 (defun org-table-fedit-post-command ()
10737 (when (not (memq this-command '(lisp-complete-symbol)))
10738 (let ((win (selected-window)))
10739 (save-excursion
10740 (condition-case nil
10741 (org-table-show-reference)
10742 (error nil))
10743 (select-window win)))))
10745 (defun org-table-formula-to-user (s)
10746 "Convert a formula from internal to user representation."
10747 (if (eq org-table-use-standard-references t)
10748 (org-table-convert-refs-to-an s)
10751 (defun org-table-formula-from-user (s)
10752 "Convert a formula from user to internal representation."
10753 (if org-table-use-standard-references
10754 (org-table-convert-refs-to-rc s)
10757 (defun org-table-convert-refs-to-rc (s)
10758 "Convert spreadsheet references from AB7 to @7$28.
10759 Works for single references, but also for entire formulas and even the
10760 full TBLFM line."
10761 (let ((start 0))
10762 (while (string-match "\\<\\([a-zA-Z]+\\)\\([0-9]+\\>\\|&\\)\\|\\(;[^\r\n:]+\\)" s start)
10763 (cond
10764 ((match-end 3)
10765 ;; format match, just advance
10766 (setq start (match-end 0)))
10767 ((and (> (match-beginning 0) 0)
10768 (equal ?. (aref s (max (1- (match-beginning 0)) 0)))
10769 (not (equal ?. (aref s (max (- (match-beginning 0) 2) 0)))))
10770 ;; 3.e5 or something like this.
10771 (setq start (match-end 0)))
10773 (setq start (match-beginning 0)
10774 s (replace-match
10775 (if (equal (match-string 2 s) "&")
10776 (format "$%d" (org-letters-to-number (match-string 1 s)))
10777 (format "@%d$%d"
10778 (string-to-number (match-string 2 s))
10779 (org-letters-to-number (match-string 1 s))))
10780 t t s)))))
10783 (defun org-table-convert-refs-to-an (s)
10784 "Convert spreadsheet references from to @7$28 to AB7.
10785 Works for single references, but also for entire formulas and even the
10786 full TBLFM line."
10787 (while (string-match "@\\([0-9]+\\)\\$\\([0-9]+\\)" s)
10788 (setq s (replace-match
10789 (format "%s%d"
10790 (org-number-to-letters
10791 (string-to-number (match-string 2 s)))
10792 (string-to-number (match-string 1 s)))
10793 t t s)))
10794 (while (string-match "\\(^\\|[^0-9a-zA-Z]\\)\\$\\([0-9]+\\)" s)
10795 (setq s (replace-match (concat "\\1"
10796 (org-number-to-letters
10797 (string-to-number (match-string 2 s))) "&")
10798 t nil s)))
10801 (defun org-letters-to-number (s)
10802 "Convert a base 26 number represented by letters into an integer.
10803 For example: AB -> 28."
10804 (let ((n 0))
10805 (setq s (upcase s))
10806 (while (> (length s) 0)
10807 (setq n (+ (* n 26) (string-to-char s) (- ?A) 1)
10808 s (substring s 1)))
10811 (defun org-number-to-letters (n)
10812 "Convert an integer into a base 26 number represented by letters.
10813 For example: 28 -> AB."
10814 (let ((s ""))
10815 (while (> n 0)
10816 (setq s (concat (char-to-string (+ (mod (1- n) 26) ?A)) s)
10817 n (/ (1- n) 26)))
10820 (defun org-table-fedit-convert-buffer (function)
10821 "Convert all references in this buffer, using FUNTION."
10822 (let ((line (org-current-line)))
10823 (goto-char (point-min))
10824 (while (not (eobp))
10825 (insert (funcall function (buffer-substring (point) (point-at-eol))))
10826 (delete-region (point) (point-at-eol))
10827 (or (eobp) (forward-char 1)))
10828 (goto-line line)))
10830 (defun org-table-fedit-toggle-ref-type ()
10831 "Convert all references in the buffer from B3 to @3$2 and back."
10832 (interactive)
10833 (org-set-local 'org-table-buffer-is-an (not org-table-buffer-is-an))
10834 (org-table-fedit-convert-buffer
10835 (if org-table-buffer-is-an
10836 'org-table-convert-refs-to-an 'org-table-convert-refs-to-rc))
10837 (message "Reference type switched to %s"
10838 (if org-table-buffer-is-an "A1 etc" "@row$column")))
10840 (defun org-table-fedit-ref-up ()
10841 "Shift the reference at point one row/hline up."
10842 (interactive)
10843 (org-table-fedit-shift-reference 'up))
10844 (defun org-table-fedit-ref-down ()
10845 "Shift the reference at point one row/hline down."
10846 (interactive)
10847 (org-table-fedit-shift-reference 'down))
10848 (defun org-table-fedit-ref-left ()
10849 "Shift the reference at point one field to the left."
10850 (interactive)
10851 (org-table-fedit-shift-reference 'left))
10852 (defun org-table-fedit-ref-right ()
10853 "Shift the reference at point one field to the right."
10854 (interactive)
10855 (org-table-fedit-shift-reference 'right))
10857 (defun org-table-fedit-shift-reference (dir)
10858 (cond
10859 ((org-at-regexp-p "\\(\\<[a-zA-Z]\\)&")
10860 (if (memq dir '(left right))
10861 (org-rematch-and-replace 1 (eq dir 'left))
10862 (error "Cannot shift reference in this direction")))
10863 ((org-at-regexp-p "\\(\\<[a-zA-Z]\\{1,2\\}\\)\\([0-9]+\\)")
10864 ;; A B3-like reference
10865 (if (memq dir '(up down))
10866 (org-rematch-and-replace 2 (eq dir 'up))
10867 (org-rematch-and-replace 1 (eq dir 'left))))
10868 ((org-at-regexp-p
10869 "\\(@\\|\\.\\.\\)\\([-+]?\\(I+\\>\\|[0-9]+\\)\\)\\(\\$\\([-+]?[0-9]+\\)\\)?")
10870 ;; An internal reference
10871 (if (memq dir '(up down))
10872 (org-rematch-and-replace 2 (eq dir 'up) (match-end 3))
10873 (org-rematch-and-replace 5 (eq dir 'left))))))
10875 (defun org-rematch-and-replace (n &optional decr hline)
10876 "Re-match the group N, and replace it with the shifted refrence."
10877 (or (match-end n) (error "Cannot shift reference in this direction"))
10878 (goto-char (match-beginning n))
10879 (and (looking-at (regexp-quote (match-string n)))
10880 (replace-match (org-shift-refpart (match-string 0) decr hline)
10881 t t)))
10883 (defun org-shift-refpart (ref &optional decr hline)
10884 "Shift a refrence part REF.
10885 If DECR is set, decrease the references row/column, else increase.
10886 If HLINE is set, this may be a hline reference, it certainly is not
10887 a translation reference."
10888 (save-match-data
10889 (let* ((sign (string-match "^[-+]" ref)) n)
10891 (if sign (setq sign (substring ref 0 1) ref (substring ref 1)))
10892 (cond
10893 ((and hline (string-match "^I+" ref))
10894 (setq n (string-to-number (concat sign (number-to-string (length ref)))))
10895 (setq n (+ n (if decr -1 1)))
10896 (if (= n 0) (setq n (+ n (if decr -1 1))))
10897 (if sign
10898 (setq sign (if (< n 0) "-" "+") n (abs n))
10899 (setq n (max 1 n)))
10900 (concat sign (make-string n ?I)))
10902 ((string-match "^[0-9]+" ref)
10903 (setq n (string-to-number (concat sign ref)))
10904 (setq n (+ n (if decr -1 1)))
10905 (if sign
10906 (concat (if (< n 0) "-" "+") (number-to-string (abs n)))
10907 (number-to-string (max 1 n))))
10909 ((string-match "^[a-zA-Z]+" ref)
10910 (org-number-to-letters
10911 (max 1 (+ (org-letters-to-number ref) (if decr -1 1)))))
10913 (t (error "Cannot shift reference"))))))
10915 (defun org-table-fedit-toggle-coordinates ()
10916 "Toggle the display of coordinates in the refrenced table."
10917 (interactive)
10918 (let ((pos (marker-position org-pos)))
10919 (with-current-buffer (marker-buffer org-pos)
10920 (save-excursion
10921 (goto-char pos)
10922 (org-table-toggle-coordinate-overlays)))))
10924 (defun org-table-fedit-finish (&optional arg)
10925 "Parse the buffer for formula definitions and install them.
10926 With prefix ARG, apply the new formulas to the table."
10927 (interactive "P")
10928 (org-table-remove-rectangle-highlight)
10929 (if org-table-use-standard-references
10930 (progn
10931 (org-table-fedit-convert-buffer 'org-table-convert-refs-to-rc)
10932 (setq org-table-buffer-is-an nil)))
10933 (let ((pos org-pos) eql var form)
10934 (goto-char (point-min))
10935 (while (re-search-forward
10936 "^\\(@[0-9]+\\$[0-9]+\\|\\$\\([a-zA-Z0-9]+\\)\\) *= *\\(.*\\(\n[ \t]+.*$\\)*\\)"
10937 nil t)
10938 (setq var (if (match-end 2) (match-string 2) (match-string 1))
10939 form (match-string 3))
10940 (setq form (org-trim form))
10941 (when (not (equal form ""))
10942 (while (string-match "[ \t]*\n[ \t]*" form)
10943 (setq form (replace-match " " t t form)))
10944 (when (assoc var eql)
10945 (error "Double formulas for %s" var))
10946 (push (cons var form) eql)))
10947 (setq org-pos nil)
10948 (set-window-configuration org-window-configuration)
10949 (select-window (get-buffer-window (marker-buffer pos)))
10950 (goto-char pos)
10951 (unless (org-at-table-p)
10952 (error "Lost table position - cannot install formulae"))
10953 (org-table-store-formulas eql)
10954 (move-marker pos nil)
10955 (kill-buffer "*Edit Formulas*")
10956 (if arg
10957 (org-table-recalculate 'all)
10958 (message "New formulas installed - press C-u C-c C-c to apply."))))
10960 (defun org-table-fedit-abort ()
10961 "Abort editing formulas, without installing the changes."
10962 (interactive)
10963 (org-table-remove-rectangle-highlight)
10964 (let ((pos org-pos))
10965 (set-window-configuration org-window-configuration)
10966 (select-window (get-buffer-window (marker-buffer pos)))
10967 (goto-char pos)
10968 (move-marker pos nil)
10969 (message "Formula editing aborted without installing changes")))
10971 (defun org-table-fedit-lisp-indent ()
10972 "Pretty-print and re-indent Lisp expressions in the Formula Editor."
10973 (interactive)
10974 (let ((pos (point)) beg end ind)
10975 (beginning-of-line 1)
10976 (cond
10977 ((looking-at "[ \t]")
10978 (goto-char pos)
10979 (call-interactively 'lisp-indent-line))
10980 ((looking-at "[$&@0-9a-zA-Z]+ *= *[^ \t\n']") (goto-char pos))
10981 ((not (fboundp 'pp-buffer))
10982 (error "Cannot pretty-print. Command `pp-buffer' is not available."))
10983 ((looking-at "[$&@0-9a-zA-Z]+ *= *'(")
10984 (goto-char (- (match-end 0) 2))
10985 (setq beg (point))
10986 (setq ind (make-string (current-column) ?\ ))
10987 (condition-case nil (forward-sexp 1)
10988 (error
10989 (error "Cannot pretty-print Lisp expression: Unbalanced parenthesis")))
10990 (setq end (point))
10991 (save-restriction
10992 (narrow-to-region beg end)
10993 (if (eq last-command this-command)
10994 (progn
10995 (goto-char (point-min))
10996 (setq this-command nil)
10997 (while (re-search-forward "[ \t]*\n[ \t]*" nil t)
10998 (replace-match " ")))
10999 (pp-buffer)
11000 (untabify (point-min) (point-max))
11001 (goto-char (1+ (point-min)))
11002 (while (re-search-forward "^." nil t)
11003 (beginning-of-line 1)
11004 (insert ind))
11005 (goto-char (point-max))
11006 (backward-delete-char 1)))
11007 (goto-char beg))
11008 (t nil))))
11010 (defvar org-show-positions nil)
11012 (defun org-table-show-reference (&optional local)
11013 "Show the location/value of the $ expression at point."
11014 (interactive)
11015 (org-table-remove-rectangle-highlight)
11016 (catch 'exit
11017 (let ((pos (if local (point) org-pos))
11018 (face2 'highlight)
11019 (org-inhibit-highlight-removal t)
11020 (win (selected-window))
11021 (org-show-positions nil)
11022 var name e what match dest)
11023 (if local (org-table-get-specials))
11024 (setq what (cond
11025 ((or (org-at-regexp-p org-table-range-regexp2)
11026 (org-at-regexp-p org-table-translate-regexp)
11027 (org-at-regexp-p org-table-range-regexp))
11028 (setq match
11029 (save-match-data
11030 (org-table-convert-refs-to-rc (match-string 0))))
11031 'range)
11032 ((org-at-regexp-p "\\$[a-zA-Z][a-zA-Z0-9]*") 'name)
11033 ((org-at-regexp-p "\\$[0-9]+") 'column)
11034 ((not local) nil)
11035 (t (error "No reference at point")))
11036 match (and what (or match (match-string 0))))
11037 (when (and match (not (equal (match-beginning 0) (point-at-bol))))
11038 (org-table-add-rectangle-overlay (match-beginning 0) (match-end 0)
11039 'secondary-selection))
11040 (org-add-hook 'before-change-functions
11041 'org-table-remove-rectangle-highlight)
11042 (if (eq what 'name) (setq var (substring match 1)))
11043 (when (eq what 'range)
11044 (or (equal (string-to-char match) ?@) (setq match (concat "@" match)))
11045 (setq match (org-table-formula-substitute-names match)))
11046 (unless local
11047 (save-excursion
11048 (end-of-line 1)
11049 (re-search-backward "^\\S-" nil t)
11050 (beginning-of-line 1)
11051 (when (looking-at "\\(\\$[0-9a-zA-Z]+\\|@[0-9]+\\$[0-9]+\\|[a-zA-Z]+\\([0-9]+\\|&\\)\\) *=")
11052 (setq dest
11053 (save-match-data
11054 (org-table-convert-refs-to-rc (match-string 1))))
11055 (org-table-add-rectangle-overlay
11056 (match-beginning 1) (match-end 1) face2))))
11057 (if (and (markerp pos) (marker-buffer pos))
11058 (if (get-buffer-window (marker-buffer pos))
11059 (select-window (get-buffer-window (marker-buffer pos)))
11060 (org-switch-to-buffer-other-window (get-buffer-window
11061 (marker-buffer pos)))))
11062 (goto-char pos)
11063 (org-table-force-dataline)
11064 (when dest
11065 (setq name (substring dest 1))
11066 (cond
11067 ((string-match "^\\$[a-zA-Z][a-zA-Z0-9]*" dest)
11068 (setq e (assoc name org-table-named-field-locations))
11069 (goto-line (nth 1 e))
11070 (org-table-goto-column (nth 2 e)))
11071 ((string-match "^@\\([0-9]+\\)\\$\\([0-9]+\\)" dest)
11072 (let ((l (string-to-number (match-string 1 dest)))
11073 (c (string-to-number (match-string 2 dest))))
11074 (goto-line (aref org-table-dlines l))
11075 (org-table-goto-column c)))
11076 (t (org-table-goto-column (string-to-number name))))
11077 (move-marker pos (point))
11078 (org-table-highlight-rectangle nil nil face2))
11079 (cond
11080 ((equal dest match))
11081 ((not match))
11082 ((eq what 'range)
11083 (condition-case nil
11084 (save-excursion
11085 (org-table-get-range match nil nil 'highlight))
11086 (error nil)))
11087 ((setq e (assoc var org-table-named-field-locations))
11088 (goto-line (nth 1 e))
11089 (org-table-goto-column (nth 2 e))
11090 (org-table-highlight-rectangle (point) (point))
11091 (message "Named field, column %d of line %d" (nth 2 e) (nth 1 e)))
11092 ((setq e (assoc var org-table-column-names))
11093 (org-table-goto-column (string-to-number (cdr e)))
11094 (org-table-highlight-rectangle (point) (point))
11095 (goto-char (org-table-begin))
11096 (if (re-search-forward (concat "^[ \t]*| *! *.*?| *\\(" var "\\) *|")
11097 (org-table-end) t)
11098 (progn
11099 (goto-char (match-beginning 1))
11100 (org-table-highlight-rectangle)
11101 (message "Named column (column %s)" (cdr e)))
11102 (error "Column name not found")))
11103 ((eq what 'column)
11104 ;; column number
11105 (org-table-goto-column (string-to-number (substring match 1)))
11106 (org-table-highlight-rectangle (point) (point))
11107 (message "Column %s" (substring match 1)))
11108 ((setq e (assoc var org-table-local-parameters))
11109 (goto-char (org-table-begin))
11110 (if (re-search-forward (concat "^[ \t]*| *\\$ *.*?| *\\(" var "=\\)") nil t)
11111 (progn
11112 (goto-char (match-beginning 1))
11113 (org-table-highlight-rectangle)
11114 (message "Local parameter."))
11115 (error "Parameter not found")))
11117 (cond
11118 ((not var) (error "No reference at point"))
11119 ((setq e (assoc var org-table-formula-constants-local))
11120 (message "Local Constant: $%s=%s in #+CONSTANTS line."
11121 var (cdr e)))
11122 ((setq e (assoc var org-table-formula-constants))
11123 (message "Constant: $%s=%s in `org-table-formula-constants'."
11124 var (cdr e)))
11125 ((setq e (and (fboundp 'constants-get) (constants-get var)))
11126 (message "Constant: $%s=%s, from `constants.el'%s."
11127 var e (format " (%s units)" constants-unit-system)))
11128 (t (error "Undefined name $%s" var)))))
11129 (goto-char pos)
11130 (when (and org-show-positions
11131 (not (memq this-command '(org-table-fedit-scroll
11132 org-table-fedit-scroll-down))))
11133 (push pos org-show-positions)
11134 (push org-table-current-begin-pos org-show-positions)
11135 (let ((min (apply 'min org-show-positions))
11136 (max (apply 'max org-show-positions)))
11137 (goto-char min) (recenter 0)
11138 (goto-char max)
11139 (or (pos-visible-in-window-p max) (recenter -1))))
11140 (select-window win))))
11142 (defun org-table-force-dataline ()
11143 "Make sure the cursor is in a dataline in a table."
11144 (unless (save-excursion
11145 (beginning-of-line 1)
11146 (looking-at org-table-dataline-regexp))
11147 (let* ((re org-table-dataline-regexp)
11148 (p1 (save-excursion (re-search-forward re nil 'move)))
11149 (p2 (save-excursion (re-search-backward re nil 'move))))
11150 (cond ((and p1 p2)
11151 (goto-char (if (< (abs (- p1 (point))) (abs (- p2 (point))))
11152 p1 p2)))
11153 ((or p1 p2) (goto-char (or p1 p2)))
11154 (t (error "No table dataline around here"))))))
11156 (defun org-table-fedit-line-up ()
11157 "Move cursor one line up in the window showing the table."
11158 (interactive)
11159 (org-table-fedit-move 'previous-line))
11161 (defun org-table-fedit-line-down ()
11162 "Move cursor one line down in the window showing the table."
11163 (interactive)
11164 (org-table-fedit-move 'next-line))
11166 (defun org-table-fedit-move (command)
11167 "Move the cursor in the window shoinw the table.
11168 Use COMMAND to do the motion, repeat if necessary to end up in a data line."
11169 (let ((org-table-allow-automatic-line-recalculation nil)
11170 (pos org-pos) (win (selected-window)) p)
11171 (select-window (get-buffer-window (marker-buffer org-pos)))
11172 (setq p (point))
11173 (call-interactively command)
11174 (while (and (org-at-table-p)
11175 (org-at-table-hline-p))
11176 (call-interactively command))
11177 (or (org-at-table-p) (goto-char p))
11178 (move-marker pos (point))
11179 (select-window win)))
11181 (defun org-table-fedit-scroll (N)
11182 (interactive "p")
11183 (let ((other-window-scroll-buffer (marker-buffer org-pos)))
11184 (scroll-other-window N)))
11186 (defun org-table-fedit-scroll-down (N)
11187 (interactive "p")
11188 (org-table-fedit-scroll (- N)))
11190 (defvar org-table-rectangle-overlays nil)
11192 (defun org-table-add-rectangle-overlay (beg end &optional face)
11193 "Add a new overlay."
11194 (let ((ov (org-make-overlay beg end)))
11195 (org-overlay-put ov 'face (or face 'secondary-selection))
11196 (push ov org-table-rectangle-overlays)))
11198 (defun org-table-highlight-rectangle (&optional beg end face)
11199 "Highlight rectangular region in a table."
11200 (setq beg (or beg (point)) end (or end (point)))
11201 (let ((b (min beg end))
11202 (e (max beg end))
11203 l1 c1 l2 c2 tmp)
11204 (and (boundp 'org-show-positions)
11205 (setq org-show-positions (cons b (cons e org-show-positions))))
11206 (goto-char (min beg end))
11207 (setq l1 (org-current-line)
11208 c1 (org-table-current-column))
11209 (goto-char (max beg end))
11210 (setq l2 (org-current-line)
11211 c2 (org-table-current-column))
11212 (if (> c1 c2) (setq tmp c1 c1 c2 c2 tmp))
11213 (goto-line l1)
11214 (beginning-of-line 1)
11215 (loop for line from l1 to l2 do
11216 (when (looking-at org-table-dataline-regexp)
11217 (org-table-goto-column c1)
11218 (skip-chars-backward "^|\n") (setq beg (point))
11219 (org-table-goto-column c2)
11220 (skip-chars-forward "^|\n") (setq end (point))
11221 (org-table-add-rectangle-overlay beg end face))
11222 (beginning-of-line 2))
11223 (goto-char b))
11224 (add-hook 'before-change-functions 'org-table-remove-rectangle-highlight))
11226 (defun org-table-remove-rectangle-highlight (&rest ignore)
11227 "Remove the rectangle overlays."
11228 (unless org-inhibit-highlight-removal
11229 (remove-hook 'before-change-functions 'org-table-remove-rectangle-highlight)
11230 (mapc 'org-delete-overlay org-table-rectangle-overlays)
11231 (setq org-table-rectangle-overlays nil)))
11233 (defvar org-table-coordinate-overlays nil
11234 "Collects the cooordinate grid overlays, so that they can be removed.")
11235 (make-variable-buffer-local 'org-table-coordinate-overlays)
11237 (defun org-table-overlay-coordinates ()
11238 "Add overlays to the table at point, to show row/column coordinates."
11239 (interactive)
11240 (mapc 'org-delete-overlay org-table-coordinate-overlays)
11241 (setq org-table-coordinate-overlays nil)
11242 (save-excursion
11243 (let ((id 0) (ih 0) hline eol s1 s2 str ic ov beg)
11244 (goto-char (org-table-begin))
11245 (while (org-at-table-p)
11246 (setq eol (point-at-eol))
11247 (setq ov (org-make-overlay (point-at-bol) (1+ (point-at-bol))))
11248 (push ov org-table-coordinate-overlays)
11249 (setq hline (looking-at org-table-hline-regexp))
11250 (setq str (if hline (format "I*%-2d" (setq ih (1+ ih)))
11251 (format "%4d" (setq id (1+ id)))))
11252 (org-overlay-before-string ov str 'org-special-keyword 'evaporate)
11253 (when hline
11254 (setq ic 0)
11255 (while (re-search-forward "[+|]\\(-+\\)" eol t)
11256 (setq beg (1+ (match-beginning 0))
11257 ic (1+ ic)
11258 s1 (concat "$" (int-to-string ic))
11259 s2 (org-number-to-letters ic)
11260 str (if (eq org-table-use-standard-references t) s2 s1))
11261 (setq ov (org-make-overlay beg (+ beg (length str))))
11262 (push ov org-table-coordinate-overlays)
11263 (org-overlay-display ov str 'org-special-keyword 'evaporate)))
11264 (beginning-of-line 2)))))
11266 (defun org-table-toggle-coordinate-overlays ()
11267 "Toggle the display of Row/Column numbers in tables."
11268 (interactive)
11269 (setq org-table-overlay-coordinates (not org-table-overlay-coordinates))
11270 (message "Row/Column number display turned %s"
11271 (if org-table-overlay-coordinates "on" "off"))
11272 (if (and (org-at-table-p) org-table-overlay-coordinates)
11273 (org-table-align))
11274 (unless org-table-overlay-coordinates
11275 (mapc 'org-delete-overlay org-table-coordinate-overlays)
11276 (setq org-table-coordinate-overlays nil)))
11278 (defun org-table-toggle-formula-debugger ()
11279 "Toggle the formula debugger in tables."
11280 (interactive)
11281 (setq org-table-formula-debug (not org-table-formula-debug))
11282 (message "Formula debugging has been turned %s"
11283 (if org-table-formula-debug "on" "off")))
11285 ;;; The orgtbl minor mode
11287 ;; Define a minor mode which can be used in other modes in order to
11288 ;; integrate the org-mode table editor.
11290 ;; This is really a hack, because the org-mode table editor uses several
11291 ;; keys which normally belong to the major mode, for example the TAB and
11292 ;; RET keys. Here is how it works: The minor mode defines all the keys
11293 ;; necessary to operate the table editor, but wraps the commands into a
11294 ;; function which tests if the cursor is currently inside a table. If that
11295 ;; is the case, the table editor command is executed. However, when any of
11296 ;; those keys is used outside a table, the function uses `key-binding' to
11297 ;; look up if the key has an associated command in another currently active
11298 ;; keymap (minor modes, major mode, global), and executes that command.
11299 ;; There might be problems if any of the keys used by the table editor is
11300 ;; otherwise used as a prefix key.
11302 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
11303 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
11304 ;; addresses this by checking explicitly for both bindings.
11306 ;; The optimized version (see variable `orgtbl-optimized') takes over
11307 ;; all keys which are bound to `self-insert-command' in the *global map*.
11308 ;; Some modes bind other commands to simple characters, for example
11309 ;; AUCTeX binds the double quote to `Tex-insert-quote'. With orgtbl-mode
11310 ;; active, this binding is ignored inside tables and replaced with a
11311 ;; modified self-insert.
11313 (defvar orgtbl-mode nil
11314 "Variable controlling `orgtbl-mode', a minor mode enabling the `org-mode'
11315 table editor in arbitrary modes.")
11316 (make-variable-buffer-local 'orgtbl-mode)
11318 (defvar orgtbl-mode-map (make-keymap)
11319 "Keymap for `orgtbl-mode'.")
11321 ;;;###autoload
11322 (defun turn-on-orgtbl ()
11323 "Unconditionally turn on `orgtbl-mode'."
11324 (orgtbl-mode 1))
11326 (defvar org-old-auto-fill-inhibit-regexp nil
11327 "Local variable used by `orgtbl-mode'")
11329 (defconst orgtbl-line-start-regexp "[ \t]*\\(|\\|#\\+\\(TBLFM\\|ORGTBL\\):\\)"
11330 "Matches a line belonging to an orgtbl.")
11332 (defconst orgtbl-extra-font-lock-keywords
11333 (list (list (concat "^" orgtbl-line-start-regexp ".*")
11334 0 (quote 'org-table) 'prepend))
11335 "Extra font-lock-keywords to be added when orgtbl-mode is active.")
11337 ;;;###autoload
11338 (defun orgtbl-mode (&optional arg)
11339 "The `org-mode' table editor as a minor mode for use in other modes."
11340 (interactive)
11341 (if (org-mode-p)
11342 ;; Exit without error, in case some hook functions calls this
11343 ;; by accident in org-mode.
11344 (message "Orgtbl-mode is not useful in org-mode, command ignored")
11345 (setq orgtbl-mode
11346 (if arg (> (prefix-numeric-value arg) 0) (not orgtbl-mode)))
11347 (if orgtbl-mode
11348 (progn
11349 (and (orgtbl-setup) (defun orgtbl-setup () nil))
11350 ;; Make sure we are first in minor-mode-map-alist
11351 (let ((c (assq 'orgtbl-mode minor-mode-map-alist)))
11352 (and c (setq minor-mode-map-alist
11353 (cons c (delq c minor-mode-map-alist)))))
11354 (org-set-local (quote org-table-may-need-update) t)
11355 (org-add-hook 'before-change-functions 'org-before-change-function
11356 nil 'local)
11357 (org-set-local 'org-old-auto-fill-inhibit-regexp
11358 auto-fill-inhibit-regexp)
11359 (org-set-local 'auto-fill-inhibit-regexp
11360 (if auto-fill-inhibit-regexp
11361 (concat orgtbl-line-start-regexp "\\|"
11362 auto-fill-inhibit-regexp)
11363 orgtbl-line-start-regexp))
11364 (org-add-to-invisibility-spec '(org-cwidth))
11365 (when (fboundp 'font-lock-add-keywords)
11366 (font-lock-add-keywords nil orgtbl-extra-font-lock-keywords)
11367 (org-restart-font-lock))
11368 (easy-menu-add orgtbl-mode-menu)
11369 (run-hooks 'orgtbl-mode-hook))
11370 (setq auto-fill-inhibit-regexp org-old-auto-fill-inhibit-regexp)
11371 (org-cleanup-narrow-column-properties)
11372 (org-remove-from-invisibility-spec '(org-cwidth))
11373 (remove-hook 'before-change-functions 'org-before-change-function t)
11374 (when (fboundp 'font-lock-remove-keywords)
11375 (font-lock-remove-keywords nil orgtbl-extra-font-lock-keywords)
11376 (org-restart-font-lock))
11377 (easy-menu-remove orgtbl-mode-menu)
11378 (force-mode-line-update 'all))))
11380 (defun org-cleanup-narrow-column-properties ()
11381 "Remove all properties related to narrow-column invisibility."
11382 (let ((s 1))
11383 (while (setq s (text-property-any s (point-max)
11384 'display org-narrow-column-arrow))
11385 (remove-text-properties s (1+ s) '(display t)))
11386 (setq s 1)
11387 (while (setq s (text-property-any s (point-max) 'org-cwidth 1))
11388 (remove-text-properties s (1+ s) '(org-cwidth t)))
11389 (setq s 1)
11390 (while (setq s (text-property-any s (point-max) 'invisible 'org-cwidth))
11391 (remove-text-properties s (1+ s) '(invisible t)))))
11393 ;; Install it as a minor mode.
11394 (put 'orgtbl-mode :included t)
11395 (put 'orgtbl-mode :menu-tag "Org Table Mode")
11396 (add-minor-mode 'orgtbl-mode " OrgTbl" orgtbl-mode-map)
11398 (defun orgtbl-make-binding (fun n &rest keys)
11399 "Create a function for binding in the table minor mode.
11400 FUN is the command to call inside a table. N is used to create a unique
11401 command name. KEYS are keys that should be checked in for a command
11402 to execute outside of tables."
11403 (eval
11404 (list 'defun
11405 (intern (concat "orgtbl-hijacker-command-" (int-to-string n)))
11406 '(arg)
11407 (concat "In tables, run `" (symbol-name fun) "'.\n"
11408 "Outside of tables, run the binding of `"
11409 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
11410 "'.")
11411 '(interactive "p")
11412 (list 'if
11413 '(org-at-table-p)
11414 (list 'call-interactively (list 'quote fun))
11415 (list 'let '(orgtbl-mode)
11416 (list 'call-interactively
11417 (append '(or)
11418 (mapcar (lambda (k)
11419 (list 'key-binding k))
11420 keys)
11421 '('orgtbl-error))))))))
11423 (defun orgtbl-error ()
11424 "Error when there is no default binding for a table key."
11425 (interactive)
11426 (error "This key has no function outside tables"))
11428 (defun orgtbl-setup ()
11429 "Setup orgtbl keymaps."
11430 (let ((nfunc 0)
11431 (bindings
11432 (list
11433 '([(meta shift left)] org-table-delete-column)
11434 '([(meta left)] org-table-move-column-left)
11435 '([(meta right)] org-table-move-column-right)
11436 '([(meta shift right)] org-table-insert-column)
11437 '([(meta shift up)] org-table-kill-row)
11438 '([(meta shift down)] org-table-insert-row)
11439 '([(meta up)] org-table-move-row-up)
11440 '([(meta down)] org-table-move-row-down)
11441 '("\C-c\C-w" org-table-cut-region)
11442 '("\C-c\M-w" org-table-copy-region)
11443 '("\C-c\C-y" org-table-paste-rectangle)
11444 '("\C-c-" org-table-insert-hline)
11445 '("\C-c}" org-table-toggle-coordinate-overlays)
11446 '("\C-c{" org-table-toggle-formula-debugger)
11447 '("\C-m" org-table-next-row)
11448 '([(shift return)] org-table-copy-down)
11449 '("\C-c\C-q" org-table-wrap-region)
11450 '("\C-c?" org-table-field-info)
11451 '("\C-c " org-table-blank-field)
11452 '("\C-c+" org-table-sum)
11453 '("\C-c=" org-table-eval-formula)
11454 '("\C-c'" org-table-edit-formulas)
11455 '("\C-c`" org-table-edit-field)
11456 '("\C-c*" org-table-recalculate)
11457 '("\C-c|" org-table-create-or-convert-from-region)
11458 '("\C-c^" org-table-sort-lines)
11459 '([(control ?#)] org-table-rotate-recalc-marks)))
11460 elt key fun cmd)
11461 (while (setq elt (pop bindings))
11462 (setq nfunc (1+ nfunc))
11463 (setq key (org-key (car elt))
11464 fun (nth 1 elt)
11465 cmd (orgtbl-make-binding fun nfunc key))
11466 (org-defkey orgtbl-mode-map key cmd))
11468 ;; Special treatment needed for TAB and RET
11469 (org-defkey orgtbl-mode-map [(return)]
11470 (orgtbl-make-binding 'orgtbl-ret 100 [(return)] "\C-m"))
11471 (org-defkey orgtbl-mode-map "\C-m"
11472 (orgtbl-make-binding 'orgtbl-ret 101 "\C-m" [(return)]))
11474 (org-defkey orgtbl-mode-map [(tab)]
11475 (orgtbl-make-binding 'orgtbl-tab 102 [(tab)] "\C-i"))
11476 (org-defkey orgtbl-mode-map "\C-i"
11477 (orgtbl-make-binding 'orgtbl-tab 103 "\C-i" [(tab)]))
11479 (org-defkey orgtbl-mode-map [(shift tab)]
11480 (orgtbl-make-binding 'org-table-previous-field 104
11481 [(shift tab)] [(tab)] "\C-i"))
11483 (org-defkey orgtbl-mode-map "\M-\C-m"
11484 (orgtbl-make-binding 'org-table-wrap-region 105
11485 "\M-\C-m" [(meta return)]))
11486 (org-defkey orgtbl-mode-map [(meta return)]
11487 (orgtbl-make-binding 'org-table-wrap-region 106
11488 [(meta return)] "\M-\C-m"))
11490 (org-defkey orgtbl-mode-map "\C-c\C-c" 'orgtbl-ctrl-c-ctrl-c)
11491 (when orgtbl-optimized
11492 ;; If the user wants maximum table support, we need to hijack
11493 ;; some standard editing functions
11494 (org-remap orgtbl-mode-map
11495 'self-insert-command 'orgtbl-self-insert-command
11496 'delete-char 'org-delete-char
11497 'delete-backward-char 'org-delete-backward-char)
11498 (org-defkey orgtbl-mode-map "|" 'org-force-self-insert))
11499 (easy-menu-define orgtbl-mode-menu orgtbl-mode-map "OrgTbl menu"
11500 '("OrgTbl"
11501 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p) :keys "C-c C-c"]
11502 ["Next Field" org-cycle :active (org-at-table-p) :keys "TAB"]
11503 ["Previous Field" org-shifttab :active (org-at-table-p) :keys "S-TAB"]
11504 ["Next Row" org-return :active (org-at-table-p) :keys "RET"]
11505 "--"
11506 ["Blank Field" org-table-blank-field :active (org-at-table-p) :keys "C-c SPC"]
11507 ["Edit Field" org-table-edit-field :active (org-at-table-p) :keys "C-c ` "]
11508 ["Copy Field from Above"
11509 org-table-copy-down :active (org-at-table-p) :keys "S-RET"]
11510 "--"
11511 ("Column"
11512 ["Move Column Left" org-metaleft :active (org-at-table-p) :keys "M-<left>"]
11513 ["Move Column Right" org-metaright :active (org-at-table-p) :keys "M-<right>"]
11514 ["Delete Column" org-shiftmetaleft :active (org-at-table-p) :keys "M-S-<left>"]
11515 ["Insert Column" org-shiftmetaright :active (org-at-table-p) :keys "M-S-<right>"])
11516 ("Row"
11517 ["Move Row Up" org-metaup :active (org-at-table-p) :keys "M-<up>"]
11518 ["Move Row Down" org-metadown :active (org-at-table-p) :keys "M-<down>"]
11519 ["Delete Row" org-shiftmetaup :active (org-at-table-p) :keys "M-S-<up>"]
11520 ["Insert Row" org-shiftmetadown :active (org-at-table-p) :keys "M-S-<down>"]
11521 ["Sort lines in region" org-table-sort-lines :active (org-at-table-p) :keys "C-c ^"]
11522 "--"
11523 ["Insert Hline" org-table-insert-hline :active (org-at-table-p) :keys "C-c -"])
11524 ("Rectangle"
11525 ["Copy Rectangle" org-copy-special :active (org-at-table-p)]
11526 ["Cut Rectangle" org-cut-special :active (org-at-table-p)]
11527 ["Paste Rectangle" org-paste-special :active (org-at-table-p)]
11528 ["Fill Rectangle" org-table-wrap-region :active (org-at-table-p)])
11529 "--"
11530 ("Radio tables"
11531 ["Insert table template" orgtbl-insert-radio-table
11532 (assq major-mode orgtbl-radio-table-templates)]
11533 ["Comment/uncomment table" orgtbl-toggle-comment t])
11534 "--"
11535 ["Set Column Formula" org-table-eval-formula :active (org-at-table-p) :keys "C-c ="]
11536 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
11537 ["Edit Formulas" org-table-edit-formulas :active (org-at-table-p) :keys "C-c '"]
11538 ["Recalculate line" org-table-recalculate :active (org-at-table-p) :keys "C-c *"]
11539 ["Recalculate all" (org-table-recalculate '(4)) :active (org-at-table-p) :keys "C-u C-c *"]
11540 ["Iterate all" (org-table-recalculate '(16)) :active (org-at-table-p) :keys "C-u C-u C-c *"]
11541 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks :active (org-at-table-p) :keys "C-c #"]
11542 ["Sum Column/Rectangle" org-table-sum
11543 :active (or (org-at-table-p) (org-region-active-p)) :keys "C-c +"]
11544 ["Which Column?" org-table-current-column :active (org-at-table-p) :keys "C-c ?"]
11545 ["Debug Formulas"
11546 org-table-toggle-formula-debugger :active (org-at-table-p)
11547 :keys "C-c {"
11548 :style toggle :selected org-table-formula-debug]
11549 ["Show Col/Row Numbers"
11550 org-table-toggle-coordinate-overlays :active (org-at-table-p)
11551 :keys "C-c }"
11552 :style toggle :selected org-table-overlay-coordinates]
11556 (defun orgtbl-ctrl-c-ctrl-c (arg)
11557 "If the cursor is inside a table, realign the table.
11558 It it is a table to be sent away to a receiver, do it.
11559 With prefix arg, also recompute table."
11560 (interactive "P")
11561 (let ((pos (point)) action)
11562 (save-excursion
11563 (beginning-of-line 1)
11564 (setq action (cond ((looking-at "#\\+ORGTBL:.*\n[ \t]*|") (match-end 0))
11565 ((looking-at "[ \t]*|") pos)
11566 ((looking-at "#\\+TBLFM:") 'recalc))))
11567 (cond
11568 ((integerp action)
11569 (goto-char action)
11570 (org-table-maybe-eval-formula)
11571 (if arg
11572 (call-interactively 'org-table-recalculate)
11573 (org-table-maybe-recalculate-line))
11574 (call-interactively 'org-table-align)
11575 (orgtbl-send-table 'maybe))
11576 ((eq action 'recalc)
11577 (save-excursion
11578 (beginning-of-line 1)
11579 (skip-chars-backward " \r\n\t")
11580 (if (org-at-table-p)
11581 (org-call-with-arg 'org-table-recalculate t))))
11582 (t (let (orgtbl-mode)
11583 (call-interactively (key-binding "\C-c\C-c")))))))
11585 (defun orgtbl-tab (arg)
11586 "Justification and field motion for `orgtbl-mode'."
11587 (interactive "P")
11588 (if arg (org-table-edit-field t)
11589 (org-table-justify-field-maybe)
11590 (org-table-next-field)))
11592 (defun orgtbl-ret ()
11593 "Justification and field motion for `orgtbl-mode'."
11594 (interactive)
11595 (org-table-justify-field-maybe)
11596 (org-table-next-row))
11598 (defun orgtbl-self-insert-command (N)
11599 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
11600 If the cursor is in a table looking at whitespace, the whitespace is
11601 overwritten, and the table is not marked as requiring realignment."
11602 (interactive "p")
11603 (if (and (org-at-table-p)
11605 (and org-table-auto-blank-field
11606 (member last-command
11607 '(orgtbl-hijacker-command-100
11608 orgtbl-hijacker-command-101
11609 orgtbl-hijacker-command-102
11610 orgtbl-hijacker-command-103
11611 orgtbl-hijacker-command-104
11612 orgtbl-hijacker-command-105))
11613 (org-table-blank-field))
11615 (eq N 1)
11616 (looking-at "[^|\n]* +|"))
11617 (let (org-table-may-need-update)
11618 (goto-char (1- (match-end 0)))
11619 (delete-backward-char 1)
11620 (goto-char (match-beginning 0))
11621 (self-insert-command N))
11622 (setq org-table-may-need-update t)
11623 (let (orgtbl-mode)
11624 (call-interactively (key-binding (vector last-input-event))))))
11626 (defun org-force-self-insert (N)
11627 "Needed to enforce self-insert under remapping."
11628 (interactive "p")
11629 (self-insert-command N))
11631 (defvar orgtbl-exp-regexp "^\\([-+]?[0-9][0-9.]*\\)[eE]\\([-+]?[0-9]+\\)$"
11632 "Regula expression matching exponentials as produced by calc.")
11634 (defvar org-table-clean-did-remove-column nil)
11636 (defun orgtbl-export (table target)
11637 (let ((func (intern (concat "orgtbl-to-" (symbol-name target))))
11638 (lines (org-split-string table "[ \t]*\n[ \t]*"))
11639 org-table-last-alignment org-table-last-column-widths
11640 maxcol column)
11641 (if (not (fboundp func))
11642 (error "Cannot export orgtbl table to %s" target))
11643 (setq lines (org-table-clean-before-export lines))
11644 (setq table
11645 (mapcar
11646 (lambda (x)
11647 (if (string-match org-table-hline-regexp x)
11648 'hline
11649 (org-split-string (org-trim x) "\\s-*|\\s-*")))
11650 lines))
11651 (setq maxcol (apply 'max (mapcar (lambda (x) (if (listp x) (length x) 0))
11652 table)))
11653 (loop for i from (1- maxcol) downto 0 do
11654 (setq column (mapcar (lambda (x) (if (listp x) (nth i x) nil)) table))
11655 (setq column (delq nil column))
11656 (push (apply 'max (mapcar 'string-width column)) org-table-last-column-widths)
11657 (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))
11658 (funcall func table nil)))
11660 (defun orgtbl-send-table (&optional maybe)
11661 "Send a tranformed version of this table to the receiver position.
11662 With argument MAYBE, fail quietly if no transformation is defined for
11663 this table."
11664 (interactive)
11665 (catch 'exit
11666 (unless (org-at-table-p) (error "Not at a table"))
11667 ;; when non-interactive, we assume align has just happened.
11668 (when (interactive-p) (org-table-align))
11669 (save-excursion
11670 (goto-char (org-table-begin))
11671 (beginning-of-line 0)
11672 (unless (looking-at "#\\+ORGTBL: *SEND +\\([a-zA-Z0-9_]+\\) +\\([^ \t\r\n]+\\)\\( +.*\\)?")
11673 (if maybe
11674 (throw 'exit nil)
11675 (error "Don't know how to transform this table."))))
11676 (let* ((name (match-string 1))
11678 (transform (intern (match-string 2)))
11679 (params (if (match-end 3) (read (concat "(" (match-string 3) ")"))))
11680 (skip (plist-get params :skip))
11681 (skipcols (plist-get params :skipcols))
11682 (txt (buffer-substring-no-properties
11683 (org-table-begin) (org-table-end)))
11684 (lines (nthcdr (or skip 0) (org-split-string txt "[ \t]*\n[ \t]*")))
11685 (lines (org-table-clean-before-export lines))
11686 (i0 (if org-table-clean-did-remove-column 2 1))
11687 (table (mapcar
11688 (lambda (x)
11689 (if (string-match org-table-hline-regexp x)
11690 'hline
11691 (org-remove-by-index
11692 (org-split-string (org-trim x) "\\s-*|\\s-*")
11693 skipcols i0)))
11694 lines))
11695 (fun (if (= i0 2) 'cdr 'identity))
11696 (org-table-last-alignment
11697 (org-remove-by-index (funcall fun org-table-last-alignment)
11698 skipcols i0))
11699 (org-table-last-column-widths
11700 (org-remove-by-index (funcall fun org-table-last-column-widths)
11701 skipcols i0)))
11703 (unless (fboundp transform)
11704 (error "No such transformation function %s" transform))
11705 (setq txt (funcall transform table params))
11706 ;; Find the insertion place
11707 (save-excursion
11708 (goto-char (point-min))
11709 (unless (re-search-forward
11710 (concat "BEGIN RECEIVE ORGTBL +" name "\\([ \t]\\|$\\)") nil t)
11711 (error "Don't know where to insert translated table"))
11712 (goto-char (match-beginning 0))
11713 (beginning-of-line 2)
11714 (setq beg (point))
11715 (unless (re-search-forward (concat "END RECEIVE ORGTBL +" name) nil t)
11716 (error "Cannot find end of insertion region"))
11717 (beginning-of-line 1)
11718 (delete-region beg (point))
11719 (goto-char beg)
11720 (insert txt "\n"))
11721 (message "Table converted and installed at receiver location"))))
11723 (defun org-remove-by-index (list indices &optional i0)
11724 "Remove the elements in LIST with indices in INDICES.
11725 First element has index 0, or I0 if given."
11726 (if (not indices)
11727 list
11728 (if (integerp indices) (setq indices (list indices)))
11729 (setq i0 (1- (or i0 0)))
11730 (delq :rm (mapcar (lambda (x)
11731 (setq i0 (1+ i0))
11732 (if (memq i0 indices) :rm x))
11733 list))))
11735 (defun orgtbl-toggle-comment ()
11736 "Comment or uncomment the orgtbl at point."
11737 (interactive)
11738 (let* ((re1 (concat "^" (regexp-quote comment-start) orgtbl-line-start-regexp))
11739 (re2 (concat "^" orgtbl-line-start-regexp))
11740 (commented (save-excursion (beginning-of-line 1)
11741 (cond ((looking-at re1) t)
11742 ((looking-at re2) nil)
11743 (t (error "Not at an org table")))))
11744 (re (if commented re1 re2))
11745 beg end)
11746 (save-excursion
11747 (beginning-of-line 1)
11748 (while (looking-at re) (beginning-of-line 0))
11749 (beginning-of-line 2)
11750 (setq beg (point))
11751 (while (looking-at re) (beginning-of-line 2))
11752 (setq end (point)))
11753 (comment-region beg end (if commented '(4) nil))))
11755 (defun orgtbl-insert-radio-table ()
11756 "Insert a radio table template appropriate for this major mode."
11757 (interactive)
11758 (let* ((e (assq major-mode orgtbl-radio-table-templates))
11759 (txt (nth 1 e))
11760 name pos)
11761 (unless e (error "No radio table setup defined for %s" major-mode))
11762 (setq name (read-string "Table name: "))
11763 (while (string-match "%n" txt)
11764 (setq txt (replace-match name t t txt)))
11765 (or (bolp) (insert "\n"))
11766 (setq pos (point))
11767 (insert txt)
11768 (goto-char pos)))
11770 (defun org-get-param (params header i sym &optional hsym)
11771 "Get parameter value for symbol SYM.
11772 If this is a header line, actually get the value for the symbol with an
11773 additional \"h\" inserted after the colon.
11774 If the value is a protperty list, get the element for the current column.
11775 Assumes variables VAL, PARAMS, HEAD and I to be scoped into the function."
11776 (let ((val (plist-get params sym)))
11777 (and hsym header (setq val (or (plist-get params hsym) val)))
11778 (if (consp val) (plist-get val i) val)))
11780 (defun orgtbl-to-generic (table params)
11781 "Convert the orgtbl-mode TABLE to some other format.
11782 This generic routine can be used for many standard cases.
11783 TABLE is a list, each entry either the symbol `hline' for a horizontal
11784 separator line, or a list of fields for that line.
11785 PARAMS is a property list of parameters that can influence the conversion.
11786 For the generic converter, some parameters are obligatory: You need to
11787 specify either :lfmt, or all of (:lstart :lend :sep). If you do not use
11788 :splice, you must have :tstart and :tend.
11790 Valid parameters are
11792 :tstart String to start the table. Ignored when :splice is t.
11793 :tend String to end the table. Ignored when :splice is t.
11795 :splice When set to t, return only table body lines, don't wrap
11796 them into :tstart and :tend. Default is nil.
11798 :hline String to be inserted on horizontal separation lines.
11799 May be nil to ignore hlines.
11801 :lstart String to start a new table line.
11802 :lend String to end a table line
11803 :sep Separator between two fields
11804 :lfmt Format for entire line, with enough %s to capture all fields.
11805 If this is present, :lstart, :lend, and :sep are ignored.
11806 :fmt A format to be used to wrap the field, should contain
11807 %s for the original field value. For example, to wrap
11808 everything in dollars, you could use :fmt \"$%s$\".
11809 This may also be a property list with column numbers and
11810 formats. For example :fmt (2 \"$%s$\" 4 \"%s%%\")
11812 :hlstart :hlend :hlsep :hlfmt :hfmt
11813 Same as above, specific for the header lines in the table.
11814 All lines before the first hline are treated as header.
11815 If any of these is not present, the data line value is used.
11817 :efmt Use this format to print numbers with exponentials.
11818 The format should have %s twice for inserting mantissa
11819 and exponent, for example \"%s\\\\times10^{%s}\". This
11820 may also be a property list with column numbers and
11821 formats. :fmt will still be applied after :efmt.
11823 In addition to this, the parameters :skip and :skipcols are always handled
11824 directly by `orgtbl-send-table'. See manual."
11825 (interactive)
11826 (let* ((p params)
11827 (splicep (plist-get p :splice))
11828 (hline (plist-get p :hline))
11829 rtn line i fm efm lfmt h)
11831 ;; Do we have a header?
11832 (if (and (not splicep) (listp (car table)) (memq 'hline table))
11833 (setq h t))
11835 ;; Put header
11836 (unless splicep
11837 (push (or (plist-get p :tstart) "ERROR: no :tstart") rtn))
11839 ;; Now loop over all lines
11840 (while (setq line (pop table))
11841 (if (eq line 'hline)
11842 ;; A horizontal separator line
11843 (progn (if hline (push hline rtn))
11844 (setq h nil)) ; no longer in header
11845 ;; A normal line. Convert the fields, push line onto the result list
11846 (setq i 0)
11847 (setq line
11848 (mapcar
11849 (lambda (f)
11850 (setq i (1+ i)
11851 fm (org-get-param p h i :fmt :hfmt)
11852 efm (org-get-param p h i :efmt))
11853 (if (and efm (string-match orgtbl-exp-regexp f))
11854 (setq f (format
11855 efm (match-string 1 f) (match-string 2 f))))
11856 (if fm (setq f (format fm f)))
11858 line))
11859 (if (setq lfmt (org-get-param p h i :lfmt :hlfmt))
11860 (push (apply 'format lfmt line) rtn)
11861 (push (concat
11862 (org-get-param p h i :lstart :hlstart)
11863 (mapconcat 'identity line (org-get-param p h i :sep :hsep))
11864 (org-get-param p h i :lend :hlend))
11865 rtn))))
11867 (unless splicep
11868 (push (or (plist-get p :tend) "ERROR: no :tend") rtn))
11870 (mapconcat 'identity (nreverse rtn) "\n")))
11872 (defun orgtbl-to-latex (table params)
11873 "Convert the orgtbl-mode TABLE to LaTeX.
11874 TABLE is a list, each entry either the symbol `hline' for a horizontal
11875 separator line, or a list of fields for that line.
11876 PARAMS is a property list of parameters that can influence the conversion.
11877 Supports all parameters from `orgtbl-to-generic'. Most important for
11878 LaTeX are:
11880 :splice When set to t, return only table body lines, don't wrap
11881 them into a tabular environment. Default is nil.
11883 :fmt A format to be used to wrap the field, should contain %s for the
11884 original field value. For example, to wrap everything in dollars,
11885 use :fmt \"$%s$\". This may also be a property list with column
11886 numbers and formats. For example :fmt (2 \"$%s$\" 4 \"%s%%\")
11888 :efmt Format for transforming numbers with exponentials. The format
11889 should have %s twice for inserting mantissa and exponent, for
11890 example \"%s\\\\times10^{%s}\". LaTeX default is \"%s\\\\,(%s)\".
11891 This may also be a property list with column numbers and formats.
11893 The general parameters :skip and :skipcols have already been applied when
11894 this function is called."
11895 (let* ((alignment (mapconcat (lambda (x) (if x "r" "l"))
11896 org-table-last-alignment ""))
11897 (params2
11898 (list
11899 :tstart (concat "\\begin{tabular}{" alignment "}")
11900 :tend "\\end{tabular}"
11901 :lstart "" :lend " \\\\" :sep " & "
11902 :efmt "%s\\,(%s)" :hline "\\hline")))
11903 (orgtbl-to-generic table (org-combine-plists params2 params))))
11905 (defun orgtbl-to-html (table params)
11906 "Convert the orgtbl-mode TABLE to LaTeX.
11907 TABLE is a list, each entry either the symbol `hline' for a horizontal
11908 separator line, or a list of fields for that line.
11909 PARAMS is a property list of parameters that can influence the conversion.
11910 Currently this function recognizes the following parameters:
11912 :splice When set to t, return only table body lines, don't wrap
11913 them into a <table> environment. Default is nil.
11915 The general parameters :skip and :skipcols have already been applied when
11916 this function is called. The function does *not* use `orgtbl-to-generic',
11917 so you cannot specify parameters for it."
11918 (let* ((splicep (plist-get params :splice))
11919 html)
11920 ;; Just call the formatter we already have
11921 ;; We need to make text lines for it, so put the fields back together.
11922 (setq html (org-format-org-table-html
11923 (mapcar
11924 (lambda (x)
11925 (if (eq x 'hline)
11926 "|----+----|"
11927 (concat "| " (mapconcat 'identity x " | ") " |")))
11928 table)
11929 splicep))
11930 (if (string-match "\n+\\'" html)
11931 (setq html (replace-match "" t t html)))
11932 html))
11934 (defun orgtbl-to-texinfo (table params)
11935 "Convert the orgtbl-mode TABLE to TeXInfo.
11936 TABLE is a list, each entry either the symbol `hline' for a horizontal
11937 separator line, or a list of fields for that line.
11938 PARAMS is a property list of parameters that can influence the conversion.
11939 Supports all parameters from `orgtbl-to-generic'. Most important for
11940 TeXInfo are:
11942 :splice nil/t When set to t, return only table body lines, don't wrap
11943 them into a multitable environment. Default is nil.
11945 :fmt fmt A format to be used to wrap the field, should contain
11946 %s for the original field value. For example, to wrap
11947 everything in @kbd{}, you could use :fmt \"@kbd{%s}\".
11948 This may also be a property list with column numbers and
11949 formats. For example :fmt (2 \"@kbd{%s}\" 4 \"@code{%s}\").
11951 :cf \"f1 f2..\" The column fractions for the table. By default these
11952 are computed automatically from the width of the columns
11953 under org-mode.
11955 The general parameters :skip and :skipcols have already been applied when
11956 this function is called."
11957 (let* ((total (float (apply '+ org-table-last-column-widths)))
11958 (colfrac (or (plist-get params :cf)
11959 (mapconcat
11960 (lambda (x) (format "%.3f" (/ (float x) total)))
11961 org-table-last-column-widths " ")))
11962 (params2
11963 (list
11964 :tstart (concat "@multitable @columnfractions " colfrac)
11965 :tend "@end multitable"
11966 :lstart "@item " :lend "" :sep " @tab "
11967 :hlstart "@headitem ")))
11968 (orgtbl-to-generic table (org-combine-plists params2 params))))
11970 ;;;; Link Stuff
11972 ;;; Link abbreviations
11974 (defun org-link-expand-abbrev (link)
11975 "Apply replacements as defined in `org-link-abbrev-alist."
11976 (if (string-match "^\\([a-zA-Z][-_a-zA-Z0-9]*\\)\\(::?\\(.*\\)\\)?$" link)
11977 (let* ((key (match-string 1 link))
11978 (as (or (assoc key org-link-abbrev-alist-local)
11979 (assoc key org-link-abbrev-alist)))
11980 (tag (and (match-end 2) (match-string 3 link)))
11981 rpl)
11982 (if (not as)
11983 link
11984 (setq rpl (cdr as))
11985 (cond
11986 ((symbolp rpl) (funcall rpl tag))
11987 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
11988 (t (concat rpl tag)))))
11989 link))
11991 ;;; Storing and inserting links
11993 (defvar org-insert-link-history nil
11994 "Minibuffer history for links inserted with `org-insert-link'.")
11996 (defvar org-stored-links nil
11997 "Contains the links stored with `org-store-link'.")
11999 (defvar org-store-link-plist nil
12000 "Plist with info about the most recently link created with `org-store-link'.")
12002 (defvar org-link-protocols nil
12003 "Link protocols added to Org-mode using `org-add-link-type'.")
12005 (defvar org-store-link-functions nil
12006 "List of functions that are called to create and store a link.
12007 Each function will be called in turn until one returns a non-nil
12008 value. Each function should check if it is responsible for creating
12009 this link (for example by looking at the major mode).
12010 If not, it must exit and return nil.
12011 If yes, it should return a non-nil value after a calling
12012 `org-store-link-props' with a list of properties and values.
12013 Special properties are:
12015 :type The link prefix. like \"http\". This must be given.
12016 :link The link, like \"http://www.astro.uva.nl/~dominik\".
12017 This is obligatory as well.
12018 :description Optional default description for the second pair
12019 of brackets in an Org-mode link. The user can still change
12020 this when inserting this link into an Org-mode buffer.
12022 In addition to these, any additional properties can be specified
12023 and then used in remember templates.")
12025 (defun org-add-link-type (type &optional follow publish)
12026 "Add TYPE to the list of `org-link-types'.
12027 Re-compute all regular expressions depending on `org-link-types'
12028 FOLLOW and PUBLISH are two functions. Both take the link path as
12029 an argument.
12030 FOLLOW should do whatever is necessary to follow the link, for example
12031 to find a file or display a mail message.
12033 PUBLISH takes the path and retuns the string that should be used when
12034 this document is published. FIMXE: This is actually not yet implemented."
12035 (add-to-list 'org-link-types type t)
12036 (org-make-link-regexps)
12037 (add-to-list 'org-link-protocols
12038 (list type follow publish)))
12040 (defun org-add-agenda-custom-command (entry)
12041 "Replace or add a command in `org-agenda-custom-commands'.
12042 This is mostly for hacking and trying a new command - once the command
12043 works you probably want to add it to `org-agenda-custom-commands' for good."
12044 (let ((ass (assoc (car entry) org-agenda-custom-commands)))
12045 (if ass
12046 (setcdr ass (cdr entry))
12047 (push entry org-agenda-custom-commands))))
12049 ;;;###autoload
12050 (defun org-store-link (arg)
12051 "\\<org-mode-map>Store an org-link to the current location.
12052 This link is added to `org-stored-links' and can later be inserted
12053 into an org-buffer with \\[org-insert-link].
12055 For some link types, a prefix arg is interpreted:
12056 For links to usenet articles, arg negates `org-usenet-links-prefer-google'.
12057 For file links, arg negates `org-context-in-file-links'."
12058 (interactive "P")
12059 (setq org-store-link-plist nil) ; reset
12060 (let (link cpltxt desc description search txt)
12061 (cond
12063 ((run-hook-with-args-until-success 'org-store-link-functions)
12064 (setq link (plist-get org-store-link-plist :link)
12065 desc (or (plist-get org-store-link-plist :description) link)))
12067 ((eq major-mode 'bbdb-mode)
12068 (let ((name (bbdb-record-name (bbdb-current-record)))
12069 (company (bbdb-record-getprop (bbdb-current-record) 'company)))
12070 (setq cpltxt (concat "bbdb:" (or name company))
12071 link (org-make-link cpltxt))
12072 (org-store-link-props :type "bbdb" :name name :company company)))
12074 ((eq major-mode 'Info-mode)
12075 (setq link (org-make-link "info:"
12076 (file-name-nondirectory Info-current-file)
12077 ":" Info-current-node))
12078 (setq cpltxt (concat (file-name-nondirectory Info-current-file)
12079 ":" Info-current-node))
12080 (org-store-link-props :type "info" :file Info-current-file
12081 :node Info-current-node))
12083 ((eq major-mode 'calendar-mode)
12084 (let ((cd (calendar-cursor-to-date)))
12085 (setq link
12086 (format-time-string
12087 (car org-time-stamp-formats)
12088 (apply 'encode-time
12089 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
12090 nil nil nil))))
12091 (org-store-link-props :type "calendar" :date cd)))
12093 ((or (eq major-mode 'vm-summary-mode)
12094 (eq major-mode 'vm-presentation-mode))
12095 (and (eq major-mode 'vm-presentation-mode) (vm-summarize))
12096 (vm-follow-summary-cursor)
12097 (save-excursion
12098 (vm-select-folder-buffer)
12099 (let* ((message (car vm-message-pointer))
12100 (folder buffer-file-name)
12101 (subject (vm-su-subject message))
12102 (to (vm-get-header-contents message "To"))
12103 (from (vm-get-header-contents message "From"))
12104 (message-id (vm-su-message-id message)))
12105 (org-store-link-props :type "vm" :from from :to to :subject subject
12106 :message-id message-id)
12107 (setq message-id (org-remove-angle-brackets message-id))
12108 (setq folder (abbreviate-file-name folder))
12109 (if (string-match (concat "^" (regexp-quote vm-folder-directory))
12110 folder)
12111 (setq folder (replace-match "" t t folder)))
12112 (setq cpltxt (org-email-link-description))
12113 (setq link (org-make-link "vm:" folder "#" message-id)))))
12115 ((eq major-mode 'wl-summary-mode)
12116 (let* ((msgnum (wl-summary-message-number))
12117 (message-id (elmo-message-field wl-summary-buffer-elmo-folder
12118 msgnum 'message-id))
12119 (wl-message-entity
12120 (if (fboundp 'elmo-message-entity)
12121 (elmo-message-entity
12122 wl-summary-buffer-elmo-folder msgnum)
12123 (elmo-msgdb-overview-get-entity
12124 msgnum (wl-summary-buffer-msgdb))))
12125 (from (wl-summary-line-from))
12126 (to (car (elmo-message-entity-field wl-message-entity 'to)))
12127 (subject (let (wl-thr-indent-string wl-parent-message-entity)
12128 (wl-summary-line-subject))))
12129 (org-store-link-props :type "wl" :from from :to to
12130 :subject subject :message-id message-id)
12131 (setq message-id (org-remove-angle-brackets message-id))
12132 (setq cpltxt (org-email-link-description))
12133 (setq link (org-make-link "wl:" wl-summary-buffer-folder-name
12134 "#" message-id))))
12136 ((or (equal major-mode 'mh-folder-mode)
12137 (equal major-mode 'mh-show-mode))
12138 (let ((from (org-mhe-get-header "From:"))
12139 (to (org-mhe-get-header "To:"))
12140 (message-id (org-mhe-get-header "Message-Id:"))
12141 (subject (org-mhe-get-header "Subject:")))
12142 (org-store-link-props :type "mh" :from from :to to
12143 :subject subject :message-id message-id)
12144 (setq cpltxt (org-email-link-description))
12145 (setq link (org-make-link "mhe:" (org-mhe-get-message-real-folder) "#"
12146 (org-remove-angle-brackets message-id)))))
12148 ((or (eq major-mode 'rmail-mode)
12149 (eq major-mode 'rmail-summary-mode))
12150 (save-window-excursion
12151 (save-restriction
12152 (when (eq major-mode 'rmail-summary-mode)
12153 (rmail-show-message rmail-current-message))
12154 (rmail-narrow-to-non-pruned-header)
12155 (let ((folder buffer-file-name)
12156 (message-id (mail-fetch-field "message-id"))
12157 (from (mail-fetch-field "from"))
12158 (to (mail-fetch-field "to"))
12159 (subject (mail-fetch-field "subject")))
12160 (org-store-link-props
12161 :type "rmail" :from from :to to
12162 :subject subject :message-id message-id)
12163 (setq message-id (org-remove-angle-brackets message-id))
12164 (setq cpltxt (org-email-link-description))
12165 (setq link (org-make-link "rmail:" folder "#" message-id)))
12166 (rmail-show-message rmail-current-message))))
12168 ((eq major-mode 'gnus-group-mode)
12169 (let ((group (cond ((fboundp 'gnus-group-group-name) ; depending on Gnus
12170 (gnus-group-group-name)) ; version
12171 ((fboundp 'gnus-group-name)
12172 (gnus-group-name))
12173 (t "???"))))
12174 (unless group (error "Not on a group"))
12175 (org-store-link-props :type "gnus" :group group)
12176 (setq cpltxt (concat
12177 (if (org-xor arg org-usenet-links-prefer-google)
12178 "http://groups.google.com/groups?group="
12179 "gnus:")
12180 group)
12181 link (org-make-link cpltxt))))
12183 ((memq major-mode '(gnus-summary-mode gnus-article-mode))
12184 (and (eq major-mode 'gnus-article-mode) (gnus-article-show-summary))
12185 (let* ((group gnus-newsgroup-name)
12186 (article (gnus-summary-article-number))
12187 (header (gnus-summary-article-header article))
12188 (from (mail-header-from header))
12189 (message-id (mail-header-id header))
12190 (date (mail-header-date header))
12191 (subject (gnus-summary-subject-string)))
12192 (org-store-link-props :type "gnus" :from from :subject subject
12193 :message-id message-id :group group)
12194 (setq cpltxt (org-email-link-description))
12195 (if (org-xor arg org-usenet-links-prefer-google)
12196 (setq link
12197 (concat
12198 cpltxt "\n "
12199 (format "http://groups.google.com/groups?as_umsgid=%s"
12200 (org-fixup-message-id-for-http message-id))))
12201 (setq link (org-make-link "gnus:" group
12202 "#" (number-to-string article))))))
12204 ((eq major-mode 'w3-mode)
12205 (setq cpltxt (url-view-url t)
12206 link (org-make-link cpltxt))
12207 (org-store-link-props :type "w3" :url (url-view-url t)))
12209 ((eq major-mode 'w3m-mode)
12210 (setq cpltxt (or w3m-current-title w3m-current-url)
12211 link (org-make-link w3m-current-url))
12212 (org-store-link-props :type "w3m" :url (url-view-url t)))
12214 ((setq search (run-hook-with-args-until-success
12215 'org-create-file-search-functions))
12216 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
12217 "::" search))
12218 (setq cpltxt (or description link)))
12220 ((eq major-mode 'image-mode)
12221 (setq cpltxt (concat "file:"
12222 (abbreviate-file-name buffer-file-name))
12223 link (org-make-link cpltxt))
12224 (org-store-link-props :type "image" :file buffer-file-name))
12226 ((eq major-mode 'dired-mode)
12227 ;; link to the file in the current line
12228 (setq cpltxt (concat "file:"
12229 (abbreviate-file-name
12230 (expand-file-name
12231 (dired-get-filename nil t))))
12232 link (org-make-link cpltxt)))
12234 ((and buffer-file-name (org-mode-p))
12235 ;; Just link to current headline
12236 (setq cpltxt (concat "file:"
12237 (abbreviate-file-name buffer-file-name)))
12238 ;; Add a context search string
12239 (when (org-xor org-context-in-file-links arg)
12240 ;; Check if we are on a target
12241 (if (org-in-regexp "<<\\(.*?\\)>>")
12242 (setq cpltxt (concat cpltxt "::" (match-string 1)))
12243 (setq txt (cond
12244 ((org-on-heading-p) nil)
12245 ((org-region-active-p)
12246 (buffer-substring (region-beginning) (region-end)))
12247 (t (buffer-substring (point-at-bol) (point-at-eol)))))
12248 (when (or (null txt) (string-match "\\S-" txt))
12249 (setq cpltxt
12250 (concat cpltxt "::" (org-make-org-heading-search-string txt))
12251 desc "NONE"))))
12252 (if (string-match "::\\'" cpltxt)
12253 (setq cpltxt (substring cpltxt 0 -2)))
12254 (setq link (org-make-link cpltxt)))
12256 ((buffer-file-name (buffer-base-buffer))
12257 ;; Just link to this file here.
12258 (setq cpltxt (concat "file:"
12259 (abbreviate-file-name
12260 (buffer-file-name (buffer-base-buffer)))))
12261 ;; Add a context string
12262 (when (org-xor org-context-in-file-links arg)
12263 (setq txt (if (org-region-active-p)
12264 (buffer-substring (region-beginning) (region-end))
12265 (buffer-substring (point-at-bol) (point-at-eol))))
12266 ;; Only use search option if there is some text.
12267 (when (string-match "\\S-" txt)
12268 (setq cpltxt
12269 (concat cpltxt "::" (org-make-org-heading-search-string txt))
12270 desc "NONE")))
12271 (setq link (org-make-link cpltxt)))
12273 ((interactive-p)
12274 (error "Cannot link to a buffer which is not visiting a file"))
12276 (t (setq link nil)))
12278 (if (consp link) (setq cpltxt (car link) link (cdr link)))
12279 (setq link (or link cpltxt)
12280 desc (or desc cpltxt))
12281 (if (equal desc "NONE") (setq desc nil))
12283 (if (and (interactive-p) link)
12284 (progn
12285 (setq org-stored-links
12286 (cons (list link desc) org-stored-links))
12287 (message "Stored: %s" (or desc link)))
12288 (and link (org-make-link-string link desc)))))
12290 (defun org-store-link-props (&rest plist)
12291 "Store link properties, extract names and addresses."
12292 (let (x adr)
12293 (when (setq x (plist-get plist :from))
12294 (setq adr (mail-extract-address-components x))
12295 (plist-put plist :fromname (car adr))
12296 (plist-put plist :fromaddress (nth 1 adr)))
12297 (when (setq x (plist-get plist :to))
12298 (setq adr (mail-extract-address-components x))
12299 (plist-put plist :toname (car adr))
12300 (plist-put plist :toaddress (nth 1 adr))))
12301 (let ((from (plist-get plist :from))
12302 (to (plist-get plist :to)))
12303 (when (and from to org-from-is-user-regexp)
12304 (plist-put plist :fromto
12305 (if (string-match org-from-is-user-regexp from)
12306 (concat "to %t")
12307 (concat "from %f")))))
12308 (setq org-store-link-plist plist))
12310 (defun org-email-link-description (&optional fmt)
12311 "Return the description part of an email link.
12312 This takes information from `org-store-link-plist' and formats it
12313 according to FMT (default from `org-email-link-description-format')."
12314 (setq fmt (or fmt org-email-link-description-format))
12315 (let* ((p org-store-link-plist)
12316 (to (plist-get p :toaddress))
12317 (from (plist-get p :fromaddress))
12318 (table
12319 (list
12320 (cons "%c" (plist-get p :fromto))
12321 (cons "%F" (plist-get p :from))
12322 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
12323 (cons "%T" (plist-get p :to))
12324 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
12325 (cons "%s" (plist-get p :subject))
12326 (cons "%m" (plist-get p :message-id)))))
12327 (when (string-match "%c" fmt)
12328 ;; Check if the user wrote this message
12329 (if (and org-from-is-user-regexp from to
12330 (save-match-data (string-match org-from-is-user-regexp from)))
12331 (setq fmt (replace-match "to %t" t t fmt))
12332 (setq fmt (replace-match "from %f" t t fmt))))
12333 (org-replace-escapes fmt table)))
12335 (defun org-make-org-heading-search-string (&optional string heading)
12336 "Make search string for STRING or current headline."
12337 (interactive)
12338 (let ((s (or string (org-get-heading))))
12339 (unless (and string (not heading))
12340 ;; We are using a headline, clean up garbage in there.
12341 (if (string-match org-todo-regexp s)
12342 (setq s (replace-match "" t t s)))
12343 (if (string-match (org-re ":[[:alnum:]_@:]+:[ \t]*$") s)
12344 (setq s (replace-match "" t t s)))
12345 (setq s (org-trim s))
12346 (if (string-match (concat "^\\(" org-quote-string "\\|"
12347 org-comment-string "\\)") s)
12348 (setq s (replace-match "" t t s)))
12349 (while (string-match org-ts-regexp s)
12350 (setq s (replace-match "" t t s))))
12351 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
12352 (setq s (replace-match " " t t s)))
12353 (or string (setq s (concat "*" s))) ; Add * for headlines
12354 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
12356 (defun org-make-link (&rest strings)
12357 "Concatenate STRINGS."
12358 (apply 'concat strings))
12360 (defun org-make-link-string (link &optional description)
12361 "Make a link with brackets, consisting of LINK and DESCRIPTION."
12362 (unless (string-match "\\S-" link)
12363 (error "Empty link"))
12364 (when (stringp description)
12365 ;; Remove brackets from the description, they are fatal.
12366 (while (string-match "\\[" description)
12367 (setq description (replace-match "{" t t description)))
12368 (while (string-match "\\]" description)
12369 (setq description (replace-match "}" t t description))))
12370 (when (equal (org-link-escape link) description)
12371 ;; No description needed, it is identical
12372 (setq description nil))
12373 (when (and (not description)
12374 (not (equal link (org-link-escape link))))
12375 (setq description link))
12376 (concat "[[" (org-link-escape link) "]"
12377 (if description (concat "[" description "]") "")
12378 "]"))
12380 (defconst org-link-escape-chars
12381 '((?\ . "%20")
12382 (?\[ . "%5B")
12383 (?\] . "%5D")
12384 (?\340 . "%E0") ; `a
12385 (?\342 . "%E2") ; ^a
12386 (?\347 . "%E7") ; ,c
12387 (?\350 . "%E8") ; `e
12388 (?\351 . "%E9") ; 'e
12389 (?\352 . "%EA") ; ^e
12390 (?\356 . "%EE") ; ^i
12391 (?\364 . "%F4") ; ^o
12392 (?\371 . "%F9") ; `u
12393 (?\373 . "%FB") ; ^u
12394 (?\; . "%3B")
12395 (?? . "%3F")
12396 (?= . "%3D")
12397 (?+ . "%2B")
12399 "Association list of escapes for some characters problematic in links.
12400 This is the list that is used for internal purposes.")
12402 (defconst org-link-escape-chars-browser
12403 '((?\ . "%20")) ; 32 for the SPC char
12404 "Association list of escapes for some characters problematic in links.
12405 This is the list that is used before handing over to the browser.")
12407 (defun org-link-escape (text &optional table)
12408 "Escape charaters in TEXT that are problematic for links."
12409 (setq table (or table org-link-escape-chars))
12410 (when text
12411 (let ((re (mapconcat (lambda (x) (regexp-quote
12412 (char-to-string (car x))))
12413 table "\\|")))
12414 (while (string-match re text)
12415 (setq text
12416 (replace-match
12417 (cdr (assoc (string-to-char (match-string 0 text))
12418 table))
12419 t t text)))
12420 text)))
12422 (defun org-link-unescape (text &optional table)
12423 "Reverse the action of `org-link-escape'."
12424 (setq table (or table org-link-escape-chars))
12425 (when text
12426 (let ((re (mapconcat (lambda (x) (regexp-quote (cdr x)))
12427 table "\\|")))
12428 (while (string-match re text)
12429 (setq text
12430 (replace-match
12431 (char-to-string (car (rassoc (match-string 0 text) table)))
12432 t t text)))
12433 text)))
12435 (defun org-xor (a b)
12436 "Exclusive or."
12437 (if a (not b) b))
12439 (defun org-get-header (header)
12440 "Find a header field in the current buffer."
12441 (save-excursion
12442 (goto-char (point-min))
12443 (let ((case-fold-search t) s)
12444 (cond
12445 ((eq header 'from)
12446 (if (re-search-forward "^From:\\s-+\\(.*\\)" nil t)
12447 (setq s (match-string 1)))
12448 (while (string-match "\"" s)
12449 (setq s (replace-match "" t t s)))
12450 (if (string-match "[<(].*" s)
12451 (setq s (replace-match "" t t s))))
12452 ((eq header 'message-id)
12453 (if (re-search-forward "^message-id:\\s-+\\(.*\\)" nil t)
12454 (setq s (match-string 1))))
12455 ((eq header 'subject)
12456 (if (re-search-forward "^subject:\\s-+\\(.*\\)" nil t)
12457 (setq s (match-string 1)))))
12458 (if (string-match "\\`[ \t\]+" s) (setq s (replace-match "" t t s)))
12459 (if (string-match "[ \t\]+\\'" s) (setq s (replace-match "" t t s)))
12460 s)))
12463 (defun org-fixup-message-id-for-http (s)
12464 "Replace special characters in a message id, so it can be used in an http query."
12465 (while (string-match "<" s)
12466 (setq s (replace-match "%3C" t t s)))
12467 (while (string-match ">" s)
12468 (setq s (replace-match "%3E" t t s)))
12469 (while (string-match "@" s)
12470 (setq s (replace-match "%40" t t s)))
12473 ;;;###autoload
12474 (defun org-insert-link-global ()
12475 "Insert a link like Org-mode does.
12476 This command can be called in any mode to insert a link in Org-mode syntax."
12477 (interactive)
12478 (org-run-like-in-org-mode 'org-insert-link))
12480 (defun org-insert-link (&optional complete-file)
12481 "Insert a link. At the prompt, enter the link.
12483 Completion can be used to select a link previously stored with
12484 `org-store-link'. When the empty string is entered (i.e. if you just
12485 press RET at the prompt), the link defaults to the most recently
12486 stored link. As SPC triggers completion in the minibuffer, you need to
12487 use M-SPC or C-q SPC to force the insertion of a space character.
12489 You will also be prompted for a description, and if one is given, it will
12490 be displayed in the buffer instead of the link.
12492 If there is already a link at point, this command will allow you to edit link
12493 and description parts.
12495 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can be
12496 selected using completion. The path to the file will be relative to
12497 the current directory if the file is in the current directory or a
12498 subdirectory. Otherwise, the link will be the absolute path as
12499 completed in the minibuffer (i.e. normally ~/path/to/file).
12501 With two \\[universal-argument] prefixes, enforce an absolute path even if the file
12502 is in the current directory or below.
12503 With three \\[universal-argument] prefixes, negate the meaning of
12504 `org-keep-stored-link-after-insertion'."
12505 (interactive "P")
12506 (let* ((wcf (current-window-configuration))
12507 (region (if (org-region-active-p)
12508 (buffer-substring (region-beginning) (region-end))))
12509 (remove (and region (list (region-beginning) (region-end))))
12510 (desc region)
12511 tmphist ; byte-compile incorrectly complains about this
12512 link entry file)
12513 (cond
12514 ((org-in-regexp org-bracket-link-regexp 1)
12515 ;; We do have a link at point, and we are going to edit it.
12516 (setq remove (list (match-beginning 0) (match-end 0)))
12517 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
12518 (setq link (read-string "Link: "
12519 (org-link-unescape
12520 (org-match-string-no-properties 1)))))
12521 ((or (org-in-regexp org-angle-link-re)
12522 (org-in-regexp org-plain-link-re))
12523 ;; Convert to bracket link
12524 (setq remove (list (match-beginning 0) (match-end 0))
12525 link (read-string "Link: "
12526 (org-remove-angle-brackets (match-string 0)))))
12527 ((equal complete-file '(4))
12528 ;; Completing read for file names.
12529 (setq file (read-file-name "File: "))
12530 (let ((pwd (file-name-as-directory (expand-file-name ".")))
12531 (pwd1 (file-name-as-directory (abbreviate-file-name
12532 (expand-file-name ".")))))
12533 (cond
12534 ((equal complete-file '(16))
12535 (setq link (org-make-link
12536 "file:"
12537 (abbreviate-file-name (expand-file-name file)))))
12538 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
12539 (setq link (org-make-link "file:" (match-string 1 file))))
12540 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
12541 (expand-file-name file))
12542 (setq link (org-make-link
12543 "file:" (match-string 1 (expand-file-name file)))))
12544 (t (setq link (org-make-link "file:" file))))))
12546 ;; Read link, with completion for stored links.
12547 (with-output-to-temp-buffer "*Org Links*"
12548 (princ "Insert a link. Use TAB to complete valid link prefixes.\n")
12549 (when org-stored-links
12550 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
12551 (princ (mapconcat
12552 (lambda (x)
12553 (if (nth 1 x) (concat (car x) " (" (nth 1 x) ")") (car x)))
12554 (reverse org-stored-links) "\n"))))
12555 (let ((cw (selected-window)))
12556 (select-window (get-buffer-window "*Org Links*"))
12557 (shrink-window-if-larger-than-buffer)
12558 (setq truncate-lines t)
12559 (select-window cw))
12560 ;; Fake a link history, containing the stored links.
12561 (setq tmphist (append (mapcar 'car org-stored-links)
12562 org-insert-link-history))
12563 (unwind-protect
12564 (setq link (org-completing-read
12565 "Link: "
12566 (append
12567 (mapcar (lambda (x) (list (concat (car x) ":")))
12568 (append org-link-abbrev-alist-local org-link-abbrev-alist))
12569 (mapcar (lambda (x) (list (concat x ":")))
12570 org-link-types))
12571 nil nil nil
12572 'tmphist
12573 (or (car (car org-stored-links)))))
12574 (set-window-configuration wcf)
12575 (kill-buffer "*Org Links*"))
12576 (setq entry (assoc link org-stored-links))
12577 (or entry (push link org-insert-link-history))
12578 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
12579 (not org-keep-stored-link-after-insertion))
12580 (setq org-stored-links (delq (assoc link org-stored-links)
12581 org-stored-links)))
12582 (setq desc (or desc (nth 1 entry)))))
12584 (if (string-match org-plain-link-re link)
12585 ;; URL-like link, normalize the use of angular brackets.
12586 (setq link (org-make-link (org-remove-angle-brackets link))))
12588 ;; Check if we are linking to the current file with a search option
12589 ;; If yes, simplify the link by using only the search option.
12590 (when (and buffer-file-name
12591 (string-match "\\<file:\\(.+?\\)::\\([^>]+\\)" link))
12592 (let* ((path (match-string 1 link))
12593 (case-fold-search nil)
12594 (search (match-string 2 link)))
12595 (save-match-data
12596 (if (equal (file-truename buffer-file-name) (file-truename path))
12597 ;; We are linking to this same file, with a search option
12598 (setq link search)))))
12600 ;; Check if we can/should use a relative path. If yes, simplify the link
12601 (when (string-match "\\<file:\\(.*\\)" link)
12602 (let* ((path (match-string 1 link))
12603 (origpath path)
12604 (case-fold-search nil))
12605 (cond
12606 ((eq org-link-file-path-type 'absolute)
12607 (setq path (abbreviate-file-name (expand-file-name path))))
12608 ((eq org-link-file-path-type 'noabbrev)
12609 (setq path (expand-file-name path)))
12610 ((eq org-link-file-path-type 'relative)
12611 (setq path (file-relative-name path)))
12613 (save-match-data
12614 (if (string-match (concat "^" (regexp-quote
12615 (file-name-as-directory
12616 (expand-file-name "."))))
12617 (expand-file-name path))
12618 ;; We are linking a file with relative path name.
12619 (setq path (substring (expand-file-name path)
12620 (match-end 0)))))))
12621 (setq link (concat "file:" path))
12622 (if (equal desc origpath)
12623 (setq desc path))))
12625 (setq desc (read-string "Description: " desc))
12626 (unless (string-match "\\S-" desc) (setq desc nil))
12627 (if remove (apply 'delete-region remove))
12628 (insert (org-make-link-string link desc))))
12630 (defun org-completing-read (&rest args)
12631 (let ((minibuffer-local-completion-map
12632 (copy-keymap minibuffer-local-completion-map)))
12633 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
12634 (apply 'completing-read args)))
12636 ;;; Opening/following a link
12637 (defvar org-link-search-failed nil)
12639 (defun org-next-link ()
12640 "Move forward to the next link.
12641 If the link is in hidden text, expose it."
12642 (interactive)
12643 (when (and org-link-search-failed (eq this-command last-command))
12644 (goto-char (point-min))
12645 (message "Link search wrapped back to beginning of buffer"))
12646 (setq org-link-search-failed nil)
12647 (let* ((pos (point))
12648 (ct (org-context))
12649 (a (assoc :link ct)))
12650 (if a (goto-char (nth 2 a)))
12651 (if (re-search-forward org-any-link-re nil t)
12652 (progn
12653 (goto-char (match-beginning 0))
12654 (if (org-invisible-p) (org-show-context)))
12655 (goto-char pos)
12656 (setq org-link-search-failed t)
12657 (error "No further link found"))))
12659 (defun org-previous-link ()
12660 "Move backward to the previous link.
12661 If the link is in hidden text, expose it."
12662 (interactive)
12663 (when (and org-link-search-failed (eq this-command last-command))
12664 (goto-char (point-max))
12665 (message "Link search wrapped back to end of buffer"))
12666 (setq org-link-search-failed nil)
12667 (let* ((pos (point))
12668 (ct (org-context))
12669 (a (assoc :link ct)))
12670 (if a (goto-char (nth 1 a)))
12671 (if (re-search-backward org-any-link-re nil t)
12672 (progn
12673 (goto-char (match-beginning 0))
12674 (if (org-invisible-p) (org-show-context)))
12675 (goto-char pos)
12676 (setq org-link-search-failed t)
12677 (error "No further link found"))))
12679 (defun org-find-file-at-mouse (ev)
12680 "Open file link or URL at mouse."
12681 (interactive "e")
12682 (mouse-set-point ev)
12683 (org-open-at-point 'in-emacs))
12685 (defun org-open-at-mouse (ev)
12686 "Open file link or URL at mouse."
12687 (interactive "e")
12688 (mouse-set-point ev)
12689 (org-open-at-point))
12691 (defvar org-window-config-before-follow-link nil
12692 "The window configuration before following a link.
12693 This is saved in case the need arises to restore it.")
12695 (defvar org-open-link-marker (make-marker)
12696 "Marker pointing to the location where `org-open-at-point; was called.")
12698 ;;;###autoload
12699 (defun org-open-at-point-global ()
12700 "Follow a link like Org-mode does.
12701 This command can be called in any mode to follow a link that has
12702 Org-mode syntax."
12703 (interactive)
12704 (org-run-like-in-org-mode 'org-open-at-point))
12706 (defun org-open-at-point (&optional in-emacs)
12707 "Open link at or after point.
12708 If there is no link at point, this function will search forward up to
12709 the end of the current subtree.
12710 Normally, files will be opened by an appropriate application. If the
12711 optional argument IN-EMACS is non-nil, Emacs will visit the file."
12712 (interactive "P")
12713 (move-marker org-open-link-marker (point))
12714 (setq org-window-config-before-follow-link (current-window-configuration))
12715 (org-remove-occur-highlights nil nil t)
12716 (if (org-at-timestamp-p t)
12717 (org-follow-timestamp-link)
12718 (let (type path link line search (pos (point)))
12719 (catch 'match
12720 (save-excursion
12721 (skip-chars-forward "^]\n\r")
12722 (when (org-in-regexp org-bracket-link-regexp)
12723 (setq link (org-link-unescape (org-match-string-no-properties 1)))
12724 (while (string-match " *\n *" link)
12725 (setq link (replace-match " " t t link)))
12726 (setq link (org-link-expand-abbrev link))
12727 (if (string-match org-link-re-with-space2 link)
12728 (setq type (match-string 1 link) path (match-string 2 link))
12729 (setq type "thisfile" path link))
12730 (throw 'match t)))
12732 (when (get-text-property (point) 'org-linked-text)
12733 (setq type "thisfile"
12734 pos (if (get-text-property (1+ (point)) 'org-linked-text)
12735 (1+ (point)) (point))
12736 path (buffer-substring
12737 (previous-single-property-change pos 'org-linked-text)
12738 (next-single-property-change pos 'org-linked-text)))
12739 (throw 'match t))
12741 (save-excursion
12742 (when (or (org-in-regexp org-angle-link-re)
12743 (org-in-regexp org-plain-link-re))
12744 (setq type (match-string 1) path (match-string 2))
12745 (throw 'match t)))
12746 (when (org-in-regexp "\\<\\([^><\n]+\\)\\>")
12747 (setq type "tree-match"
12748 path (match-string 1))
12749 (throw 'match t))
12750 (save-excursion
12751 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@:]+\\):[ \t]*$"))
12752 (setq type "tags"
12753 path (match-string 1))
12754 (while (string-match ":" path)
12755 (setq path (replace-match "+" t t path)))
12756 (throw 'match t))))
12757 (unless path
12758 (error "No link found"))
12759 ;; Remove any trailing spaces in path
12760 (if (string-match " +\\'" path)
12761 (setq path (replace-match "" t t path)))
12763 (cond
12765 ((assoc type org-link-protocols)
12766 (funcall (nth 1 (assoc type org-link-protocols)) path))
12768 ((equal type "mailto")
12769 (let ((cmd (car org-link-mailto-program))
12770 (args (cdr org-link-mailto-program)) args1
12771 (address path) (subject "") a)
12772 (if (string-match "\\(.*\\)::\\(.*\\)" path)
12773 (setq address (match-string 1 path)
12774 subject (org-link-escape (match-string 2 path))))
12775 (while args
12776 (cond
12777 ((not (stringp (car args))) (push (pop args) args1))
12778 (t (setq a (pop args))
12779 (if (string-match "%a" a)
12780 (setq a (replace-match address t t a)))
12781 (if (string-match "%s" a)
12782 (setq a (replace-match subject t t a)))
12783 (push a args1))))
12784 (apply cmd (nreverse args1))))
12786 ((member type '("http" "https" "ftp" "news"))
12787 (browse-url (concat type ":" (org-link-escape
12788 path org-link-escape-chars-browser))))
12790 ((member type '("message"))
12791 (browse-url (concat type ":" path)))
12793 ((string= type "tags")
12794 (org-tags-view in-emacs path))
12795 ((string= type "thisfile")
12796 (if in-emacs
12797 (switch-to-buffer-other-window
12798 (org-get-buffer-for-internal-link (current-buffer)))
12799 (org-mark-ring-push))
12800 (let ((cmd `(org-link-search
12801 ,path
12802 ,(cond ((equal in-emacs '(4)) 'occur)
12803 ((equal in-emacs '(16)) 'org-occur)
12804 (t nil))
12805 ,pos)))
12806 (condition-case nil (eval cmd)
12807 (error (progn (widen) (eval cmd))))))
12809 ((string= type "tree-match")
12810 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
12812 ((string= type "file")
12813 (if (string-match "::\\([0-9]+\\)\\'" path)
12814 (setq line (string-to-number (match-string 1 path))
12815 path (substring path 0 (match-beginning 0)))
12816 (if (string-match "::\\(.+\\)\\'" path)
12817 (setq search (match-string 1 path)
12818 path (substring path 0 (match-beginning 0)))))
12819 (if (string-match "[*?{]" (file-name-nondirectory path))
12820 (dired path)
12821 (org-open-file path in-emacs line search)))
12823 ((string= type "news")
12824 (org-follow-gnus-link path))
12826 ((string= type "bbdb")
12827 (org-follow-bbdb-link path))
12829 ((string= type "info")
12830 (org-follow-info-link path))
12832 ((string= type "gnus")
12833 (let (group article)
12834 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
12835 (error "Error in Gnus link"))
12836 (setq group (match-string 1 path)
12837 article (match-string 3 path))
12838 (org-follow-gnus-link group article)))
12840 ((string= type "vm")
12841 (let (folder article)
12842 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
12843 (error "Error in VM link"))
12844 (setq folder (match-string 1 path)
12845 article (match-string 3 path))
12846 ;; in-emacs is the prefix arg, will be interpreted as read-only
12847 (org-follow-vm-link folder article in-emacs)))
12849 ((string= type "wl")
12850 (let (folder article)
12851 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
12852 (error "Error in Wanderlust link"))
12853 (setq folder (match-string 1 path)
12854 article (match-string 3 path))
12855 (org-follow-wl-link folder article)))
12857 ((string= type "mhe")
12858 (let (folder article)
12859 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
12860 (error "Error in MHE link"))
12861 (setq folder (match-string 1 path)
12862 article (match-string 3 path))
12863 (org-follow-mhe-link folder article)))
12865 ((string= type "rmail")
12866 (let (folder article)
12867 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
12868 (error "Error in RMAIL link"))
12869 (setq folder (match-string 1 path)
12870 article (match-string 3 path))
12871 (org-follow-rmail-link folder article)))
12873 ((string= type "shell")
12874 (let ((cmd path))
12875 (if (or (not org-confirm-shell-link-function)
12876 (funcall org-confirm-shell-link-function
12877 (format "Execute \"%s\" in shell? "
12878 (org-add-props cmd nil
12879 'face 'org-warning))))
12880 (progn
12881 (message "Executing %s" cmd)
12882 (shell-command cmd))
12883 (error "Abort"))))
12885 ((string= type "elisp")
12886 (let ((cmd path))
12887 (if (or (not org-confirm-elisp-link-function)
12888 (funcall org-confirm-elisp-link-function
12889 (format "Execute \"%s\" as elisp? "
12890 (org-add-props cmd nil
12891 'face 'org-warning))))
12892 (message "%s => %s" cmd (eval (read cmd)))
12893 (error "Abort"))))
12896 (browse-url-at-point)))))
12897 (move-marker org-open-link-marker nil))
12899 ;;; File search
12901 (defvar org-create-file-search-functions nil
12902 "List of functions to construct the right search string for a file link.
12903 These functions are called in turn with point at the location to
12904 which the link should point.
12906 A function in the hook should first test if it would like to
12907 handle this file type, for example by checking the major-mode or
12908 the file extension. If it decides not to handle this file, it
12909 should just return nil to give other functions a chance. If it
12910 does handle the file, it must return the search string to be used
12911 when following the link. The search string will be part of the
12912 file link, given after a double colon, and `org-open-at-point'
12913 will automatically search for it. If special measures must be
12914 taken to make the search successful, another function should be
12915 added to the companion hook `org-execute-file-search-functions',
12916 which see.
12918 A function in this hook may also use `setq' to set the variable
12919 `description' to provide a suggestion for the descriptive text to
12920 be used for this link when it gets inserted into an Org-mode
12921 buffer with \\[org-insert-link].")
12923 (defvar org-execute-file-search-functions nil
12924 "List of functions to execute a file search triggered by a link.
12926 Functions added to this hook must accept a single argument, the
12927 search string that was part of the file link, the part after the
12928 double colon. The function must first check if it would like to
12929 handle this search, for example by checking the major-mode or the
12930 file extension. If it decides not to handle this search, it
12931 should just return nil to give other functions a chance. If it
12932 does handle the search, it must return a non-nil value to keep
12933 other functions from trying.
12935 Each function can access the current prefix argument through the
12936 variable `current-prefix-argument'. Note that a single prefix is
12937 used to force opening a link in Emacs, so it may be good to only
12938 use a numeric or double prefix to guide the search function.
12940 In case this is needed, a function in this hook can also restore
12941 the window configuration before `org-open-at-point' was called using:
12943 (set-window-configuration org-window-config-before-follow-link)")
12945 (defun org-link-search (s &optional type avoid-pos)
12946 "Search for a link search option.
12947 If S is surrounded by forward slashes, it is interpreted as a
12948 regular expression. In org-mode files, this will create an `org-occur'
12949 sparse tree. In ordinary files, `occur' will be used to list matches.
12950 If the current buffer is in `dired-mode', grep will be used to search
12951 in all files. If AVOID-POS is given, ignore matches near that position."
12952 (let ((case-fold-search t)
12953 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
12954 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
12955 (append '(("") (" ") ("\t") ("\n"))
12956 org-emphasis-alist)
12957 "\\|") "\\)"))
12958 (pos (point))
12959 (pre "") (post "")
12960 words re0 re1 re2 re3 re4 re5 re2a reall)
12961 (cond
12962 ;; First check if there are any special
12963 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
12964 ;; Now try the builtin stuff
12965 ((save-excursion
12966 (goto-char (point-min))
12967 (and
12968 (re-search-forward
12969 (concat "<<" (regexp-quote s0) ">>") nil t)
12970 (setq pos (match-beginning 0))))
12971 ;; There is an exact target for this
12972 (goto-char pos))
12973 ((string-match "^/\\(.*\\)/$" s)
12974 ;; A regular expression
12975 (cond
12976 ((org-mode-p)
12977 (org-occur (match-string 1 s)))
12978 ;;((eq major-mode 'dired-mode)
12979 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
12980 (t (org-do-occur (match-string 1 s)))))
12982 ;; A normal search strings
12983 (when (equal (string-to-char s) ?*)
12984 ;; Anchor on headlines, post may include tags.
12985 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
12986 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@:+]:[ \t]*\\)?$")
12987 s (substring s 1)))
12988 (remove-text-properties
12989 0 (length s)
12990 '(face nil mouse-face nil keymap nil fontified nil) s)
12991 ;; Make a series of regular expressions to find a match
12992 (setq words (org-split-string s "[ \n\r\t]+")
12993 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
12994 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
12995 "\\)" markers)
12996 re2a (concat "[ \t\r\n]\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
12997 re4 (concat "[^a-zA-Z_]\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
12998 re1 (concat pre re2 post)
12999 re3 (concat pre re4 post)
13000 re5 (concat pre ".*" re4)
13001 re2 (concat pre re2)
13002 re2a (concat pre re2a)
13003 re4 (concat pre re4)
13004 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
13005 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
13006 re5 "\\)"
13008 (cond
13009 ((eq type 'org-occur) (org-occur reall))
13010 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
13011 (t (goto-char (point-min))
13012 (if (or (org-search-not-self 1 re0 nil t)
13013 (org-search-not-self 1 re1 nil t)
13014 (org-search-not-self 1 re2 nil t)
13015 (org-search-not-self 1 re2a nil t)
13016 (org-search-not-self 1 re3 nil t)
13017 (org-search-not-self 1 re4 nil t)
13018 (org-search-not-self 1 re5 nil t)
13020 (goto-char (match-beginning 1))
13021 (goto-char pos)
13022 (error "No match")))))
13024 ;; Normal string-search
13025 (goto-char (point-min))
13026 (if (search-forward s nil t)
13027 (goto-char (match-beginning 0))
13028 (error "No match"))))
13029 (and (org-mode-p) (org-show-context 'link-search))))
13031 (defun org-search-not-self (group &rest args)
13032 "Execute `re-search-forward', but only accept matches that do not
13033 enclose the position of `org-open-link-marker'."
13034 (let ((m org-open-link-marker))
13035 (catch 'exit
13036 (while (apply 're-search-forward args)
13037 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
13038 (goto-char (match-end group))
13039 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
13040 (> (match-beginning 0) (marker-position m))
13041 (< (match-end 0) (marker-position m)))
13042 (save-match-data
13043 (or (not (org-in-regexp
13044 org-bracket-link-analytic-regexp 1))
13045 (not (match-end 4)) ; no description
13046 (and (<= (match-beginning 4) (point))
13047 (>= (match-end 4) (point))))))
13048 (throw 'exit (point))))))))
13050 (defun org-get-buffer-for-internal-link (buffer)
13051 "Return a buffer to be used for displaying the link target of internal links."
13052 (cond
13053 ((not org-display-internal-link-with-indirect-buffer)
13054 buffer)
13055 ((string-match "(Clone)$" (buffer-name buffer))
13056 (message "Buffer is already a clone, not making another one")
13057 ;; we also do not modify visibility in this case
13058 buffer)
13059 (t ; make a new indirect buffer for displaying the link
13060 (let* ((bn (buffer-name buffer))
13061 (ibn (concat bn "(Clone)"))
13062 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
13063 (with-current-buffer ib (org-overview))
13064 ib))))
13066 (defun org-do-occur (regexp &optional cleanup)
13067 "Call the Emacs command `occur'.
13068 If CLEANUP is non-nil, remove the printout of the regular expression
13069 in the *Occur* buffer. This is useful if the regex is long and not useful
13070 to read."
13071 (occur regexp)
13072 (when cleanup
13073 (let ((cwin (selected-window)) win beg end)
13074 (when (setq win (get-buffer-window "*Occur*"))
13075 (select-window win))
13076 (goto-char (point-min))
13077 (when (re-search-forward "match[a-z]+" nil t)
13078 (setq beg (match-end 0))
13079 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
13080 (setq end (1- (match-beginning 0)))))
13081 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
13082 (goto-char (point-min))
13083 (select-window cwin))))
13085 ;;; The mark ring for links jumps
13087 (defvar org-mark-ring nil
13088 "Mark ring for positions before jumps in Org-mode.")
13089 (defvar org-mark-ring-last-goto nil
13090 "Last position in the mark ring used to go back.")
13091 ;; Fill and close the ring
13092 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
13093 (loop for i from 1 to org-mark-ring-length do
13094 (push (make-marker) org-mark-ring))
13095 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
13096 org-mark-ring)
13098 (defun org-mark-ring-push (&optional pos buffer)
13099 "Put the current position or POS into the mark ring and rotate it."
13100 (interactive)
13101 (setq pos (or pos (point)))
13102 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
13103 (move-marker (car org-mark-ring)
13104 (or pos (point))
13105 (or buffer (current-buffer)))
13106 (message "%s"
13107 (substitute-command-keys
13108 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
13110 (defun org-mark-ring-goto (&optional n)
13111 "Jump to the previous position in the mark ring.
13112 With prefix arg N, jump back that many stored positions. When
13113 called several times in succession, walk through the entire ring.
13114 Org-mode commands jumping to a different position in the current file,
13115 or to another Org-mode file, automatically push the old position
13116 onto the ring."
13117 (interactive "p")
13118 (let (p m)
13119 (if (eq last-command this-command)
13120 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
13121 (setq p org-mark-ring))
13122 (setq org-mark-ring-last-goto p)
13123 (setq m (car p))
13124 (switch-to-buffer (marker-buffer m))
13125 (goto-char m)
13126 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
13128 (defun org-remove-angle-brackets (s)
13129 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
13130 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
13132 (defun org-add-angle-brackets (s)
13133 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
13134 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
13137 ;;; Following specific links
13139 (defun org-follow-timestamp-link ()
13140 (cond
13141 ((org-at-date-range-p t)
13142 (let ((org-agenda-start-on-weekday)
13143 (t1 (match-string 1))
13144 (t2 (match-string 2)))
13145 (setq t1 (time-to-days (org-time-string-to-time t1))
13146 t2 (time-to-days (org-time-string-to-time t2)))
13147 (org-agenda-list nil t1 (1+ (- t2 t1)))))
13148 ((org-at-timestamp-p t)
13149 (org-agenda-list nil (time-to-days (org-time-string-to-time
13150 (substring (match-string 1) 0 10)))
13152 (t (error "This should not happen"))))
13155 (defun org-follow-bbdb-link (name)
13156 "Follow a BBDB link to NAME."
13157 (require 'bbdb)
13158 (let ((inhibit-redisplay (not debug-on-error))
13159 (bbdb-electric-p nil))
13160 (catch 'exit
13161 ;; Exact match on name
13162 (bbdb-name (concat "\\`" name "\\'") nil)
13163 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
13164 ;; Exact match on name
13165 (bbdb-company (concat "\\`" name "\\'") nil)
13166 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
13167 ;; Partial match on name
13168 (bbdb-name name nil)
13169 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
13170 ;; Partial match on company
13171 (bbdb-company name nil)
13172 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
13173 ;; General match including network address and notes
13174 (bbdb name nil)
13175 (when (= 0 (buffer-size (get-buffer "*BBDB*")))
13176 (delete-window (get-buffer-window "*BBDB*"))
13177 (error "No matching BBDB record")))))
13179 (defun org-follow-info-link (name)
13180 "Follow an info file & node link to NAME."
13181 (if (or (string-match "\\(.*\\)::?\\(.*\\)" name)
13182 (string-match "\\(.*\\)" name))
13183 (progn
13184 (require 'info)
13185 (if (match-string 2 name) ; If there isn't a node, choose "Top"
13186 (Info-find-node (match-string 1 name) (match-string 2 name))
13187 (Info-find-node (match-string 1 name) "Top")))
13188 (message "Could not open: %s" name)))
13190 (defun org-follow-gnus-link (&optional group article)
13191 "Follow a Gnus link to GROUP and ARTICLE."
13192 (require 'gnus)
13193 (funcall (cdr (assq 'gnus org-link-frame-setup)))
13194 (if gnus-other-frame-object (select-frame gnus-other-frame-object))
13195 (cond ((and group article)
13196 (gnus-group-read-group 1 nil group)
13197 (gnus-summary-goto-article (string-to-number article) nil t))
13198 (group (gnus-group-jump-to-group group))))
13200 (defun org-follow-vm-link (&optional folder article readonly)
13201 "Follow a VM link to FOLDER and ARTICLE."
13202 (require 'vm)
13203 (setq article (org-add-angle-brackets article))
13204 (if (string-match "^//\\([a-zA-Z]+@\\)?\\([^:]+\\):\\(.*\\)" folder)
13205 ;; ange-ftp or efs or tramp access
13206 (let ((user (or (match-string 1 folder) (user-login-name)))
13207 (host (match-string 2 folder))
13208 (file (match-string 3 folder)))
13209 (cond
13210 ((featurep 'tramp)
13211 ;; use tramp to access the file
13212 (if (featurep 'xemacs)
13213 (setq folder (format "[%s@%s]%s" user host file))
13214 (setq folder (format "/%s@%s:%s" user host file))))
13216 ;; use ange-ftp or efs
13217 (require (if (featurep 'xemacs) 'efs 'ange-ftp))
13218 (setq folder (format "/%s@%s:%s" user host file))))))
13219 (when folder
13220 (funcall (cdr (assq 'vm org-link-frame-setup)) folder readonly)
13221 (sit-for 0.1)
13222 (when article
13223 (vm-select-folder-buffer)
13224 (widen)
13225 (let ((case-fold-search t))
13226 (goto-char (point-min))
13227 (if (not (re-search-forward
13228 (concat "^" "message-id: *" (regexp-quote article))))
13229 (error "Could not find the specified message in this folder"))
13230 (vm-isearch-update)
13231 (vm-isearch-narrow)
13232 (vm-beginning-of-message)
13233 (vm-summarize)))))
13235 (defun org-follow-wl-link (folder article)
13236 "Follow a Wanderlust link to FOLDER and ARTICLE."
13237 (if (and (string= folder "%")
13238 article
13239 (string-match "^\\([^#]+\\)\\(#\\(.*\\)\\)?" article))
13240 ;; XXX: imap-uw supports folders starting with '#' such as "#mh/inbox".
13241 ;; Thus, we recompose folder and article ids.
13242 (setq folder (format "%s#%s" folder (match-string 1 article))
13243 article (match-string 3 article)))
13244 (if (not (elmo-folder-exists-p (wl-folder-get-elmo-folder folder)))
13245 (error "No such folder: %s" folder))
13246 (wl-summary-goto-folder-subr folder 'no-sync t nil t nil nil)
13247 (and article
13248 (wl-summary-jump-to-msg-by-message-id (org-add-angle-brackets article))
13249 (wl-summary-redisplay)))
13251 (defun org-follow-rmail-link (folder article)
13252 "Follow an RMAIL link to FOLDER and ARTICLE."
13253 (setq article (org-add-angle-brackets article))
13254 (let (message-number)
13255 (save-excursion
13256 (save-window-excursion
13257 (rmail (if (string= folder "RMAIL") rmail-file-name folder))
13258 (setq message-number
13259 (save-restriction
13260 (widen)
13261 (goto-char (point-max))
13262 (if (re-search-backward
13263 (concat "^Message-ID:\\s-+" (regexp-quote
13264 (or article "")))
13265 nil t)
13266 (rmail-what-message))))))
13267 (if message-number
13268 (progn
13269 (rmail (if (string= folder "RMAIL") rmail-file-name folder))
13270 (rmail-show-message message-number)
13271 message-number)
13272 (error "Message not found"))))
13274 ;;; mh-e integration based on planner-mode
13275 (defun org-mhe-get-message-real-folder ()
13276 "Return the name of the current message real folder, so if you use
13277 sequences, it will now work."
13278 (save-excursion
13279 (let* ((folder
13280 (if (equal major-mode 'mh-folder-mode)
13281 mh-current-folder
13282 ;; Refer to the show buffer
13283 mh-show-folder-buffer))
13284 (end-index
13285 (if (boundp 'mh-index-folder)
13286 (min (length mh-index-folder) (length folder))))
13288 ;; a simple test on mh-index-data does not work, because
13289 ;; mh-index-data is always nil in a show buffer.
13290 (if (and (boundp 'mh-index-folder)
13291 (string= mh-index-folder (substring folder 0 end-index)))
13292 (if (equal major-mode 'mh-show-mode)
13293 (save-window-excursion
13294 (let (pop-up-frames)
13295 (when (buffer-live-p (get-buffer folder))
13296 (progn
13297 (pop-to-buffer folder)
13298 (org-mhe-get-message-folder-from-index)
13301 (org-mhe-get-message-folder-from-index)
13303 folder
13307 (defun org-mhe-get-message-folder-from-index ()
13308 "Returns the name of the message folder in a index folder buffer."
13309 (save-excursion
13310 (mh-index-previous-folder)
13311 (re-search-forward "^\\(+.*\\)$" nil t)
13312 (message "%s" (match-string 1))))
13314 (defun org-mhe-get-message-folder ()
13315 "Return the name of the current message folder. Be careful if you
13316 use sequences."
13317 (save-excursion
13318 (if (equal major-mode 'mh-folder-mode)
13319 mh-current-folder
13320 ;; Refer to the show buffer
13321 mh-show-folder-buffer)))
13323 (defun org-mhe-get-message-num ()
13324 "Return the number of the current message. Be careful if you
13325 use sequences."
13326 (save-excursion
13327 (if (equal major-mode 'mh-folder-mode)
13328 (mh-get-msg-num nil)
13329 ;; Refer to the show buffer
13330 (mh-show-buffer-message-number))))
13332 (defun org-mhe-get-header (header)
13333 "Return a header of the message in folder mode. This will create a
13334 show buffer for the corresponding message. If you have a more clever
13335 idea..."
13336 (let* ((folder (org-mhe-get-message-folder))
13337 (num (org-mhe-get-message-num))
13338 (buffer (get-buffer-create (concat "show-" folder)))
13339 (header-field))
13340 (with-current-buffer buffer
13341 (mh-display-msg num folder)
13342 (if (equal major-mode 'mh-folder-mode)
13343 (mh-header-display)
13344 (mh-show-header-display))
13345 (set-buffer buffer)
13346 (setq header-field (mh-get-header-field header))
13347 (if (equal major-mode 'mh-folder-mode)
13348 (mh-show)
13349 (mh-show-show))
13350 header-field)))
13352 (defun org-follow-mhe-link (folder article)
13353 "Follow an MHE link to FOLDER and ARTICLE.
13354 If ARTICLE is nil FOLDER is shown. If the configuration variable
13355 `org-mhe-search-all-folders' is t and `mh-searcher' is pick,
13356 ARTICLE is searched in all folders. Indexed searches (swish++,
13357 namazu, and others supported by MH-E) will always search in all
13358 folders."
13359 (require 'mh-e)
13360 (require 'mh-search)
13361 (require 'mh-utils)
13362 (mh-find-path)
13363 (if (not article)
13364 (mh-visit-folder (mh-normalize-folder-name folder))
13365 (setq article (org-add-angle-brackets article))
13366 (mh-search-choose)
13367 (if (equal mh-searcher 'pick)
13368 (progn
13369 (mh-search folder (list "--message-id" article))
13370 (when (and org-mhe-search-all-folders
13371 (not (org-mhe-get-message-real-folder)))
13372 (kill-this-buffer)
13373 (mh-search "+" (list "--message-id" article))))
13374 (mh-search "+" article))
13375 (if (org-mhe-get-message-real-folder)
13376 (mh-show-msg 1)
13377 (kill-this-buffer)
13378 (error "Message not found"))))
13380 ;;; BibTeX links
13382 ;; Use the custom search meachnism to construct and use search strings for
13383 ;; file links to BibTeX database entries.
13385 (defun org-create-file-search-in-bibtex ()
13386 "Create the search string and description for a BibTeX database entry."
13387 (when (eq major-mode 'bibtex-mode)
13388 ;; yes, we want to construct this search string.
13389 ;; Make a good description for this entry, using names, year and the title
13390 ;; Put it into the `description' variable which is dynamically scoped.
13391 (let ((bibtex-autokey-names 1)
13392 (bibtex-autokey-names-stretch 1)
13393 (bibtex-autokey-name-case-convert-function 'identity)
13394 (bibtex-autokey-name-separator " & ")
13395 (bibtex-autokey-additional-names " et al.")
13396 (bibtex-autokey-year-length 4)
13397 (bibtex-autokey-name-year-separator " ")
13398 (bibtex-autokey-titlewords 3)
13399 (bibtex-autokey-titleword-separator " ")
13400 (bibtex-autokey-titleword-case-convert-function 'identity)
13401 (bibtex-autokey-titleword-length 'infty)
13402 (bibtex-autokey-year-title-separator ": "))
13403 (setq description (bibtex-generate-autokey)))
13404 ;; Now parse the entry, get the key and return it.
13405 (save-excursion
13406 (bibtex-beginning-of-entry)
13407 (cdr (assoc "=key=" (bibtex-parse-entry))))))
13409 (defun org-execute-file-search-in-bibtex (s)
13410 "Find the link search string S as a key for a database entry."
13411 (when (eq major-mode 'bibtex-mode)
13412 ;; Yes, we want to do the search in this file.
13413 ;; We construct a regexp that searches for "@entrytype{" followed by the key
13414 (goto-char (point-min))
13415 (and (re-search-forward (concat "@[a-zA-Z]+[ \t\n]*{[ \t\n]*"
13416 (regexp-quote s) "[ \t\n]*,") nil t)
13417 (goto-char (match-beginning 0)))
13418 (if (and (match-beginning 0) (equal current-prefix-arg '(16)))
13419 ;; Use double prefix to indicate that any web link should be browsed
13420 (let ((b (current-buffer)) (p (point)))
13421 ;; Restore the window configuration because we just use the web link
13422 (set-window-configuration org-window-config-before-follow-link)
13423 (save-excursion (set-buffer b) (goto-char p)
13424 (bibtex-url)))
13425 (recenter 0)) ; Move entry start to beginning of window
13426 ;; return t to indicate that the search is done.
13429 ;; Finally add the functions to the right hooks.
13430 (add-hook 'org-create-file-search-functions 'org-create-file-search-in-bibtex)
13431 (add-hook 'org-execute-file-search-functions 'org-execute-file-search-in-bibtex)
13433 ;; end of Bibtex link setup
13435 ;;; Following file links
13437 (defun org-open-file (path &optional in-emacs line search)
13438 "Open the file at PATH.
13439 First, this expands any special file name abbreviations. Then the
13440 configuration variable `org-file-apps' is checked if it contains an
13441 entry for this file type, and if yes, the corresponding command is launched.
13442 If no application is found, Emacs simply visits the file.
13443 With optional argument IN-EMACS, Emacs will visit the file.
13444 Optional LINE specifies a line to go to, optional SEARCH a string to
13445 search for. If LINE or SEARCH is given, the file will always be
13446 opened in Emacs.
13447 If the file does not exist, an error is thrown."
13448 (setq in-emacs (or in-emacs line search))
13449 (let* ((file (if (equal path "")
13450 buffer-file-name
13451 (substitute-in-file-name (expand-file-name path))))
13452 (apps (append org-file-apps (org-default-apps)))
13453 (remp (and (assq 'remote apps) (org-file-remote-p file)))
13454 (dirp (if remp nil (file-directory-p file)))
13455 (dfile (downcase file))
13456 (old-buffer (current-buffer))
13457 (old-pos (point))
13458 (old-mode major-mode)
13459 ext cmd)
13460 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
13461 (setq ext (match-string 1 dfile))
13462 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
13463 (setq ext (match-string 1 dfile))))
13464 (if in-emacs
13465 (setq cmd 'emacs)
13466 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
13467 (and dirp (cdr (assoc 'directory apps)))
13468 (cdr (assoc ext apps))
13469 (cdr (assoc t apps)))))
13470 (when (eq cmd 'mailcap)
13471 (require 'mailcap)
13472 (mailcap-parse-mailcaps)
13473 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
13474 (command (mailcap-mime-info mime-type)))
13475 (if (stringp command)
13476 (setq cmd command)
13477 (setq cmd 'emacs))))
13478 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
13479 (not (file-exists-p file))
13480 (not org-open-non-existing-files))
13481 (error "No such file: %s" file))
13482 (cond
13483 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
13484 ;; Remove quotes around the file name - we'll use shell-quote-argument.
13485 (while (string-match "['\"]%s['\"]" cmd)
13486 (setq cmd (replace-match "%s" t t cmd)))
13487 (while (string-match "%s" cmd)
13488 (setq cmd (replace-match
13489 (save-match-data (shell-quote-argument file))
13490 t t cmd)))
13491 (save-window-excursion
13492 (start-process-shell-command cmd nil cmd)))
13493 ((or (stringp cmd)
13494 (eq cmd 'emacs))
13495 (funcall (cdr (assq 'file org-link-frame-setup)) file)
13496 (widen)
13497 (if line (goto-line line)
13498 (if search (org-link-search search))))
13499 ((consp cmd)
13500 (eval cmd))
13501 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
13502 (and (org-mode-p) (eq old-mode 'org-mode)
13503 (or (not (equal old-buffer (current-buffer)))
13504 (not (equal old-pos (point))))
13505 (org-mark-ring-push old-pos old-buffer))))
13507 (defun org-default-apps ()
13508 "Return the default applications for this operating system."
13509 (cond
13510 ((eq system-type 'darwin)
13511 org-file-apps-defaults-macosx)
13512 ((eq system-type 'windows-nt)
13513 org-file-apps-defaults-windowsnt)
13514 (t org-file-apps-defaults-gnu)))
13516 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
13517 (defun org-file-remote-p (file)
13518 "Test whether FILE specifies a location on a remote system.
13519 Return non-nil if the location is indeed remote.
13521 For example, the filename \"/user@host:/foo\" specifies a location
13522 on the system \"/user@host:\"."
13523 (cond ((fboundp 'file-remote-p)
13524 (file-remote-p file))
13525 ((fboundp 'tramp-handle-file-remote-p)
13526 (tramp-handle-file-remote-p file))
13527 ((and (boundp 'ange-ftp-name-format)
13528 (string-match (car ange-ftp-name-format) file))
13530 (t nil)))
13533 ;;;; Hooks for remember.el, and refiling
13535 (defvar annotation) ; from remember.el, dynamically scoped in `remember-mode'
13536 (defvar initial) ; from remember.el, dynamically scoped in `remember-mode'
13538 ;;;###autoload
13539 (defun org-remember-insinuate ()
13540 "Setup remember.el for use wiht Org-mode."
13541 (require 'remember)
13542 (setq remember-annotation-functions '(org-remember-annotation))
13543 (setq remember-handler-functions '(org-remember-handler))
13544 (add-hook 'remember-mode-hook 'org-remember-apply-template))
13546 ;;;###autoload
13547 (defun org-remember-annotation ()
13548 "Return a link to the current location as an annotation for remember.el.
13549 If you are using Org-mode files as target for data storage with
13550 remember.el, then the annotations should include a link compatible with the
13551 conventions in Org-mode. This function returns such a link."
13552 (org-store-link nil))
13554 (defconst org-remember-help
13555 "Select a destination location for the note.
13556 UP/DOWN=headline TAB=cycle visibility [Q]uit RET/<left>/<right>=Store
13557 RET on headline -> Store as sublevel entry to current headline
13558 RET at beg-of-buf -> Append to file as level 2 headline
13559 <left>/<right> -> before/after current headline, same headings level")
13561 (defvar org-remember-previous-location nil)
13562 (defvar org-force-remember-template-char) ;; dynamically scoped
13564 (defun org-select-remember-template (&optional use-char)
13565 (when org-remember-templates
13566 (let* ((templates (mapcar (lambda (x)
13567 (if (stringp (car x))
13568 (append (list (nth 1 x) (car x)) (cddr x))
13569 (append (list (car x) "") (cdr x))))
13570 org-remember-templates))
13571 (char (or use-char
13572 (cond
13573 ((= (length templates) 1)
13574 (caar templates))
13575 ((and (boundp 'org-force-remember-template-char)
13576 org-force-remember-template-char)
13577 (if (stringp org-force-remember-template-char)
13578 (string-to-char org-force-remember-template-char)
13579 org-force-remember-template-char))
13581 (message "Select template: %s"
13582 (mapconcat
13583 (lambda (x)
13584 (cond
13585 ((not (string-match "\\S-" (nth 1 x)))
13586 (format "[%c]" (car x)))
13587 ((equal (downcase (car x))
13588 (downcase (aref (nth 1 x) 0)))
13589 (format "[%c]%s" (car x)
13590 (substring (nth 1 x) 1)))
13591 (t (format "[%c]%s" (car x) (nth 1 x)))))
13592 templates " "))
13593 (let ((inhibit-quit t) (char0 (read-char-exclusive)))
13594 (when (equal char0 ?\C-g)
13595 (jump-to-register remember-register)
13596 (kill-buffer remember-buffer))
13597 char0))))))
13598 (cddr (assoc char templates)))))
13600 (defvar x-last-selected-text)
13601 (defvar x-last-selected-text-primary)
13603 ;;;###autoload
13604 (defun org-remember-apply-template (&optional use-char skip-interactive)
13605 "Initialize *remember* buffer with template, invoke `org-mode'.
13606 This function should be placed into `remember-mode-hook' and in fact requires
13607 to be run from that hook to function properly."
13608 (if org-remember-templates
13609 (let* ((entry (org-select-remember-template use-char))
13610 (tpl (car entry))
13611 (plist-p (if org-store-link-plist t nil))
13612 (file (if (and (nth 1 entry) (stringp (nth 1 entry))
13613 (string-match "\\S-" (nth 1 entry)))
13614 (nth 1 entry)
13615 org-default-notes-file))
13616 (headline (nth 2 entry))
13617 (v-c (or (and (eq window-system 'x)
13618 (fboundp 'x-cut-buffer-or-selection-value)
13619 (x-cut-buffer-or-selection-value))
13620 (org-bound-and-true-p x-last-selected-text)
13621 (org-bound-and-true-p x-last-selected-text-primary)
13622 (and (> (length kill-ring) 0) (current-kill 0))))
13623 (v-t (format-time-string (car org-time-stamp-formats) (org-current-time)))
13624 (v-T (format-time-string (cdr org-time-stamp-formats) (org-current-time)))
13625 (v-u (concat "[" (substring v-t 1 -1) "]"))
13626 (v-U (concat "[" (substring v-T 1 -1) "]"))
13627 ;; `initial' and `annotation' are bound in `remember'
13628 (v-i (if (boundp 'initial) initial))
13629 (v-a (if (and (boundp 'annotation) annotation)
13630 (if (equal annotation "[[]]") "" annotation)
13631 ""))
13632 (v-A (if (and v-a
13633 (string-match "\\[\\(\\[.*?\\]\\)\\(\\[.*?\\]\\)?\\]" v-a))
13634 (replace-match "[\\1[%^{Link description}]]" nil nil v-a)
13635 v-a))
13636 (v-n user-full-name)
13637 (org-startup-folded nil)
13638 org-time-was-given org-end-time-was-given x
13639 prompt completions char time pos default histvar)
13640 (setq org-store-link-plist
13641 (append (list :annotation v-a :initial v-i)
13642 org-store-link-plist))
13643 (unless tpl (setq tpl "") (message "No template") (ding) (sit-for 1))
13644 (erase-buffer)
13645 (insert (substitute-command-keys
13646 (format
13647 "## Filing location: Select interactively, default, or last used:
13648 ## %s to select file and header location interactively.
13649 ## %s \"%s\" -> \"* %s\"
13650 ## C-u C-u C-c C-c \"%s\" -> \"* %s\"
13651 ## To switch templates, use `\\[org-remember]'. To abort use `C-c C-k'.\n\n"
13652 (if org-remember-store-without-prompt " C-u C-c C-c" " C-c C-c")
13653 (if org-remember-store-without-prompt " C-c C-c" " C-u C-c C-c")
13654 (abbreviate-file-name (or file org-default-notes-file))
13655 (or headline "")
13656 (or (car org-remember-previous-location) "???")
13657 (or (cdr org-remember-previous-location) "???"))))
13658 (insert tpl) (goto-char (point-min))
13659 ;; Simple %-escapes
13660 (while (re-search-forward "%\\([tTuUaiAc]\\)" nil t)
13661 (when (and initial (equal (match-string 0) "%i"))
13662 (save-match-data
13663 (let* ((lead (buffer-substring
13664 (point-at-bol) (match-beginning 0))))
13665 (setq v-i (mapconcat 'identity
13666 (org-split-string initial "\n")
13667 (concat "\n" lead))))))
13668 (replace-match
13669 (or (eval (intern (concat "v-" (match-string 1)))) "")
13670 t t))
13672 ;; %[] Insert contents of a file.
13673 (goto-char (point-min))
13674 (while (re-search-forward "%\\[\\(.+\\)\\]" nil t)
13675 (let ((start (match-beginning 0))
13676 (end (match-end 0))
13677 (filename (expand-file-name (match-string 1))))
13678 (goto-char start)
13679 (delete-region start end)
13680 (condition-case error
13681 (insert-file-contents filename)
13682 (error (insert (format "%%![Couldn't insert %s: %s]"
13683 filename error))))))
13684 ;; %() embedded elisp
13685 (goto-char (point-min))
13686 (while (re-search-forward "%\\((.+)\\)" nil t)
13687 (goto-char (match-beginning 0))
13688 (let ((template-start (point)))
13689 (forward-char 1)
13690 (let ((result
13691 (condition-case error
13692 (eval (read (current-buffer)))
13693 (error (format "%%![Error: %s]" error)))))
13694 (delete-region template-start (point))
13695 (insert result))))
13697 ;; From the property list
13698 (when plist-p
13699 (goto-char (point-min))
13700 (while (re-search-forward "%\\(:[-a-zA-Z]+\\)" nil t)
13701 (and (setq x (or (plist-get org-store-link-plist
13702 (intern (match-string 1))) ""))
13703 (replace-match x t t))))
13705 ;; Turn on org-mode in the remember buffer, set local variables
13706 (org-mode)
13707 (org-set-local 'org-finish-function 'org-remember-finalize)
13708 (if (and file (string-match "\\S-" file) (not (file-directory-p file)))
13709 (org-set-local 'org-default-notes-file file))
13710 (if (and headline (stringp headline) (string-match "\\S-" headline))
13711 (org-set-local 'org-remember-default-headline headline))
13712 ;; Interactive template entries
13713 (goto-char (point-min))
13714 (while (re-search-forward "%^\\({\\([^}]*\\)}\\)?\\([gGuUtT]\\)?" nil t)
13715 (setq char (if (match-end 3) (match-string 3))
13716 prompt (if (match-end 2) (match-string 2)))
13717 (goto-char (match-beginning 0))
13718 (replace-match "")
13719 (setq completions nil default nil)
13720 (when prompt
13721 (setq completions (org-split-string prompt "|")
13722 prompt (pop completions)
13723 default (car completions)
13724 histvar (intern (concat
13725 "org-remember-template-prompt-history::"
13726 (or prompt "")))
13727 completions (mapcar 'list completions)))
13728 (cond
13729 ((member char '("G" "g"))
13730 (let* ((org-last-tags-completion-table
13731 (org-global-tags-completion-table
13732 (if (equal char "G") (org-agenda-files) (and file (list file)))))
13733 (org-add-colon-after-tag-completion t)
13734 (ins (completing-read
13735 (if prompt (concat prompt ": ") "Tags: ")
13736 'org-tags-completion-function nil nil nil
13737 'org-tags-history)))
13738 (setq ins (mapconcat 'identity
13739 (org-split-string ins (org-re "[^[:alnum:]_@]+"))
13740 ":"))
13741 (when (string-match "\\S-" ins)
13742 (or (equal (char-before) ?:) (insert ":"))
13743 (insert ins)
13744 (or (equal (char-after) ?:) (insert ":")))))
13745 (char
13746 (setq org-time-was-given (equal (upcase char) char))
13747 (setq time (org-read-date (equal (upcase char) "U") t nil
13748 prompt))
13749 (org-insert-time-stamp time org-time-was-given
13750 (member char '("u" "U"))
13751 nil nil (list org-end-time-was-given)))
13753 (insert (org-completing-read
13754 (concat (if prompt prompt "Enter string")
13755 (if default (concat " [" default "]"))
13756 ": ")
13757 completions nil nil nil histvar default)))))
13758 (goto-char (point-min))
13759 (if (re-search-forward "%\\?" nil t)
13760 (replace-match "")
13761 (and (re-search-forward "^[^#\n]" nil t) (backward-char 1))))
13762 (org-mode)
13763 (org-set-local 'org-finish-function 'org-remember-finalize))
13764 (when (save-excursion
13765 (goto-char (point-min))
13766 (re-search-forward "%!" nil t))
13767 (replace-match "")
13768 (add-hook 'post-command-hook 'org-remember-finish-immediately 'append)))
13770 (defun org-remember-finish-immediately ()
13771 "File remember note immediately.
13772 This should be run in `post-command-hook' and will remove itself
13773 from that hook."
13774 (remove-hook 'post-command-hook 'org-remember-finish-immediately)
13775 (when org-finish-function
13776 (funcall org-finish-function)))
13778 (defvar org-clock-marker) ; Defined below
13779 (defun org-remember-finalize ()
13780 "Finalize the remember process."
13781 (unless (fboundp 'remember-finalize)
13782 (defalias 'remember-finalize 'remember-buffer))
13783 (when (and org-clock-marker
13784 (equal (marker-buffer org-clock-marker) (current-buffer)))
13785 ;; FIXME: test this, this is w/o notetaking!
13786 (let (org-log-note-clock-out) (org-clock-out)))
13787 (when buffer-file-name
13788 (save-buffer)
13789 (setq buffer-file-name nil))
13790 (remember-finalize))
13792 ;;;###autoload
13793 (defun org-remember (&optional goto org-force-remember-template-char)
13794 "Call `remember'. If this is already a remember buffer, re-apply template.
13795 If there is an active region, make sure remember uses it as initial content
13796 of the remember buffer.
13798 When called interactively with a `C-u' prefix argument GOTO, don't remember
13799 anything, just go to the file/headline where the selected template usually
13800 stores its notes. With a double prefix arg `C-u C-u', go to the last
13801 note stored by remember.
13803 Lisp programs can set ORG-FORCE-REMEMBER-TEMPLATE-CHAR to a character
13804 associated with a template in `org-remember-templates'."
13805 (interactive "P")
13806 (cond
13807 ((equal goto '(4)) (org-go-to-remember-target))
13808 ((equal goto '(16)) (org-remember-goto-last-stored))
13810 (if (memq org-finish-function '(remember-buffer remember-finalize))
13811 (progn
13812 (when (< (length org-remember-templates) 2)
13813 (error "No other template available"))
13814 (erase-buffer)
13815 (let ((annotation (plist-get org-store-link-plist :annotation))
13816 (initial (plist-get org-store-link-plist :initial)))
13817 (org-remember-apply-template))
13818 (message "Press C-c C-c to remember data"))
13819 (if (org-region-active-p)
13820 (remember (buffer-substring (point) (mark)))
13821 (call-interactively 'remember))))))
13823 (defun org-remember-goto-last-stored ()
13824 "Go to the location where the last remember note was stored."
13825 (interactive)
13826 (bookmark-jump "org-remember-last-stored")
13827 (message "This is the last note stored by remember"))
13829 (defun org-go-to-remember-target (&optional template-key)
13830 "Go to the target location of a remember template.
13831 The user is queried for the template."
13832 (interactive)
13833 (let* ((entry (org-select-remember-template template-key))
13834 (file (nth 1 entry))
13835 (heading (nth 2 entry))
13836 visiting)
13837 (unless (and file (stringp file) (string-match "\\S-" file))
13838 (setq file org-default-notes-file))
13839 (unless (and heading (stringp heading) (string-match "\\S-" heading))
13840 (setq heading org-remember-default-headline))
13841 (setq visiting (org-find-base-buffer-visiting file))
13842 (if (not visiting) (find-file-noselect file))
13843 (switch-to-buffer (or visiting (get-file-buffer file)))
13844 (widen)
13845 (goto-char (point-min))
13846 (if (re-search-forward
13847 (concat "^\\*+[ \t]+" (regexp-quote heading)
13848 (org-re "\\([ \t]+:[[:alnum:]@_:]*\\)?[ \t]*$"))
13849 nil t)
13850 (goto-char (match-beginning 0))
13851 (error "Target headline not found: %s" heading))))
13853 (defvar org-note-abort nil) ; dynamically scoped
13855 ;;;###autoload
13856 (defun org-remember-handler ()
13857 "Store stuff from remember.el into an org file.
13858 First prompts for an org file. If the user just presses return, the value
13859 of `org-default-notes-file' is used.
13860 Then the command offers the headings tree of the selected file in order to
13861 file the text at a specific location.
13862 You can either immediately press RET to get the note appended to the
13863 file, or you can use vertical cursor motion and visibility cycling (TAB) to
13864 find a better place. Then press RET or <left> or <right> in insert the note.
13866 Key Cursor position Note gets inserted
13867 -----------------------------------------------------------------------------
13868 RET buffer-start as level 1 heading at end of file
13869 RET on headline as sublevel of the heading at cursor
13870 RET no heading at cursor position, level taken from context.
13871 Or use prefix arg to specify level manually.
13872 <left> on headline as same level, before current heading
13873 <right> on headline as same level, after current heading
13875 So the fastest way to store the note is to press RET RET to append it to
13876 the default file. This way your current train of thought is not
13877 interrupted, in accordance with the principles of remember.el.
13878 You can also get the fast execution without prompting by using
13879 C-u C-c C-c to exit the remember buffer. See also the variable
13880 `org-remember-store-without-prompt'.
13882 Before being stored away, the function ensures that the text has a
13883 headline, i.e. a first line that starts with a \"*\". If not, a headline
13884 is constructed from the current date and some additional data.
13886 If the variable `org-adapt-indentation' is non-nil, the entire text is
13887 also indented so that it starts in the same column as the headline
13888 \(i.e. after the stars).
13890 See also the variable `org-reverse-note-order'."
13891 (goto-char (point-min))
13892 (while (looking-at "^[ \t]*\n\\|^##.*\n")
13893 (replace-match ""))
13894 (goto-char (point-max))
13895 (beginning-of-line 1)
13896 (while (looking-at "[ \t]*$\\|##.*")
13897 (delete-region (1- (point)) (point-max))
13898 (beginning-of-line 1))
13899 (catch 'quit
13900 (if org-note-abort (throw 'quit nil))
13901 (let* ((txt (buffer-substring (point-min) (point-max)))
13902 (fastp (org-xor (equal current-prefix-arg '(4))
13903 org-remember-store-without-prompt))
13904 (file (cond
13905 (fastp org-default-notes-file)
13906 ((and (eq org-remember-interactive-interface 'refile)
13907 org-refile-targets)
13908 org-default-notes-file)
13909 ((not (and (equal current-prefix-arg '(16))
13910 org-remember-previous-location))
13911 (org-get-org-file))))
13912 (heading org-remember-default-headline)
13913 (visiting (and file (org-find-base-buffer-visiting file)))
13914 (org-startup-folded nil)
13915 (org-startup-align-all-tables nil)
13916 (org-goto-start-pos 1)
13917 spos exitcmd level indent reversed)
13918 (if (and (equal current-prefix-arg '(16)) org-remember-previous-location)
13919 (setq file (car org-remember-previous-location)
13920 heading (cdr org-remember-previous-location)
13921 fastp t))
13922 (setq current-prefix-arg nil)
13923 (if (string-match "[ \t\n]+\\'" txt)
13924 (setq txt (replace-match "" t t txt)))
13925 ;; Modify text so that it becomes a nice subtree which can be inserted
13926 ;; into an org tree.
13927 (let* ((lines (split-string txt "\n"))
13928 first)
13929 (setq first (car lines) lines (cdr lines))
13930 (if (string-match "^\\*+ " first)
13931 ;; Is already a headline
13932 (setq indent nil)
13933 ;; We need to add a headline: Use time and first buffer line
13934 (setq lines (cons first lines)
13935 first (concat "* " (current-time-string)
13936 " (" (remember-buffer-desc) ")")
13937 indent " "))
13938 (if (and org-adapt-indentation indent)
13939 (setq lines (mapcar
13940 (lambda (x)
13941 (if (string-match "\\S-" x)
13942 (concat indent x) x))
13943 lines)))
13944 (setq txt (concat first "\n"
13945 (mapconcat 'identity lines "\n"))))
13946 (if (string-match "\n[ \t]*\n[ \t\n]*\\'" txt)
13947 (setq txt (replace-match "\n\n" t t txt))
13948 (if (string-match "[ \t\n]*\\'" txt)
13949 (setq txt (replace-match "\n" t t txt))))
13950 ;; Put the modified text back into the remember buffer, for refile.
13951 (erase-buffer)
13952 (insert txt)
13953 (goto-char (point-min))
13954 (when (and (eq org-remember-interactive-interface 'refile)
13955 (not fastp))
13956 (org-refile nil (or visiting (find-file-noselect file)))
13957 (throw 'quit t))
13958 ;; Find the file
13959 (if (not visiting) (find-file-noselect file))
13960 (with-current-buffer (or visiting (get-file-buffer file))
13961 (unless (org-mode-p)
13962 (error "Target files for remember notes must be in Org-mode"))
13963 (save-excursion
13964 (save-restriction
13965 (widen)
13966 (and (goto-char (point-min))
13967 (not (re-search-forward "^\\* " nil t))
13968 (insert "\n* " (or heading "Notes") "\n"))
13969 (setq reversed (org-notes-order-reversed-p))
13971 ;; Find the default location
13972 (when (and heading (stringp heading) (string-match "\\S-" heading))
13973 (goto-char (point-min))
13974 (if (re-search-forward
13975 (concat "^\\*+[ \t]+" (regexp-quote heading)
13976 (org-re "\\([ \t]+:[[:alnum:]@_:]*\\)?[ \t]*$"))
13977 nil t)
13978 (setq org-goto-start-pos (match-beginning 0))
13979 (when fastp
13980 (goto-char (point-max))
13981 (unless (bolp) (newline))
13982 (insert "* " heading "\n")
13983 (setq org-goto-start-pos (point-at-bol 0)))))
13985 ;; Ask the User for a location, using the appropriate interface
13986 (cond
13987 (fastp (setq spos org-goto-start-pos
13988 exitcmd 'return))
13989 ((eq org-remember-interactive-interface 'outline)
13990 (setq spos (org-get-location (current-buffer)
13991 org-remember-help)
13992 exitcmd (cdr spos)
13993 spos (car spos)))
13994 ((eq org-remember-interactive-interface 'outline-path-completion)
13995 (let ((org-refile-targets '((nil . (:maxlevel . 10))))
13996 (org-refile-use-outline-path t))
13997 (setq spos (org-refile-get-location "Heading: ")
13998 exitcmd 'return
13999 spos (nth 3 spos))))
14000 (t (error "this should not hapen")))
14001 (if (not spos) (throw 'quit nil)) ; return nil to show we did
14002 ; not handle this note
14003 (goto-char spos)
14004 (cond ((org-on-heading-p t)
14005 (org-back-to-heading t)
14006 (setq level (funcall outline-level))
14007 (cond
14008 ((eq exitcmd 'return)
14009 ;; sublevel of current
14010 (setq org-remember-previous-location
14011 (cons (abbreviate-file-name file)
14012 (org-get-heading 'notags)))
14013 (if reversed
14014 (outline-next-heading)
14015 (org-end-of-subtree t)
14016 (if (not (bolp))
14017 (if (looking-at "[ \t]*\n")
14018 (beginning-of-line 2)
14019 (end-of-line 1)
14020 (insert "\n"))))
14021 (bookmark-set "org-remember-last-stored")
14022 (org-paste-subtree (org-get-legal-level level 1) txt))
14023 ((eq exitcmd 'left)
14024 ;; before current
14025 (bookmark-set "org-remember-last-stored")
14026 (org-paste-subtree level txt))
14027 ((eq exitcmd 'right)
14028 ;; after current
14029 (org-end-of-subtree t)
14030 (bookmark-set "org-remember-last-stored")
14031 (org-paste-subtree level txt))
14032 (t (error "This should not happen"))))
14034 ((and (bobp) (not reversed))
14035 ;; Put it at the end, one level below level 1
14036 (save-restriction
14037 (widen)
14038 (goto-char (point-max))
14039 (if (not (bolp)) (newline))
14040 (bookmark-set "org-remember-last-stored")
14041 (org-paste-subtree (org-get-legal-level 1 1) txt)))
14043 ((and (bobp) reversed)
14044 ;; Put it at the start, as level 1
14045 (save-restriction
14046 (widen)
14047 (goto-char (point-min))
14048 (re-search-forward "^\\*+ " nil t)
14049 (beginning-of-line 1)
14050 (bookmark-set "org-remember-last-stored")
14051 (org-paste-subtree 1 txt)))
14053 ;; Put it right there, with automatic level determined by
14054 ;; org-paste-subtree or from prefix arg
14055 (bookmark-set "org-remember-last-stored")
14056 (org-paste-subtree
14057 (if (numberp current-prefix-arg) current-prefix-arg)
14058 txt)))
14059 (when remember-save-after-remembering
14060 (save-buffer)
14061 (if (not visiting) (kill-buffer (current-buffer)))))))))
14063 t) ;; return t to indicate that we took care of this note.
14065 (defun org-get-org-file ()
14066 "Read a filename, with default directory `org-directory'."
14067 (let ((default (or org-default-notes-file remember-data-file)))
14068 (read-file-name (format "File name [%s]: " default)
14069 (file-name-as-directory org-directory)
14070 default)))
14072 (defun org-notes-order-reversed-p ()
14073 "Check if the current file should receive notes in reversed order."
14074 (cond
14075 ((not org-reverse-note-order) nil)
14076 ((eq t org-reverse-note-order) t)
14077 ((not (listp org-reverse-note-order)) nil)
14078 (t (catch 'exit
14079 (let ((all org-reverse-note-order)
14080 entry)
14081 (while (setq entry (pop all))
14082 (if (string-match (car entry) buffer-file-name)
14083 (throw 'exit (cdr entry))))
14084 nil)))))
14086 ;;; Refiling
14088 (defvar org-refile-target-table nil
14089 "The list of refile targets, created by `org-refile'.")
14091 (defvar org-agenda-new-buffers nil
14092 "Buffers created to visit agenda files.")
14094 (defun org-get-refile-targets (&optional default-buffer)
14095 "Produce a table with refile targets."
14096 (let ((entries (or org-refile-targets '((nil . (:level . 1)))))
14097 targets txt re files f desc descre)
14098 (with-current-buffer (or default-buffer (current-buffer))
14099 (while (setq entry (pop entries))
14100 (setq files (car entry) desc (cdr entry))
14101 (cond
14102 ((null files) (setq files (list (current-buffer))))
14103 ((eq files 'org-agenda-files)
14104 (setq files (org-agenda-files 'unrestricted)))
14105 ((and (symbolp files) (fboundp files))
14106 (setq files (funcall files)))
14107 ((and (symbolp files) (boundp files))
14108 (setq files (symbol-value files))))
14109 (if (stringp files) (setq files (list files)))
14110 (cond
14111 ((eq (car desc) :tag)
14112 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
14113 ((eq (car desc) :todo)
14114 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
14115 ((eq (car desc) :regexp)
14116 (setq descre (cdr desc)))
14117 ((eq (car desc) :level)
14118 (setq descre (concat "^\\*\\{" (number-to-string
14119 (if org-odd-levels-only
14120 (1- (* 2 (cdr desc)))
14121 (cdr desc)))
14122 "\\}[ \t]")))
14123 ((eq (car desc) :maxlevel)
14124 (setq descre (concat "^\\*\\{1," (number-to-string
14125 (if org-odd-levels-only
14126 (1- (* 2 (cdr desc)))
14127 (cdr desc)))
14128 "\\}[ \t]")))
14129 (t (error "Bad refiling target description %s" desc)))
14130 (while (setq f (pop files))
14131 (save-excursion
14132 (set-buffer (if (bufferp f) f (org-get-agenda-file-buffer f)))
14133 (if (bufferp f) (setq f (buffer-file-name (buffer-base-buffer f))))
14134 (save-excursion
14135 (save-restriction
14136 (widen)
14137 (goto-char (point-min))
14138 (while (re-search-forward descre nil t)
14139 (goto-char (point-at-bol))
14140 (when (looking-at org-complex-heading-regexp)
14141 (setq txt (match-string 4)
14142 re (concat "^" (regexp-quote
14143 (buffer-substring (match-beginning 1)
14144 (match-end 4)))))
14145 (if (match-end 5) (setq re (concat re "[ \t]+"
14146 (regexp-quote
14147 (match-string 5)))))
14148 (setq re (concat re "[ \t]*$"))
14149 (when org-refile-use-outline-path
14150 (setq txt (mapconcat 'identity
14151 (append
14152 (if (eq org-refile-use-outline-path 'file)
14153 (list (file-name-nondirectory
14154 (buffer-file-name (buffer-base-buffer))))
14155 (if (eq org-refile-use-outline-path 'full-file-path)
14156 (list (buffer-file-name (buffer-base-buffer)))))
14157 (org-get-outline-path)
14158 (list txt))
14159 "/")))
14160 (push (list txt f re (point)) targets))
14161 (goto-char (point-at-eol))))))))
14162 (nreverse targets))))
14164 (defun org-get-outline-path ()
14165 "Return the outline path to the current entry, as a list."
14166 (let (rtn)
14167 (save-excursion
14168 (while (org-up-heading-safe)
14169 (when (looking-at org-complex-heading-regexp)
14170 (push (org-match-string-no-properties 4) rtn)))
14171 rtn)))
14173 (defvar org-refile-history nil
14174 "History for refiling operations.")
14176 (defun org-refile (&optional goto default-buffer)
14177 "Move the entry at point to another heading.
14178 The list of target headings is compiled using the information in
14179 `org-refile-targets', which see. This list is created upon first use, and
14180 you can update it by calling this command with a double prefix (`C-u C-u').
14181 FIXME: Can we find a better way of updating?
14183 At the target location, the entry is filed as a subitem of the target heading.
14184 Depending on `org-reverse-note-order', the new subitem will either be the
14185 first of the last subitem.
14187 With prefix arg GOTO, the command will only visit the target location,
14188 not actually move anything.
14189 With a double prefix `C-c C-c', go to the location where the last refiling
14190 operation has put the subtree.
14192 With a double prefix argument, the command can be used to jump to any
14193 heading in the current buffer."
14194 (interactive "P")
14195 (let* ((cbuf (current-buffer))
14196 (filename (buffer-file-name (buffer-base-buffer cbuf)))
14197 pos it nbuf file re level reversed)
14198 (if (equal goto '(16))
14199 (org-refile-goto-last-stored)
14200 (when (setq it (org-refile-get-location
14201 (if goto "Goto: " "Refile to: ") default-buffer))
14202 (setq file (nth 1 it)
14203 re (nth 2 it)
14204 pos (nth 3 it))
14205 (setq nbuf (or (find-buffer-visiting file)
14206 (find-file-noselect file)))
14207 (if goto
14208 (progn
14209 (switch-to-buffer nbuf)
14210 (goto-char pos)
14211 (org-show-context 'org-goto))
14212 (org-copy-special)
14213 (save-excursion
14214 (set-buffer (setq nbuf (or (find-buffer-visiting file)
14215 (find-file-noselect file))))
14216 (setq reversed (org-notes-order-reversed-p))
14217 (save-excursion
14218 (save-restriction
14219 (widen)
14220 (goto-char pos)
14221 (looking-at outline-regexp)
14222 (setq level (org-get-legal-level (funcall outline-level) 1))
14223 (goto-char
14224 (if reversed
14225 (outline-next-heading)
14226 (or (save-excursion (outline-get-next-sibling))
14227 (org-end-of-subtree t t)
14228 (point-max))))
14229 (bookmark-set "org-refile-last-stored")
14230 (org-paste-subtree level))))
14231 (org-cut-special)
14232 (message "Entry refiled to \"%s\"" (car it)))))))
14234 (defun org-refile-goto-last-stored ()
14235 "Go to the location where the last refile was stored."
14236 (interactive)
14237 (bookmark-jump "org-refile-last-stored")
14238 (message "This is the location of the last refile"))
14240 (defun org-refile-get-location (&optional prompt default-buffer)
14241 "Prompt the user for a refile location, using PROMPT."
14242 (let ((org-refile-targets org-refile-targets)
14243 (org-refile-use-outline-path org-refile-use-outline-path))
14244 (setq org-refile-target-table (org-get-refile-targets default-buffer)))
14245 (unless org-refile-target-table
14246 (error "No refile targets"))
14247 (let* ((cbuf (current-buffer))
14248 (filename (buffer-file-name (buffer-base-buffer cbuf)))
14249 (fname (and filename (file-truename filename)))
14250 (tbl (mapcar
14251 (lambda (x)
14252 (if (not (equal fname (file-truename (nth 1 x))))
14253 (cons (concat (car x) " (" (file-name-nondirectory
14254 (nth 1 x)) ")")
14255 (cdr x))
14257 org-refile-target-table))
14258 (completion-ignore-case t))
14259 (assoc (completing-read prompt tbl nil t nil 'org-refile-history)
14260 tbl)))
14262 ;;;; Dynamic blocks
14264 (defun org-find-dblock (name)
14265 "Find the first dynamic block with name NAME in the buffer.
14266 If not found, stay at current position and return nil."
14267 (let (pos)
14268 (save-excursion
14269 (goto-char (point-min))
14270 (setq pos (and (re-search-forward (concat "^#\\+BEGIN:[ \t]+" name "\\>")
14271 nil t)
14272 (match-beginning 0))))
14273 (if pos (goto-char pos))
14274 pos))
14276 (defconst org-dblock-start-re
14277 "^#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
14278 "Matches the startline of a dynamic block, with parameters.")
14280 (defconst org-dblock-end-re "^#\\+END\\([: \t\r\n]\\|$\\)"
14281 "Matches the end of a dyhamic block.")
14283 (defun org-create-dblock (plist)
14284 "Create a dynamic block section, with parameters taken from PLIST.
14285 PLIST must containe a :name entry which is used as name of the block."
14286 (unless (bolp) (newline))
14287 (let ((name (plist-get plist :name)))
14288 (insert "#+BEGIN: " name)
14289 (while plist
14290 (if (eq (car plist) :name)
14291 (setq plist (cddr plist))
14292 (insert " " (prin1-to-string (pop plist)))))
14293 (insert "\n\n#+END:\n")
14294 (beginning-of-line -2)))
14296 (defun org-prepare-dblock ()
14297 "Prepare dynamic block for refresh.
14298 This empties the block, puts the cursor at the insert position and returns
14299 the property list including an extra property :name with the block name."
14300 (unless (looking-at org-dblock-start-re)
14301 (error "Not at a dynamic block"))
14302 (let* ((begdel (1+ (match-end 0)))
14303 (name (org-no-properties (match-string 1)))
14304 (params (append (list :name name)
14305 (read (concat "(" (match-string 3) ")")))))
14306 (unless (re-search-forward org-dblock-end-re nil t)
14307 (error "Dynamic block not terminated"))
14308 (delete-region begdel (match-beginning 0))
14309 (goto-char begdel)
14310 (open-line 1)
14311 params))
14313 (defun org-map-dblocks (&optional command)
14314 "Apply COMMAND to all dynamic blocks in the current buffer.
14315 If COMMAND is not given, use `org-update-dblock'."
14316 (let ((cmd (or command 'org-update-dblock))
14317 pos)
14318 (save-excursion
14319 (goto-char (point-min))
14320 (while (re-search-forward org-dblock-start-re nil t)
14321 (goto-char (setq pos (match-beginning 0)))
14322 (condition-case nil
14323 (funcall cmd)
14324 (error (message "Error during update of dynamic block")))
14325 (goto-char pos)
14326 (unless (re-search-forward org-dblock-end-re nil t)
14327 (error "Dynamic block not terminated"))))))
14329 (defun org-dblock-update (&optional arg)
14330 "User command for updating dynamic blocks.
14331 Update the dynamic block at point. With prefix ARG, update all dynamic
14332 blocks in the buffer."
14333 (interactive "P")
14334 (if arg
14335 (org-update-all-dblocks)
14336 (or (looking-at org-dblock-start-re)
14337 (org-beginning-of-dblock))
14338 (org-update-dblock)))
14340 (defun org-update-dblock ()
14341 "Update the dynamic block at point
14342 This means to empty the block, parse for parameters and then call
14343 the correct writing function."
14344 (save-window-excursion
14345 (let* ((pos (point))
14346 (line (org-current-line))
14347 (params (org-prepare-dblock))
14348 (name (plist-get params :name))
14349 (cmd (intern (concat "org-dblock-write:" name))))
14350 (message "Updating dynamic block `%s' at line %d..." name line)
14351 (funcall cmd params)
14352 (message "Updating dynamic block `%s' at line %d...done" name line)
14353 (goto-char pos))))
14355 (defun org-beginning-of-dblock ()
14356 "Find the beginning of the dynamic block at point.
14357 Error if there is no scuh block at point."
14358 (let ((pos (point))
14359 beg)
14360 (end-of-line 1)
14361 (if (and (re-search-backward org-dblock-start-re nil t)
14362 (setq beg (match-beginning 0))
14363 (re-search-forward org-dblock-end-re nil t)
14364 (> (match-end 0) pos))
14365 (goto-char beg)
14366 (goto-char pos)
14367 (error "Not in a dynamic block"))))
14369 (defun org-update-all-dblocks ()
14370 "Update all dynamic blocks in the buffer.
14371 This function can be used in a hook."
14372 (when (org-mode-p)
14373 (org-map-dblocks 'org-update-dblock)))
14376 ;;;; Completion
14378 (defconst org-additional-option-like-keywords
14379 '("BEGIN_HTML" "BEGIN_LaTeX" "END_HTML" "END_LaTeX"
14380 "ORGTBL" "HTML:" "LaTeX:" "BEGIN:" "END:" "DATE:" "TBLFM"
14381 "BEGIN_EXAMPLE" "END_EXAMPLE"))
14383 (defun org-complete (&optional arg)
14384 "Perform completion on word at point.
14385 At the beginning of a headline, this completes TODO keywords as given in
14386 `org-todo-keywords'.
14387 If the current word is preceded by a backslash, completes the TeX symbols
14388 that are supported for HTML support.
14389 If the current word is preceded by \"#+\", completes special words for
14390 setting file options.
14391 In the line after \"#+STARTUP:, complete valid keywords.\"
14392 At all other locations, this simply calls the value of
14393 `org-completion-fallback-command'."
14394 (interactive "P")
14395 (org-without-partial-completion
14396 (catch 'exit
14397 (let* ((end (point))
14398 (beg1 (save-excursion
14399 (skip-chars-backward (org-re "[:alnum:]_@"))
14400 (point)))
14401 (beg (save-excursion
14402 (skip-chars-backward "a-zA-Z0-9_:$")
14403 (point)))
14404 (confirm (lambda (x) (stringp (car x))))
14405 (searchhead (equal (char-before beg) ?*))
14406 (tag (and (equal (char-before beg1) ?:)
14407 (equal (char-after (point-at-bol)) ?*)))
14408 (prop (and (equal (char-before beg1) ?:)
14409 (not (equal (char-after (point-at-bol)) ?*))))
14410 (texp (equal (char-before beg) ?\\))
14411 (link (equal (char-before beg) ?\[))
14412 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
14413 beg)
14414 "#+"))
14415 (startup (string-match "^#\\+STARTUP:.*"
14416 (buffer-substring (point-at-bol) (point))))
14417 (completion-ignore-case opt)
14418 (type nil)
14419 (tbl nil)
14420 (table (cond
14421 (opt
14422 (setq type :opt)
14423 (append
14424 (mapcar
14425 (lambda (x)
14426 (string-match "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
14427 (cons (match-string 2 x) (match-string 1 x)))
14428 (org-split-string (org-get-current-options) "\n"))
14429 (mapcar 'list org-additional-option-like-keywords)))
14430 (startup
14431 (setq type :startup)
14432 org-startup-options)
14433 (link (append org-link-abbrev-alist-local
14434 org-link-abbrev-alist))
14435 (texp
14436 (setq type :tex)
14437 org-html-entities)
14438 ((string-match "\\`\\*+[ \t]+\\'"
14439 (buffer-substring (point-at-bol) beg))
14440 (setq type :todo)
14441 (mapcar 'list org-todo-keywords-1))
14442 (searchhead
14443 (setq type :searchhead)
14444 (save-excursion
14445 (goto-char (point-min))
14446 (while (re-search-forward org-todo-line-regexp nil t)
14447 (push (list
14448 (org-make-org-heading-search-string
14449 (match-string 3) t))
14450 tbl)))
14451 tbl)
14452 (tag (setq type :tag beg beg1)
14453 (or org-tag-alist (org-get-buffer-tags)))
14454 (prop (setq type :prop beg beg1)
14455 (mapcar 'list (org-buffer-property-keys nil t t)))
14456 (t (progn
14457 (call-interactively org-completion-fallback-command)
14458 (throw 'exit nil)))))
14459 (pattern (buffer-substring-no-properties beg end))
14460 (completion (try-completion pattern table confirm)))
14461 (cond ((eq completion t)
14462 (if (not (assoc (upcase pattern) table))
14463 (message "Already complete")
14464 (if (equal type :opt)
14465 (insert (substring (cdr (assoc (upcase pattern) table))
14466 (length pattern)))
14467 (if (memq type '(:tag :prop)) (insert ":")))))
14468 ((null completion)
14469 (message "Can't find completion for \"%s\"" pattern)
14470 (ding))
14471 ((not (string= pattern completion))
14472 (delete-region beg end)
14473 (if (string-match " +$" completion)
14474 (setq completion (replace-match "" t t completion)))
14475 (insert completion)
14476 (if (get-buffer-window "*Completions*")
14477 (delete-window (get-buffer-window "*Completions*")))
14478 (if (assoc completion table)
14479 (if (eq type :todo) (insert " ")
14480 (if (memq type '(:tag :prop)) (insert ":"))))
14481 (if (and (equal type :opt) (assoc completion table))
14482 (message "%s" (substitute-command-keys
14483 "Press \\[org-complete] again to insert example settings"))))
14485 (message "Making completion list...")
14486 (let ((list (sort (all-completions pattern table confirm)
14487 'string<)))
14488 (with-output-to-temp-buffer "*Completions*"
14489 (condition-case nil
14490 ;; Protection needed for XEmacs and emacs 21
14491 (display-completion-list list pattern)
14492 (error (display-completion-list list)))))
14493 (message "Making completion list...%s" "done")))))))
14495 ;;;; TODO, DEADLINE, Comments
14497 (defun org-toggle-comment ()
14498 "Change the COMMENT state of an entry."
14499 (interactive)
14500 (save-excursion
14501 (org-back-to-heading)
14502 (let (case-fold-search)
14503 (if (looking-at (concat outline-regexp
14504 "\\( *\\<" org-comment-string "\\>[ \t]*\\)"))
14505 (replace-match "" t t nil 1)
14506 (if (looking-at outline-regexp)
14507 (progn
14508 (goto-char (match-end 0))
14509 (insert org-comment-string " ")))))))
14511 (defvar org-last-todo-state-is-todo nil
14512 "This is non-nil when the last TODO state change led to a TODO state.
14513 If the last change removed the TODO tag or switched to DONE, then
14514 this is nil.")
14516 (defvar org-setting-tags nil) ; dynamically skiped
14518 ;; FIXME: better place
14519 (defun org-property-or-variable-value (var &optional inherit)
14520 "Check if there is a property fixing the value of VAR.
14521 If yes, return this value. If not, return the current value of the variable."
14522 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
14523 (if (and prop (stringp prop) (string-match "\\S-" prop))
14524 (read prop)
14525 (symbol-value var))))
14527 (defun org-parse-local-options (string var)
14528 "Parse STRING for startup setting relevant for variable VAR."
14529 (let ((rtn (symbol-value var))
14530 e opts)
14531 (save-match-data
14532 (if (or (not string) (not (string-match "\\S-" string)))
14534 (setq opts (delq nil (mapcar (lambda (x)
14535 (setq e (assoc x org-startup-options))
14536 (if (eq (nth 1 e) var) e nil))
14537 (org-split-string string "[ \t]+"))))
14538 (if (not opts)
14540 (setq rtn nil)
14541 (while (setq e (pop opts))
14542 (if (not (nth 3 e))
14543 (setq rtn (nth 2 e))
14544 (if (not (listp rtn)) (setq rtn nil))
14545 (push (nth 2 e) rtn)))
14546 rtn)))))
14548 (defvar org-blocker-hook nil
14549 "Hook for functions that are allowed to block a state change.
14551 Each function gets as its single argument a property list, see
14552 `org-trigger-hook' for more information about this list.
14554 If any of the functions in this hook returns nil, the state change
14555 is blocked.")
14557 (defvar org-trigger-hook nil
14558 "Hook for functions that are triggered by a state change.
14560 Each function gets as its single argument a property list with at least
14561 the following elements:
14563 (:type type-of-change :position pos-at-entry-start
14564 :from old-state :to new-state)
14566 Depending on the type, more properties may be present.
14568 This mechanism is currently implemented for:
14570 TODO state changes
14571 ------------------
14572 :type todo-state-change
14573 :from previous state (keyword as a string), or nil
14574 :to new state (keyword as a string), or nil")
14577 (defun org-todo (&optional arg)
14578 "Change the TODO state of an item.
14579 The state of an item is given by a keyword at the start of the heading,
14580 like
14581 *** TODO Write paper
14582 *** DONE Call mom
14584 The different keywords are specified in the variable `org-todo-keywords'.
14585 By default the available states are \"TODO\" and \"DONE\".
14586 So for this example: when the item starts with TODO, it is changed to DONE.
14587 When it starts with DONE, the DONE is removed. And when neither TODO nor
14588 DONE are present, add TODO at the beginning of the heading.
14590 With C-u prefix arg, use completion to determine the new state.
14591 With numeric prefix arg, switch to that state.
14593 For calling through lisp, arg is also interpreted in the following way:
14594 'none -> empty state
14595 \"\"(empty string) -> switch to empty state
14596 'done -> switch to DONE
14597 'nextset -> switch to the next set of keywords
14598 'previousset -> switch to the previous set of keywords
14599 \"WAITING\" -> switch to the specified keyword, but only if it
14600 really is a member of `org-todo-keywords'."
14601 (interactive "P")
14602 (save-excursion
14603 (catch 'exit
14604 (org-back-to-heading)
14605 (if (looking-at outline-regexp) (goto-char (1- (match-end 0))))
14606 (or (looking-at (concat " +" org-todo-regexp " *"))
14607 (looking-at " *"))
14608 (let* ((match-data (match-data))
14609 (startpos (point-at-bol))
14610 (logging (save-match-data (org-entry-get nil "LOGGING" t)))
14611 (org-log-done org-log-done)
14612 (org-log-repeat org-log-repeat)
14613 (org-todo-log-states org-todo-log-states)
14614 (this (match-string 1))
14615 (hl-pos (match-beginning 0))
14616 (head (org-get-todo-sequence-head this))
14617 (ass (assoc head org-todo-kwd-alist))
14618 (interpret (nth 1 ass))
14619 (done-word (nth 3 ass))
14620 (final-done-word (nth 4 ass))
14621 (last-state (or this ""))
14622 (completion-ignore-case t)
14623 (member (member this org-todo-keywords-1))
14624 (tail (cdr member))
14625 (state (cond
14626 ((and org-todo-key-trigger
14627 (or (and (equal arg '(4)) (eq org-use-fast-todo-selection 'prefix))
14628 (and (not arg) org-use-fast-todo-selection
14629 (not (eq org-use-fast-todo-selection 'prefix)))))
14630 ;; Use fast selection
14631 (org-fast-todo-selection))
14632 ((and (equal arg '(4))
14633 (or (not org-use-fast-todo-selection)
14634 (not org-todo-key-trigger)))
14635 ;; Read a state with completion
14636 (completing-read "State: " (mapcar (lambda(x) (list x))
14637 org-todo-keywords-1)
14638 nil t))
14639 ((eq arg 'right)
14640 (if this
14641 (if tail (car tail) nil)
14642 (car org-todo-keywords-1)))
14643 ((eq arg 'left)
14644 (if (equal member org-todo-keywords-1)
14646 (if this
14647 (nth (- (length org-todo-keywords-1) (length tail) 2)
14648 org-todo-keywords-1)
14649 (org-last org-todo-keywords-1))))
14650 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
14651 (setq arg nil))) ; hack to fall back to cycling
14652 (arg
14653 ;; user or caller requests a specific state
14654 (cond
14655 ((equal arg "") nil)
14656 ((eq arg 'none) nil)
14657 ((eq arg 'done) (or done-word (car org-done-keywords)))
14658 ((eq arg 'nextset)
14659 (or (car (cdr (member head org-todo-heads)))
14660 (car org-todo-heads)))
14661 ((eq arg 'previousset)
14662 (let ((org-todo-heads (reverse org-todo-heads)))
14663 (or (car (cdr (member head org-todo-heads)))
14664 (car org-todo-heads))))
14665 ((car (member arg org-todo-keywords-1)))
14666 ((nth (1- (prefix-numeric-value arg))
14667 org-todo-keywords-1))))
14668 ((null member) (or head (car org-todo-keywords-1)))
14669 ((equal this final-done-word) nil) ;; -> make empty
14670 ((null tail) nil) ;; -> first entry
14671 ((eq interpret 'sequence)
14672 (car tail))
14673 ((memq interpret '(type priority))
14674 (if (eq this-command last-command)
14675 (car tail)
14676 (if (> (length tail) 0)
14677 (or done-word (car org-done-keywords))
14678 nil)))
14679 (t nil)))
14680 (next (if state (concat " " state " ") " "))
14681 (change-plist (list :type 'todo-state-change :from this :to state
14682 :position startpos))
14683 dolog now-done-p)
14684 (when org-blocker-hook
14685 (unless (save-excursion
14686 (save-match-data
14687 (run-hook-with-args-until-failure
14688 'org-blocker-hook change-plist)))
14689 (if (interactive-p)
14690 (error "TODO state change from %s to %s blocked" this state)
14691 ;; fail silently
14692 (message "TODO state change from %s to %s blocked" this state)
14693 (throw 'exit nil))))
14694 (store-match-data match-data)
14695 (replace-match next t t)
14696 (unless (pos-visible-in-window-p hl-pos)
14697 (message "TODO state changed to %s" (org-trim next)))
14698 (unless head
14699 (setq head (org-get-todo-sequence-head state)
14700 ass (assoc head org-todo-kwd-alist)
14701 interpret (nth 1 ass)
14702 done-word (nth 3 ass)
14703 final-done-word (nth 4 ass)))
14704 (when (memq arg '(nextset previousset))
14705 (message "Keyword-Set %d/%d: %s"
14706 (- (length org-todo-sets) -1
14707 (length (memq (assoc state org-todo-sets) org-todo-sets)))
14708 (length org-todo-sets)
14709 (mapconcat 'identity (assoc state org-todo-sets) " ")))
14710 (setq org-last-todo-state-is-todo
14711 (not (member state org-done-keywords)))
14712 (setq now-done-p (and (member state org-done-keywords)
14713 (not (member this org-done-keywords))))
14714 (and logging (org-local-logging logging))
14715 (when (and (or org-todo-log-states org-log-done)
14716 (not (memq arg '(nextset previousset))))
14717 ;; we need to look at recording a time and note
14718 (setq dolog (or (nth 1 (assoc state org-todo-log-states))
14719 (nth 2 (assoc this org-todo-log-states))))
14720 (when (and state
14721 (member state org-not-done-keywords)
14722 (not (member this org-not-done-keywords)))
14723 ;; This is now a todo state and was not one before
14724 ;; If there was a CLOSED time stamp, get rid of it.
14725 (org-add-planning-info nil nil 'closed))
14726 (when (and now-done-p org-log-done)
14727 ;; It is now done, and it was not done before
14728 (org-add-planning-info 'closed (org-current-time))
14729 (if (and (not dolog) (eq 'note org-log-done))
14730 (org-add-log-maybe 'done state 'findpos 'note)))
14731 (when (and state dolog)
14732 ;; This is a non-nil state, and we need to log it
14733 (org-add-log-maybe 'state state 'findpos dolog)))
14734 ;; Fixup tag positioning
14735 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
14736 (run-hooks 'org-after-todo-state-change-hook)
14737 (if (and arg (not (member state org-done-keywords)))
14738 (setq head (org-get-todo-sequence-head state)))
14739 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
14740 ;; Do we need to trigger a repeat?
14741 (when now-done-p (org-auto-repeat-maybe state))
14742 ;; Fixup cursor location if close to the keyword
14743 (if (and (outline-on-heading-p)
14744 (not (bolp))
14745 (save-excursion (beginning-of-line 1)
14746 (looking-at org-todo-line-regexp))
14747 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
14748 (progn
14749 (goto-char (or (match-end 2) (match-end 1)))
14750 (just-one-space)))
14751 (when org-trigger-hook
14752 (save-excursion
14753 (run-hook-with-args 'org-trigger-hook change-plist)))))))
14755 (defun org-local-logging (value)
14756 "Get logging settings from a property VALUE."
14757 (let* (words w a)
14758 ;; directly set the variables, they are already local.
14759 (setq org-log-done nil
14760 org-log-repeat nil
14761 org-todo-log-states nil)
14762 (setq words (org-split-string value))
14763 (while (setq w (pop words))
14764 (cond
14765 ((setq a (assoc w org-startup-options))
14766 (and (member (nth 1 a) '(org-log-done org-log-repeat))
14767 (set (nth 1 a) (nth 2 a))))
14768 ((setq a (org-extract-log-state-settings w))
14769 (and (member (car a) org-todo-keywords-1)
14770 (push a org-todo-log-states)))))))
14772 (defun org-get-todo-sequence-head (kwd)
14773 "Return the head of the TODO sequence to which KWD belongs.
14774 If KWD is not set, check if there is a text property remembering the
14775 right sequence."
14776 (let (p)
14777 (cond
14778 ((not kwd)
14779 (or (get-text-property (point-at-bol) 'org-todo-head)
14780 (progn
14781 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
14782 nil (point-at-eol)))
14783 (get-text-property p 'org-todo-head))))
14784 ((not (member kwd org-todo-keywords-1))
14785 (car org-todo-keywords-1))
14786 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
14788 (defun org-fast-todo-selection ()
14789 "Fast TODO keyword selection with single keys.
14790 Returns the new TODO keyword, or nil if no state change should occur."
14791 (let* ((fulltable org-todo-key-alist)
14792 (done-keywords org-done-keywords) ;; needed for the faces.
14793 (maxlen (apply 'max (mapcar
14794 (lambda (x)
14795 (if (stringp (car x)) (string-width (car x)) 0))
14796 fulltable)))
14797 (expert nil)
14798 (fwidth (+ maxlen 3 1 3))
14799 (ncol (/ (- (window-width) 4) fwidth))
14800 tg cnt e c tbl
14801 groups ingroup)
14802 (save-window-excursion
14803 (if expert
14804 (set-buffer (get-buffer-create " *Org todo*"))
14805 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
14806 (erase-buffer)
14807 (org-set-local 'org-done-keywords done-keywords)
14808 (setq tbl fulltable cnt 0)
14809 (while (setq e (pop tbl))
14810 (cond
14811 ((equal e '(:startgroup))
14812 (push '() groups) (setq ingroup t)
14813 (when (not (= cnt 0))
14814 (setq cnt 0)
14815 (insert "\n"))
14816 (insert "{ "))
14817 ((equal e '(:endgroup))
14818 (setq ingroup nil cnt 0)
14819 (insert "}\n"))
14821 (setq tg (car e) c (cdr e))
14822 (if ingroup (push tg (car groups)))
14823 (setq tg (org-add-props tg nil 'face
14824 (org-get-todo-face tg)))
14825 (if (and (= cnt 0) (not ingroup)) (insert " "))
14826 (insert "[" c "] " tg (make-string
14827 (- fwidth 4 (length tg)) ?\ ))
14828 (when (= (setq cnt (1+ cnt)) ncol)
14829 (insert "\n")
14830 (if ingroup (insert " "))
14831 (setq cnt 0)))))
14832 (insert "\n")
14833 (goto-char (point-min))
14834 (if (and (not expert) (fboundp 'fit-window-to-buffer))
14835 (fit-window-to-buffer))
14836 (message "[a-z..]:Set [SPC]:clear")
14837 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
14838 (cond
14839 ((or (= c ?\C-g)
14840 (and (= c ?q) (not (rassoc c fulltable))))
14841 (setq quit-flag t))
14842 ((= c ?\ ) nil)
14843 ((setq e (rassoc c fulltable) tg (car e))
14845 (t (setq quit-flag t))))))
14847 (defun org-get-repeat ()
14848 "Check if tere is a deadline/schedule with repeater in this entry."
14849 (save-match-data
14850 (save-excursion
14851 (org-back-to-heading t)
14852 (if (re-search-forward
14853 org-repeat-re (save-excursion (outline-next-heading) (point)) t)
14854 (match-string 1)))))
14856 (defvar org-last-changed-timestamp)
14857 (defvar org-log-post-message)
14858 (defvar org-log-note-purpose)
14859 (defun org-auto-repeat-maybe (done-word)
14860 "Check if the current headline contains a repeated deadline/schedule.
14861 If yes, set TODO state back to what it was and change the base date
14862 of repeating deadline/scheduled time stamps to new date.
14863 This function is run automatically after each state change to a DONE state."
14864 ;; last-state is dynamically scoped into this function
14865 (let* ((repeat (org-get-repeat))
14866 (aa (assoc last-state org-todo-kwd-alist))
14867 (interpret (nth 1 aa))
14868 (head (nth 2 aa))
14869 (whata '(("d" . day) ("m" . month) ("y" . year)))
14870 (msg "Entry repeats: ")
14871 (org-log-done nil)
14872 (org-todo-log-states nil)
14873 re type n what ts)
14874 (when repeat
14875 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
14876 (org-todo (if (eq interpret 'type) last-state head))
14877 (when (and org-log-repeat
14878 (or (not (memq 'org-add-log-note
14879 (default-value 'post-command-hook)))
14880 (eq org-log-note-purpose 'done)))
14881 ;; Make sure a note is taken;
14882 (org-add-log-maybe 'state (or done-word (car org-done-keywords))
14883 'findpos org-log-repeat))
14884 (org-back-to-heading t)
14885 (org-add-planning-info nil nil 'closed)
14886 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
14887 org-deadline-time-regexp "\\)\\|\\("
14888 org-ts-regexp "\\)"))
14889 (while (re-search-forward
14890 re (save-excursion (outline-next-heading) (point)) t)
14891 (setq type (if (match-end 1) org-scheduled-string
14892 (if (match-end 3) org-deadline-string "Plain:"))
14893 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
14894 (when (string-match "\\([-+]?[0-9]+\\)\\([dwmy]\\)" ts)
14895 (setq n (string-to-number (match-string 1 ts))
14896 what (match-string 2 ts))
14897 (if (equal what "w") (setq n (* n 7) what "d"))
14898 (org-timestamp-change n (cdr (assoc what whata)))
14899 (setq msg (concat msg type org-last-changed-timestamp " "))))
14900 (setq org-log-post-message msg)
14901 (message "%s" msg))))
14903 (defun org-show-todo-tree (arg)
14904 "Make a compact tree which shows all headlines marked with TODO.
14905 The tree will show the lines where the regexp matches, and all higher
14906 headlines above the match.
14907 With a \\[universal-argument] prefix, also show the DONE entries.
14908 With a numeric prefix N, construct a sparse tree for the Nth element
14909 of `org-todo-keywords-1'."
14910 (interactive "P")
14911 (let ((case-fold-search nil)
14912 (kwd-re
14913 (cond ((null arg) org-not-done-regexp)
14914 ((equal arg '(4))
14915 (let ((kwd (completing-read "Keyword (or KWD1|KWD2|...): "
14916 (mapcar 'list org-todo-keywords-1))))
14917 (concat "\\("
14918 (mapconcat 'identity (org-split-string kwd "|") "\\|")
14919 "\\)\\>")))
14920 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
14921 (regexp-quote (nth (1- (prefix-numeric-value arg))
14922 org-todo-keywords-1)))
14923 (t (error "Invalid prefix argument: %s" arg)))))
14924 (message "%d TODO entries found"
14925 (org-occur (concat "^" outline-regexp " *" kwd-re )))))
14927 (defun org-deadline (&optional remove)
14928 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
14929 With argument REMOVE, remove any deadline from the item."
14930 (interactive "P")
14931 (if remove
14932 (progn
14933 (org-remove-timestamp-with-keyword org-deadline-string)
14934 (message "Item no longer has a deadline."))
14935 (org-add-planning-info 'deadline nil 'closed)))
14937 (defun org-schedule (&optional remove)
14938 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
14939 With argument REMOVE, remove any scheduling date from the item."
14940 (interactive "P")
14941 (if remove
14942 (progn
14943 (org-remove-timestamp-with-keyword org-scheduled-string)
14944 (message "Item is no longer scheduled."))
14945 (org-add-planning-info 'scheduled nil 'closed)))
14947 (defun org-remove-timestamp-with-keyword (keyword)
14948 "Remove all time stamps with KEYWORD in the current entry."
14949 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
14950 beg)
14951 (save-excursion
14952 (org-back-to-heading t)
14953 (setq beg (point))
14954 (org-end-of-subtree t t)
14955 (while (re-search-backward re beg t)
14956 (replace-match "")
14957 (unless (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
14958 (delete-region (point-at-bol) (min (1+ (point)) (point-max))))))))
14960 (defun org-add-planning-info (what &optional time &rest remove)
14961 "Insert new timestamp with keyword in the line directly after the headline.
14962 WHAT indicates what kind of time stamp to add. TIME indicated the time to use.
14963 If non is given, the user is prompted for a date.
14964 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
14965 be removed."
14966 (interactive)
14967 (let (org-time-was-given org-end-time-was-given)
14968 (when what (setq time (or time (org-read-date nil 'to-time))))
14969 (when (and org-insert-labeled-timestamps-at-point
14970 (member what '(scheduled deadline)))
14971 (insert
14972 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
14973 (org-insert-time-stamp time org-time-was-given
14974 nil nil nil (list org-end-time-was-given))
14975 (setq what nil))
14976 (save-excursion
14977 (save-restriction
14978 (let (col list elt ts buffer-invisibility-spec)
14979 (org-back-to-heading t)
14980 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
14981 (goto-char (match-end 1))
14982 (setq col (current-column))
14983 (goto-char (match-end 0))
14984 (if (eobp) (insert "\n") (forward-char 1))
14985 (if (and (not (looking-at outline-regexp))
14986 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
14987 "[^\r\n]*"))
14988 (not (equal (match-string 1) org-clock-string)))
14989 (narrow-to-region (match-beginning 0) (match-end 0))
14990 (insert-before-markers "\n")
14991 (backward-char 1)
14992 (narrow-to-region (point) (point))
14993 (indent-to-column col))
14994 ;; Check if we have to remove something.
14995 (setq list (cons what remove))
14996 (while list
14997 (setq elt (pop list))
14998 (goto-char (point-min))
14999 (when (or (and (eq elt 'scheduled)
15000 (re-search-forward org-scheduled-time-regexp nil t))
15001 (and (eq elt 'deadline)
15002 (re-search-forward org-deadline-time-regexp nil t))
15003 (and (eq elt 'closed)
15004 (re-search-forward org-closed-time-regexp nil t)))
15005 (replace-match "")
15006 (if (looking-at "--+<[^>]+>") (replace-match ""))
15007 (if (looking-at " +") (replace-match ""))))
15008 (goto-char (point-max))
15009 (when what
15010 (insert
15011 (if (not (equal (char-before) ?\ )) " " "")
15012 (cond ((eq what 'scheduled) org-scheduled-string)
15013 ((eq what 'deadline) org-deadline-string)
15014 ((eq what 'closed) org-closed-string))
15015 " ")
15016 (setq ts (org-insert-time-stamp
15017 time
15018 (or org-time-was-given
15019 (and (eq what 'closed) org-log-done-with-time))
15020 (eq what 'closed)
15021 nil nil (list org-end-time-was-given)))
15022 (end-of-line 1))
15023 (goto-char (point-min))
15024 (widen)
15025 (if (looking-at "[ \t]+\r?\n")
15026 (replace-match ""))
15027 ts)))))
15029 (defvar org-log-note-marker (make-marker))
15030 (defvar org-log-note-purpose nil)
15031 (defvar org-log-note-state nil)
15032 (defvar org-log-note-how nil)
15033 (defvar org-log-note-window-configuration nil)
15034 (defvar org-log-note-return-to (make-marker))
15035 (defvar org-log-post-message nil
15036 "Message to be displayed after a log note has been stored.
15037 The auto-repeater uses this.")
15039 (defun org-add-log-maybe (&optional purpose state findpos how)
15040 "Set up the post command hook to take a note.
15041 If this is about to TODO state change, the new state is expected in STATE.
15042 When FINDPOS is non-nil, find the correct position for the note in
15043 the current entry. If not, assume that it can be inserted at point."
15044 (save-excursion
15045 (when findpos
15046 (org-back-to-heading t)
15047 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"
15048 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
15049 "[^\r\n]*\\)?"))
15050 (goto-char (match-end 0))
15051 (unless org-log-states-order-reversed
15052 (and (= (char-after) ?\n) (forward-char 1))
15053 (org-skip-over-state-notes)
15054 (skip-chars-backward " \t\n\r")))
15055 (move-marker org-log-note-marker (point))
15056 (setq org-log-note-purpose purpose
15057 org-log-note-state state
15058 org-log-note-how how)
15059 (add-hook 'post-command-hook 'org-add-log-note 'append)))
15061 (defun org-skip-over-state-notes ()
15062 "Skip past the list of State notes in an entry."
15063 (if (looking-at "\n[ \t]*- State") (forward-char 1))
15064 (while (looking-at "[ \t]*- State")
15065 (condition-case nil
15066 (org-next-item)
15067 (error (org-end-of-item)))))
15069 (defun org-add-log-note (&optional purpose)
15070 "Pop up a window for taking a note, and add this note later at point."
15071 (remove-hook 'post-command-hook 'org-add-log-note)
15072 (setq org-log-note-window-configuration (current-window-configuration))
15073 (delete-other-windows)
15074 (move-marker org-log-note-return-to (point))
15075 (switch-to-buffer (marker-buffer org-log-note-marker))
15076 (goto-char org-log-note-marker)
15077 (org-switch-to-buffer-other-window "*Org Note*")
15078 (erase-buffer)
15079 (if (memq org-log-note-how '(time state)) ; FIXME: time or state????????????
15080 (org-store-log-note)
15081 (let ((org-inhibit-startup t)) (org-mode))
15082 (insert (format "# Insert note for %s.
15083 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
15084 (cond
15085 ((eq org-log-note-purpose 'clock-out) "stopped clock")
15086 ((eq org-log-note-purpose 'done) "closed todo item")
15087 ((eq org-log-note-purpose 'state)
15088 (format "state change to \"%s\"" org-log-note-state))
15089 (t (error "This should not happen")))))
15090 (org-set-local 'org-finish-function 'org-store-log-note)))
15092 (defun org-store-log-note ()
15093 "Finish taking a log note, and insert it to where it belongs."
15094 (let ((txt (buffer-string))
15095 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
15096 lines ind)
15097 (kill-buffer (current-buffer))
15098 (while (string-match "\\`#.*\n[ \t\n]*" txt)
15099 (setq txt (replace-match "" t t txt)))
15100 (if (string-match "\\s-+\\'" txt)
15101 (setq txt (replace-match "" t t txt)))
15102 (setq lines (org-split-string txt "\n"))
15103 (when (and note (string-match "\\S-" note))
15104 (setq note
15105 (org-replace-escapes
15106 note
15107 (list (cons "%u" (user-login-name))
15108 (cons "%U" user-full-name)
15109 (cons "%t" (format-time-string
15110 (org-time-stamp-format 'long 'inactive)
15111 (current-time)))
15112 (cons "%s" (if org-log-note-state
15113 (concat "\"" org-log-note-state "\"")
15114 "")))))
15115 (if lines (setq note (concat note " \\\\")))
15116 (push note lines))
15117 (when (or current-prefix-arg org-note-abort) (setq lines nil))
15118 (when lines
15119 (save-excursion
15120 (set-buffer (marker-buffer org-log-note-marker))
15121 (save-excursion
15122 (goto-char org-log-note-marker)
15123 (move-marker org-log-note-marker nil)
15124 (end-of-line 1)
15125 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
15126 (indent-relative nil)
15127 (insert "- " (pop lines))
15128 (org-indent-line-function)
15129 (beginning-of-line 1)
15130 (looking-at "[ \t]*")
15131 (setq ind (concat (match-string 0) " "))
15132 (end-of-line 1)
15133 (while lines (insert "\n" ind (pop lines)))))))
15134 (set-window-configuration org-log-note-window-configuration)
15135 (with-current-buffer (marker-buffer org-log-note-return-to)
15136 (goto-char org-log-note-return-to))
15137 (move-marker org-log-note-return-to nil)
15138 (and org-log-post-message (message "%s" org-log-post-message)))
15140 ;; FIXME: what else would be useful?
15141 ;; - priority
15142 ;; - date
15144 (defun org-sparse-tree (&optional arg)
15145 "Create a sparse tree, prompt for the details.
15146 This command can create sparse trees. You first need to select the type
15147 of match used to create the tree:
15149 t Show entries with a specific TODO keyword.
15150 T Show entries selected by a tags match.
15151 p Enter a property name and its value (both with completion on existing
15152 names/values) and show entries with that property.
15153 r Show entries matching a regular expression
15154 d Show deadlines due within `org-deadline-warning-days'."
15155 (interactive "P")
15156 (let (ans kwd value)
15157 (message "Sparse tree: [/]regexp [t]odo-kwd [T]ag [p]roperty [d]eadlines [b]efore-date")
15158 (setq ans (read-char-exclusive))
15159 (cond
15160 ((equal ans ?d)
15161 (call-interactively 'org-check-deadlines))
15162 ((equal ans ?b)
15163 (call-interactively 'org-check-before-date))
15164 ((equal ans ?t)
15165 (org-show-todo-tree '(4)))
15166 ((equal ans ?T)
15167 (call-interactively 'org-tags-sparse-tree))
15168 ((member ans '(?p ?P))
15169 (setq kwd (completing-read "Property: "
15170 (mapcar 'list (org-buffer-property-keys))))
15171 (setq value (completing-read "Value: "
15172 (mapcar 'list (org-property-values kwd))))
15173 (unless (string-match "\\`{.*}\\'" value)
15174 (setq value (concat "\"" value "\"")))
15175 (org-tags-sparse-tree arg (concat kwd "=" value)))
15176 ((member ans '(?r ?R ?/))
15177 (call-interactively 'org-occur))
15178 (t (error "No such sparse tree command \"%c\"" ans)))))
15180 (defvar org-occur-highlights nil)
15181 (make-variable-buffer-local 'org-occur-highlights)
15183 (defun org-occur (regexp &optional keep-previous callback)
15184 "Make a compact tree which shows all matches of REGEXP.
15185 The tree will show the lines where the regexp matches, and all higher
15186 headlines above the match. It will also show the heading after the match,
15187 to make sure editing the matching entry is easy.
15188 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
15189 call to `org-occur' will be kept, to allow stacking of calls to this
15190 command.
15191 If CALLBACK is non-nil, it is a function which is called to confirm
15192 that the match should indeed be shown."
15193 (interactive "sRegexp: \nP")
15194 (or keep-previous (org-remove-occur-highlights nil nil t))
15195 (let ((cnt 0))
15196 (save-excursion
15197 (goto-char (point-min))
15198 (if (or (not keep-previous) ; do not want to keep
15199 (not org-occur-highlights)) ; no previous matches
15200 ;; hide everything
15201 (org-overview))
15202 (while (re-search-forward regexp nil t)
15203 (when (or (not callback)
15204 (save-match-data (funcall callback)))
15205 (setq cnt (1+ cnt))
15206 (when org-highlight-sparse-tree-matches
15207 (org-highlight-new-match (match-beginning 0) (match-end 0)))
15208 (org-show-context 'occur-tree))))
15209 (when org-remove-highlights-with-change
15210 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
15211 nil 'local))
15212 (unless org-sparse-tree-open-archived-trees
15213 (org-hide-archived-subtrees (point-min) (point-max)))
15214 (run-hooks 'org-occur-hook)
15215 (if (interactive-p)
15216 (message "%d match(es) for regexp %s" cnt regexp))
15217 cnt))
15219 (defun org-show-context (&optional key)
15220 "Make sure point and context and visible.
15221 How much context is shown depends upon the variables
15222 `org-show-hierarchy-above', `org-show-following-heading'. and
15223 `org-show-siblings'."
15224 (let ((heading-p (org-on-heading-p t))
15225 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
15226 (following-p (org-get-alist-option org-show-following-heading key))
15227 (entry-p (org-get-alist-option org-show-entry-below key))
15228 (siblings-p (org-get-alist-option org-show-siblings key)))
15229 (catch 'exit
15230 ;; Show heading or entry text
15231 (if (and heading-p (not entry-p))
15232 (org-flag-heading nil) ; only show the heading
15233 (and (or entry-p (org-invisible-p) (org-invisible-p2))
15234 (org-show-hidden-entry))) ; show entire entry
15235 (when following-p
15236 ;; Show next sibling, or heading below text
15237 (save-excursion
15238 (and (if heading-p (org-goto-sibling) (outline-next-heading))
15239 (org-flag-heading nil))))
15240 (when siblings-p (org-show-siblings))
15241 (when hierarchy-p
15242 ;; show all higher headings, possibly with siblings
15243 (save-excursion
15244 (while (and (condition-case nil
15245 (progn (org-up-heading-all 1) t)
15246 (error nil))
15247 (not (bobp)))
15248 (org-flag-heading nil)
15249 (when siblings-p (org-show-siblings))))))))
15251 (defun org-reveal (&optional siblings)
15252 "Show current entry, hierarchy above it, and the following headline.
15253 This can be used to show a consistent set of context around locations
15254 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
15255 not t for the search context.
15257 With optional argument SIBLINGS, on each level of the hierarchy all
15258 siblings are shown. This repairs the tree structure to what it would
15259 look like when opened with hierarchical calls to `org-cycle'."
15260 (interactive "P")
15261 (let ((org-show-hierarchy-above t)
15262 (org-show-following-heading t)
15263 (org-show-siblings (if siblings t org-show-siblings)))
15264 (org-show-context nil)))
15266 (defun org-highlight-new-match (beg end)
15267 "Highlight from BEG to END and mark the highlight is an occur headline."
15268 (let ((ov (org-make-overlay beg end)))
15269 (org-overlay-put ov 'face 'secondary-selection)
15270 (push ov org-occur-highlights)))
15272 (defun org-remove-occur-highlights (&optional beg end noremove)
15273 "Remove the occur highlights from the buffer.
15274 BEG and END are ignored. If NOREMOVE is nil, remove this function
15275 from the `before-change-functions' in the current buffer."
15276 (interactive)
15277 (unless org-inhibit-highlight-removal
15278 (mapc 'org-delete-overlay org-occur-highlights)
15279 (setq org-occur-highlights nil)
15280 (unless noremove
15281 (remove-hook 'before-change-functions
15282 'org-remove-occur-highlights 'local))))
15284 ;;;; Priorities
15286 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
15287 "Regular expression matching the priority indicator.")
15289 (defvar org-remove-priority-next-time nil)
15291 (defun org-priority-up ()
15292 "Increase the priority of the current item."
15293 (interactive)
15294 (org-priority 'up))
15296 (defun org-priority-down ()
15297 "Decrease the priority of the current item."
15298 (interactive)
15299 (org-priority 'down))
15301 (defun org-priority (&optional action)
15302 "Change the priority of an item by ARG.
15303 ACTION can be `set', `up', `down', or a character."
15304 (interactive)
15305 (setq action (or action 'set))
15306 (let (current new news have remove)
15307 (save-excursion
15308 (org-back-to-heading)
15309 (if (looking-at org-priority-regexp)
15310 (setq current (string-to-char (match-string 2))
15311 have t)
15312 (setq current org-default-priority))
15313 (cond
15314 ((or (eq action 'set) (integerp action))
15315 (if (integerp action)
15316 (setq new action)
15317 (message "Priority %c-%c, SPC to remove: " org-highest-priority org-lowest-priority)
15318 (setq new (read-char-exclusive)))
15319 (if (and (= (upcase org-highest-priority) org-highest-priority)
15320 (= (upcase org-lowest-priority) org-lowest-priority))
15321 (setq new (upcase new)))
15322 (cond ((equal new ?\ ) (setq remove t))
15323 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
15324 (error "Priority must be between `%c' and `%c'"
15325 org-highest-priority org-lowest-priority))))
15326 ((eq action 'up)
15327 (if (and (not have) (eq last-command this-command))
15328 (setq new org-lowest-priority)
15329 (setq new (if (and org-priority-start-cycle-with-default (not have))
15330 org-default-priority (1- current)))))
15331 ((eq action 'down)
15332 (if (and (not have) (eq last-command this-command))
15333 (setq new org-highest-priority)
15334 (setq new (if (and org-priority-start-cycle-with-default (not have))
15335 org-default-priority (1+ current)))))
15336 (t (error "Invalid action")))
15337 (if (or (< (upcase new) org-highest-priority)
15338 (> (upcase new) org-lowest-priority))
15339 (setq remove t))
15340 (setq news (format "%c" new))
15341 (if have
15342 (if remove
15343 (replace-match "" t t nil 1)
15344 (replace-match news t t nil 2))
15345 (if remove
15346 (error "No priority cookie found in line")
15347 (looking-at org-todo-line-regexp)
15348 (if (match-end 2)
15349 (progn
15350 (goto-char (match-end 2))
15351 (insert " [#" news "]"))
15352 (goto-char (match-beginning 3))
15353 (insert "[#" news "] ")))))
15354 (org-preserve-lc (org-set-tags nil 'align))
15355 (if remove
15356 (message "Priority removed")
15357 (message "Priority of current item set to %s" news))))
15360 (defun org-get-priority (s)
15361 "Find priority cookie and return priority."
15362 (save-match-data
15363 (if (not (string-match org-priority-regexp s))
15364 (* 1000 (- org-lowest-priority org-default-priority))
15365 (* 1000 (- org-lowest-priority
15366 (string-to-char (match-string 2 s)))))))
15368 ;;;; Tags
15370 (defun org-scan-tags (action matcher &optional todo-only)
15371 "Scan headline tags with inheritance and produce output ACTION.
15372 ACTION can be `sparse-tree' or `agenda'. MATCHER is a Lisp form to be
15373 evaluated, testing if a given set of tags qualifies a headline for
15374 inclusion. When TODO-ONLY is non-nil, only lines with a TODO keyword
15375 are included in the output."
15376 (let* ((re (concat "[\n\r]" outline-regexp " *\\(\\<\\("
15377 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
15378 (org-re
15379 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*$")))
15380 (props (list 'face nil
15381 'done-face 'org-done
15382 'undone-face nil
15383 'mouse-face 'highlight
15384 'org-not-done-regexp org-not-done-regexp
15385 'org-todo-regexp org-todo-regexp
15386 'keymap org-agenda-keymap
15387 'help-echo
15388 (format "mouse-2 or RET jump to org file %s"
15389 (abbreviate-file-name
15390 (or (buffer-file-name (buffer-base-buffer))
15391 (buffer-name (buffer-base-buffer)))))))
15392 (case-fold-search nil)
15393 lspos
15394 tags tags-list tags-alist (llast 0) rtn level category i txt
15395 todo marker entry priority)
15396 (save-excursion
15397 (goto-char (point-min))
15398 (when (eq action 'sparse-tree)
15399 (org-overview)
15400 (org-remove-occur-highlights))
15401 (while (re-search-forward re nil t)
15402 (catch :skip
15403 (setq todo (if (match-end 1) (match-string 2))
15404 tags (if (match-end 4) (match-string 4)))
15405 (goto-char (setq lspos (1+ (match-beginning 0))))
15406 (setq level (org-reduced-level (funcall outline-level))
15407 category (org-get-category))
15408 (setq i llast llast level)
15409 ;; remove tag lists from same and sublevels
15410 (while (>= i level)
15411 (when (setq entry (assoc i tags-alist))
15412 (setq tags-alist (delete entry tags-alist)))
15413 (setq i (1- i)))
15414 ;; add the nex tags
15415 (when tags
15416 (setq tags (mapcar 'downcase (org-split-string tags ":"))
15417 tags-alist
15418 (cons (cons level tags) tags-alist)))
15419 ;; compile tags for current headline
15420 (setq tags-list
15421 (if org-use-tag-inheritance
15422 (apply 'append (mapcar 'cdr tags-alist))
15423 tags))
15424 (when (and (or (not todo-only) (member todo org-not-done-keywords))
15425 (eval matcher)
15426 (or (not org-agenda-skip-archived-trees)
15427 (not (member org-archive-tag tags-list))))
15428 (and (eq action 'agenda) (org-agenda-skip))
15429 ;; list this headline
15431 (if (eq action 'sparse-tree)
15432 (progn
15433 (and org-highlight-sparse-tree-matches
15434 (org-get-heading) (match-end 0)
15435 (org-highlight-new-match
15436 (match-beginning 0) (match-beginning 1)))
15437 (org-show-context 'tags-tree))
15438 (setq txt (org-format-agenda-item
15440 (concat
15441 (if org-tags-match-list-sublevels
15442 (make-string (1- level) ?.) "")
15443 (org-get-heading))
15444 category tags-list)
15445 priority (org-get-priority txt))
15446 (goto-char lspos)
15447 (setq marker (org-agenda-new-marker))
15448 (org-add-props txt props
15449 'org-marker marker 'org-hd-marker marker 'org-category category
15450 'priority priority 'type "tagsmatch")
15451 (push txt rtn))
15452 ;; if we are to skip sublevels, jump to end of subtree
15453 (or org-tags-match-list-sublevels (org-end-of-subtree t))))))
15454 (when (and (eq action 'sparse-tree)
15455 (not org-sparse-tree-open-archived-trees))
15456 (org-hide-archived-subtrees (point-min) (point-max)))
15457 (nreverse rtn)))
15459 (defvar todo-only) ;; dynamically scoped
15461 (defun org-tags-sparse-tree (&optional todo-only match)
15462 "Create a sparse tree according to tags string MATCH.
15463 MATCH can contain positive and negative selection of tags, like
15464 \"+WORK+URGENT-WITHBOSS\".
15465 If optional argument TODO_ONLY is non-nil, only select lines that are
15466 also TODO lines."
15467 (interactive "P")
15468 (org-prepare-agenda-buffers (list (current-buffer)))
15469 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
15471 (defvar org-cached-props nil)
15472 (defun org-cached-entry-get (pom property)
15473 (if (or (eq t org-use-property-inheritance)
15474 (member property org-use-property-inheritance))
15475 ;; Caching is not possible, check it directly
15476 (org-entry-get pom property 'inherit)
15477 ;; Get all properties, so that we can do complicated checks easily
15478 (cdr (assoc property (or org-cached-props
15479 (setq org-cached-props
15480 (org-entry-properties pom)))))))
15482 (defun org-global-tags-completion-table (&optional files)
15483 "Return the list of all tags in all agenda buffer/files."
15484 (save-excursion
15485 (org-uniquify
15486 (delq nil
15487 (apply 'append
15488 (mapcar
15489 (lambda (file)
15490 (set-buffer (find-file-noselect file))
15491 (append (org-get-buffer-tags)
15492 (mapcar (lambda (x) (if (stringp (car-safe x))
15493 (list (car-safe x)) nil))
15494 org-tag-alist)))
15495 (if (and files (car files))
15496 files
15497 (org-agenda-files))))))))
15499 (defun org-make-tags-matcher (match)
15500 "Create the TAGS//TODO matcher form for the selection string MATCH."
15501 ;; todo-only is scoped dynamically into this function, and the function
15502 ;; may change it it the matcher asksk for it.
15503 (unless match
15504 ;; Get a new match request, with completion
15505 (let ((org-last-tags-completion-table
15506 (org-global-tags-completion-table)))
15507 (setq match (completing-read
15508 "Match: " 'org-tags-completion-function nil nil nil
15509 'org-tags-history))))
15511 ;; Parse the string and create a lisp form
15512 (let ((match0 match)
15513 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL=\\([0-9]+\\)\\|\\([[:alnum:]_]+\\)=\\({[^}]+}\\|\"[^\"]*\"\\)\\|[[:alnum:]_@]+\\)"))
15514 minus tag mm
15515 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
15516 orterms term orlist re-p level-p prop-p pn pv cat-p gv)
15517 (if (string-match "/+" match)
15518 ;; match contains also a todo-matching request
15519 (progn
15520 (setq tagsmatch (substring match 0 (match-beginning 0))
15521 todomatch (substring match (match-end 0)))
15522 (if (string-match "^!" todomatch)
15523 (setq todo-only t todomatch (substring todomatch 1)))
15524 (if (string-match "^\\s-*$" todomatch)
15525 (setq todomatch nil)))
15526 ;; only matching tags
15527 (setq tagsmatch match todomatch nil))
15529 ;; Make the tags matcher
15530 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
15531 (setq tagsmatcher t)
15532 (setq orterms (org-split-string tagsmatch "|") orlist nil)
15533 (while (setq term (pop orterms))
15534 (while (and (equal (substring term -1) "\\") orterms)
15535 (setq term (concat term "|" (pop orterms)))) ; repair bad split
15536 (while (string-match re term)
15537 (setq minus (and (match-end 1)
15538 (equal (match-string 1 term) "-"))
15539 tag (match-string 2 term)
15540 re-p (equal (string-to-char tag) ?{)
15541 level-p (match-end 3)
15542 prop-p (match-end 4)
15543 mm (cond
15544 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
15545 (level-p `(= level ,(string-to-number
15546 (match-string 3 term))))
15547 (prop-p
15548 (setq pn (match-string 4 term)
15549 pv (match-string 5 term)
15550 cat-p (equal pn "CATEGORY")
15551 re-p (equal (string-to-char pv) ?{)
15552 pv (substring pv 1 -1))
15553 (if (equal pn "CATEGORY")
15554 (setq gv '(get-text-property (point) 'org-category))
15555 (setq gv `(org-cached-entry-get nil ,pn)))
15556 (if re-p
15557 `(string-match ,pv (or ,gv ""))
15558 `(equal ,pv (or ,gv ""))))
15559 (t `(member ,(downcase tag) tags-list)))
15560 mm (if minus (list 'not mm) mm)
15561 term (substring term (match-end 0)))
15562 (push mm tagsmatcher))
15563 (push (if (> (length tagsmatcher) 1)
15564 (cons 'and tagsmatcher)
15565 (car tagsmatcher))
15566 orlist)
15567 (setq tagsmatcher nil))
15568 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
15569 (setq tagsmatcher
15570 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
15572 ;; Make the todo matcher
15573 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
15574 (setq todomatcher t)
15575 (setq orterms (org-split-string todomatch "|") orlist nil)
15576 (while (setq term (pop orterms))
15577 (while (string-match re term)
15578 (setq minus (and (match-end 1)
15579 (equal (match-string 1 term) "-"))
15580 kwd (match-string 2 term)
15581 re-p (equal (string-to-char kwd) ?{)
15582 term (substring term (match-end 0))
15583 mm (if re-p
15584 `(string-match ,(substring kwd 1 -1) todo)
15585 (list 'equal 'todo kwd))
15586 mm (if minus (list 'not mm) mm))
15587 (push mm todomatcher))
15588 (push (if (> (length todomatcher) 1)
15589 (cons 'and todomatcher)
15590 (car todomatcher))
15591 orlist)
15592 (setq todomatcher nil))
15593 (setq todomatcher (if (> (length orlist) 1)
15594 (cons 'or orlist) (car orlist))))
15596 ;; Return the string and lisp forms of the matcher
15597 (setq matcher (if todomatcher
15598 (list 'and tagsmatcher todomatcher)
15599 tagsmatcher))
15600 (cons match0 matcher)))
15602 (defun org-match-any-p (re list)
15603 "Does re match any element of list?"
15604 (setq list (mapcar (lambda (x) (string-match re x)) list))
15605 (delq nil list))
15607 (defvar org-add-colon-after-tag-completion nil) ;; dynamically skoped param
15608 (defvar org-tags-overlay (org-make-overlay 1 1))
15609 (org-detach-overlay org-tags-overlay)
15611 (defun org-align-tags-here (to-col)
15612 ;; Assumes that this is a headline
15613 (let ((pos (point)) (col (current-column)) tags)
15614 (beginning-of-line 1)
15615 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
15616 (< pos (match-beginning 2)))
15617 (progn
15618 (setq tags (match-string 2))
15619 (goto-char (match-beginning 1))
15620 (insert " ")
15621 (delete-region (point) (1+ (match-end 0)))
15622 (backward-char 1)
15623 (move-to-column
15624 (max (1+ (current-column))
15625 (1+ col)
15626 (if (> to-col 0)
15627 to-col
15628 (- (abs to-col) (length tags))))
15630 (insert tags)
15631 (move-to-column (min (current-column) col) t))
15632 (goto-char pos))))
15634 (defun org-set-tags (&optional arg just-align)
15635 "Set the tags for the current headline.
15636 With prefix ARG, realign all tags in headings in the current buffer."
15637 (interactive "P")
15638 (let* ((re (concat "^" outline-regexp))
15639 (current (org-get-tags-string))
15640 (col (current-column))
15641 (org-setting-tags t)
15642 table current-tags inherited-tags ; computed below when needed
15643 tags p0 c0 c1 rpl)
15644 (if arg
15645 (save-excursion
15646 (goto-char (point-min))
15647 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
15648 (while (re-search-forward re nil t)
15649 (org-set-tags nil t)
15650 (end-of-line 1)))
15651 (message "All tags realigned to column %d" org-tags-column))
15652 (if just-align
15653 (setq tags current)
15654 ;; Get a new set of tags from the user
15655 (save-excursion
15656 (setq table (or org-tag-alist (org-get-buffer-tags))
15657 org-last-tags-completion-table table
15658 current-tags (org-split-string current ":")
15659 inherited-tags (nreverse
15660 (nthcdr (length current-tags)
15661 (nreverse (org-get-tags-at))))
15662 tags
15663 (if (or (eq t org-use-fast-tag-selection)
15664 (and org-use-fast-tag-selection
15665 (delq nil (mapcar 'cdr table))))
15666 (org-fast-tag-selection
15667 current-tags inherited-tags table
15668 (if org-fast-tag-selection-include-todo org-todo-key-alist))
15669 (let ((org-add-colon-after-tag-completion t))
15670 (org-trim
15671 (org-without-partial-completion
15672 (completing-read "Tags: " 'org-tags-completion-function
15673 nil nil current 'org-tags-history)))))))
15674 (while (string-match "[-+&]+" tags)
15675 ;; No boolean logic, just a list
15676 (setq tags (replace-match ":" t t tags))))
15678 (if (string-match "\\`[\t ]*\\'" tags)
15679 (setq tags "")
15680 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
15681 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
15683 ;; Insert new tags at the correct column
15684 (beginning-of-line 1)
15685 (cond
15686 ((and (equal current "") (equal tags "")))
15687 ((re-search-forward
15688 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
15689 (point-at-eol) t)
15690 (if (equal tags "")
15691 (setq rpl "")
15692 (goto-char (match-beginning 0))
15693 (setq c0 (current-column) p0 (point)
15694 c1 (max (1+ c0) (if (> org-tags-column 0)
15695 org-tags-column
15696 (- (- org-tags-column) (length tags))))
15697 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
15698 (replace-match rpl t t)
15699 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
15700 tags)
15701 (t (error "Tags alignment failed")))
15702 (move-to-column col)
15703 (unless just-align
15704 (run-hooks 'org-after-tags-change-hook)))))
15706 (defun org-change-tag-in-region (beg end tag off)
15707 "Add or remove TAG for each entry in the region.
15708 This works in the agenda, and also in an org-mode buffer."
15709 (interactive
15710 (list (region-beginning) (region-end)
15711 (let ((org-last-tags-completion-table
15712 (if (org-mode-p)
15713 (org-get-buffer-tags)
15714 (org-global-tags-completion-table))))
15715 (completing-read
15716 "Tag: " 'org-tags-completion-function nil nil nil
15717 'org-tags-history))
15718 (progn
15719 (message "[s]et or [r]emove? ")
15720 (equal (read-char-exclusive) ?r))))
15721 (if (fboundp 'deactivate-mark) (deactivate-mark))
15722 (let ((agendap (equal major-mode 'org-agenda-mode))
15723 l1 l2 m buf pos newhead (cnt 0))
15724 (goto-char end)
15725 (setq l2 (1- (org-current-line)))
15726 (goto-char beg)
15727 (setq l1 (org-current-line))
15728 (loop for l from l1 to l2 do
15729 (goto-line l)
15730 (setq m (get-text-property (point) 'org-hd-marker))
15731 (when (or (and (org-mode-p) (org-on-heading-p))
15732 (and agendap m))
15733 (setq buf (if agendap (marker-buffer m) (current-buffer))
15734 pos (if agendap m (point)))
15735 (with-current-buffer buf
15736 (save-excursion
15737 (save-restriction
15738 (goto-char pos)
15739 (setq cnt (1+ cnt))
15740 (org-toggle-tag tag (if off 'off 'on))
15741 (setq newhead (org-get-heading)))))
15742 (and agendap (org-agenda-change-all-lines newhead m))))
15743 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
15745 (defun org-tags-completion-function (string predicate &optional flag)
15746 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
15747 (confirm (lambda (x) (stringp (car x)))))
15748 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
15749 (setq s1 (match-string 1 string)
15750 s2 (match-string 2 string))
15751 (setq s1 "" s2 string))
15752 (cond
15753 ((eq flag nil)
15754 ;; try completion
15755 (setq rtn (try-completion s2 ctable confirm))
15756 (if (stringp rtn)
15757 (setq rtn
15758 (concat s1 s2 (substring rtn (length s2))
15759 (if (and org-add-colon-after-tag-completion
15760 (assoc rtn ctable))
15761 ":" ""))))
15762 rtn)
15763 ((eq flag t)
15764 ;; all-completions
15765 (all-completions s2 ctable confirm)
15767 ((eq flag 'lambda)
15768 ;; exact match?
15769 (assoc s2 ctable)))
15772 (defun org-fast-tag-insert (kwd tags face &optional end)
15773 "Insert KDW, and the TAGS, the latter with face FACE. Also inser END."
15774 (insert (format "%-12s" (concat kwd ":"))
15775 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
15776 (or end "")))
15778 (defun org-fast-tag-show-exit (flag)
15779 (save-excursion
15780 (goto-line 3)
15781 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
15782 (replace-match ""))
15783 (when flag
15784 (end-of-line 1)
15785 (move-to-column (- (window-width) 19) t)
15786 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
15788 (defun org-set-current-tags-overlay (current prefix)
15789 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
15790 (if (featurep 'xemacs)
15791 (org-overlay-display org-tags-overlay (concat prefix s)
15792 'secondary-selection)
15793 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
15794 (org-overlay-display org-tags-overlay (concat prefix s)))))
15796 (defun org-fast-tag-selection (current inherited table &optional todo-table)
15797 "Fast tag selection with single keys.
15798 CURRENT is the current list of tags in the headline, INHERITED is the
15799 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
15800 possibly with grouping information. TODO-TABLE is a similar table with
15801 TODO keywords, should these have keys assigned to them.
15802 If the keys are nil, a-z are automatically assigned.
15803 Returns the new tags string, or nil to not change the current settings."
15804 (let* ((fulltable (append table todo-table))
15805 (maxlen (apply 'max (mapcar
15806 (lambda (x)
15807 (if (stringp (car x)) (string-width (car x)) 0))
15808 fulltable)))
15809 (buf (current-buffer))
15810 (expert (eq org-fast-tag-selection-single-key 'expert))
15811 (buffer-tags nil)
15812 (fwidth (+ maxlen 3 1 3))
15813 (ncol (/ (- (window-width) 4) fwidth))
15814 (i-face 'org-done)
15815 (c-face 'org-todo)
15816 tg cnt e c char c1 c2 ntable tbl rtn
15817 ov-start ov-end ov-prefix
15818 (exit-after-next org-fast-tag-selection-single-key)
15819 (done-keywords org-done-keywords)
15820 groups ingroup)
15821 (save-excursion
15822 (beginning-of-line 1)
15823 (if (looking-at
15824 (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
15825 (setq ov-start (match-beginning 1)
15826 ov-end (match-end 1)
15827 ov-prefix "")
15828 (setq ov-start (1- (point-at-eol))
15829 ov-end (1+ ov-start))
15830 (skip-chars-forward "^\n\r")
15831 (setq ov-prefix
15832 (concat
15833 (buffer-substring (1- (point)) (point))
15834 (if (> (current-column) org-tags-column)
15836 (make-string (- org-tags-column (current-column)) ?\ ))))))
15837 (org-move-overlay org-tags-overlay ov-start ov-end)
15838 (save-window-excursion
15839 (if expert
15840 (set-buffer (get-buffer-create " *Org tags*"))
15841 (delete-other-windows)
15842 (split-window-vertically)
15843 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
15844 (erase-buffer)
15845 (org-set-local 'org-done-keywords done-keywords)
15846 (org-fast-tag-insert "Inherited" inherited i-face "\n")
15847 (org-fast-tag-insert "Current" current c-face "\n\n")
15848 (org-fast-tag-show-exit exit-after-next)
15849 (org-set-current-tags-overlay current ov-prefix)
15850 (setq tbl fulltable char ?a cnt 0)
15851 (while (setq e (pop tbl))
15852 (cond
15853 ((equal e '(:startgroup))
15854 (push '() groups) (setq ingroup t)
15855 (when (not (= cnt 0))
15856 (setq cnt 0)
15857 (insert "\n"))
15858 (insert "{ "))
15859 ((equal e '(:endgroup))
15860 (setq ingroup nil cnt 0)
15861 (insert "}\n"))
15863 (setq tg (car e) c2 nil)
15864 (if (cdr e)
15865 (setq c (cdr e))
15866 ;; automatically assign a character.
15867 (setq c1 (string-to-char
15868 (downcase (substring
15869 tg (if (= (string-to-char tg) ?@) 1 0)))))
15870 (if (or (rassoc c1 ntable) (rassoc c1 table))
15871 (while (or (rassoc char ntable) (rassoc char table))
15872 (setq char (1+ char)))
15873 (setq c2 c1))
15874 (setq c (or c2 char)))
15875 (if ingroup (push tg (car groups)))
15876 (setq tg (org-add-props tg nil 'face
15877 (cond
15878 ((not (assoc tg table))
15879 (org-get-todo-face tg))
15880 ((member tg current) c-face)
15881 ((member tg inherited) i-face)
15882 (t nil))))
15883 (if (and (= cnt 0) (not ingroup)) (insert " "))
15884 (insert "[" c "] " tg (make-string
15885 (- fwidth 4 (length tg)) ?\ ))
15886 (push (cons tg c) ntable)
15887 (when (= (setq cnt (1+ cnt)) ncol)
15888 (insert "\n")
15889 (if ingroup (insert " "))
15890 (setq cnt 0)))))
15891 (setq ntable (nreverse ntable))
15892 (insert "\n")
15893 (goto-char (point-min))
15894 (if (and (not expert) (fboundp 'fit-window-to-buffer))
15895 (fit-window-to-buffer))
15896 (setq rtn
15897 (catch 'exit
15898 (while t
15899 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free%s%s"
15900 (if groups " [!] no groups" " [!]groups")
15901 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
15902 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
15903 (cond
15904 ((= c ?\r) (throw 'exit t))
15905 ((= c ?!)
15906 (setq groups (not groups))
15907 (goto-char (point-min))
15908 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
15909 ((= c ?\C-c)
15910 (if (not expert)
15911 (org-fast-tag-show-exit
15912 (setq exit-after-next (not exit-after-next)))
15913 (setq expert nil)
15914 (delete-other-windows)
15915 (split-window-vertically)
15916 (org-switch-to-buffer-other-window " *Org tags*")
15917 (and (fboundp 'fit-window-to-buffer)
15918 (fit-window-to-buffer))))
15919 ((or (= c ?\C-g)
15920 (and (= c ?q) (not (rassoc c ntable))))
15921 (org-detach-overlay org-tags-overlay)
15922 (setq quit-flag t))
15923 ((= c ?\ )
15924 (setq current nil)
15925 (if exit-after-next (setq exit-after-next 'now)))
15926 ((= c ?\t)
15927 (condition-case nil
15928 (setq tg (completing-read
15929 "Tag: "
15930 (or buffer-tags
15931 (with-current-buffer buf
15932 (org-get-buffer-tags)))))
15933 (quit (setq tg "")))
15934 (when (string-match "\\S-" tg)
15935 (add-to-list 'buffer-tags (list tg))
15936 (if (member tg current)
15937 (setq current (delete tg current))
15938 (push tg current)))
15939 (if exit-after-next (setq exit-after-next 'now)))
15940 ((setq e (rassoc c todo-table) tg (car e))
15941 (with-current-buffer buf
15942 (save-excursion (org-todo tg)))
15943 (if exit-after-next (setq exit-after-next 'now)))
15944 ((setq e (rassoc c ntable) tg (car e))
15945 (if (member tg current)
15946 (setq current (delete tg current))
15947 (loop for g in groups do
15948 (if (member tg g)
15949 (mapc (lambda (x)
15950 (setq current (delete x current)))
15951 g)))
15952 (push tg current))
15953 (if exit-after-next (setq exit-after-next 'now))))
15955 ;; Create a sorted list
15956 (setq current
15957 (sort current
15958 (lambda (a b)
15959 (assoc b (cdr (memq (assoc a ntable) ntable))))))
15960 (if (eq exit-after-next 'now) (throw 'exit t))
15961 (goto-char (point-min))
15962 (beginning-of-line 2)
15963 (delete-region (point) (point-at-eol))
15964 (org-fast-tag-insert "Current" current c-face)
15965 (org-set-current-tags-overlay current ov-prefix)
15966 (while (re-search-forward
15967 (org-re "\\[.\\] \\([[:alnum:]_@]+\\)") nil t)
15968 (setq tg (match-string 1))
15969 (add-text-properties
15970 (match-beginning 1) (match-end 1)
15971 (list 'face
15972 (cond
15973 ((member tg current) c-face)
15974 ((member tg inherited) i-face)
15975 (t (get-text-property (match-beginning 1) 'face))))))
15976 (goto-char (point-min)))))
15977 (org-detach-overlay org-tags-overlay)
15978 (if rtn
15979 (mapconcat 'identity current ":")
15980 nil))))
15982 (defun org-get-tags-string ()
15983 "Get the TAGS string in the current headline."
15984 (unless (org-on-heading-p t)
15985 (error "Not on a heading"))
15986 (save-excursion
15987 (beginning-of-line 1)
15988 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
15989 (org-match-string-no-properties 1)
15990 "")))
15992 (defun org-get-tags ()
15993 "Get the list of tags specified in the current headline."
15994 (org-split-string (org-get-tags-string) ":"))
15996 (defun org-get-buffer-tags ()
15997 "Get a table of all tags used in the buffer, for completion."
15998 (let (tags)
15999 (save-excursion
16000 (goto-char (point-min))
16001 (while (re-search-forward
16002 (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t\r\n]") nil t)
16003 (when (equal (char-after (point-at-bol 0)) ?*)
16004 (mapc (lambda (x) (add-to-list 'tags x))
16005 (org-split-string (org-match-string-no-properties 1) ":")))))
16006 (mapcar 'list tags)))
16009 ;;;; Properties
16011 ;;; Setting and retrieving properties
16013 (defconst org-special-properties
16014 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "PRIORITY"
16015 "TIMESTAMP" "TIMESTAMP_IA")
16016 "The special properties valid in Org-mode.
16018 These are properties that are not defined in the property drawer,
16019 but in some other way.")
16021 (defconst org-default-properties
16022 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION"
16023 "LOCATION" "LOGGING" "COLUMNS")
16024 "Some properties that are used by Org-mode for various purposes.
16025 Being in this list makes sure that they are offered for completion.")
16027 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
16028 "Regular expression matching the first line of a property drawer.")
16030 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
16031 "Regular expression matching the first line of a property drawer.")
16033 (defun org-property-action ()
16034 "Do an action on properties."
16035 (interactive)
16036 (let (c)
16037 (org-at-property-p)
16038 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
16039 (setq c (read-char-exclusive))
16040 (cond
16041 ((equal c ?s)
16042 (call-interactively 'org-set-property))
16043 ((equal c ?d)
16044 (call-interactively 'org-delete-property))
16045 ((equal c ?D)
16046 (call-interactively 'org-delete-property-globally))
16047 ((equal c ?c)
16048 (call-interactively 'org-compute-property-at-point))
16049 (t (error "No such property action %c" c)))))
16051 (defun org-at-property-p ()
16052 "Is the cursor in a property line?"
16053 ;; FIXME: Does not check if we are actually in the drawer.
16054 ;; FIXME: also returns true on any drawers.....
16055 ;; This is used by C-c C-c for property action.
16056 (save-excursion
16057 (beginning-of-line 1)
16058 (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))))
16060 (defmacro org-with-point-at (pom &rest body)
16061 "Move to buffer and point of point-or-marker POM for the duration of BODY."
16062 (declare (indent 1) (debug t))
16063 `(save-excursion
16064 (if (markerp pom) (set-buffer (marker-buffer pom)))
16065 (save-excursion
16066 (goto-char (or pom (point)))
16067 ,@body)))
16069 (defun org-get-property-block (&optional beg end force)
16070 "Return the (beg . end) range of the body of the property drawer.
16071 BEG and END can be beginning and end of subtree, if not given
16072 they will be found.
16073 If the drawer does not exist and FORCE is non-nil, create the drawer."
16074 (catch 'exit
16075 (save-excursion
16076 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
16077 (end (or end (progn (outline-next-heading) (point)))))
16078 (goto-char beg)
16079 (if (re-search-forward org-property-start-re end t)
16080 (setq beg (1+ (match-end 0)))
16081 (if force
16082 (save-excursion
16083 (org-insert-property-drawer)
16084 (setq end (progn (outline-next-heading) (point))))
16085 (throw 'exit nil))
16086 (goto-char beg)
16087 (if (re-search-forward org-property-start-re end t)
16088 (setq beg (1+ (match-end 0)))))
16089 (if (re-search-forward org-property-end-re end t)
16090 (setq end (match-beginning 0))
16091 (or force (throw 'exit nil))
16092 (goto-char beg)
16093 (setq end beg)
16094 (org-indent-line-function)
16095 (insert ":END:\n"))
16096 (cons beg end)))))
16098 (defun org-entry-properties (&optional pom which)
16099 "Get all properties of the entry at point-or-marker POM.
16100 This includes the TODO keyword, the tags, time strings for deadline,
16101 scheduled, and clocking, and any additional properties defined in the
16102 entry. The return value is an alist, keys may occur multiple times
16103 if the property key was used several times.
16104 POM may also be nil, in which case the current entry is used.
16105 If WHICH is nil or `all', get all properties. If WHICH is
16106 `special' or `standard', only get that subclass."
16107 (setq which (or which 'all))
16108 (org-with-point-at pom
16109 (let ((clockstr (substring org-clock-string 0 -1))
16110 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY"))
16111 beg end range props sum-props key value string clocksum)
16112 (save-excursion
16113 (when (condition-case nil (org-back-to-heading t) (error nil))
16114 (setq beg (point))
16115 (setq sum-props (get-text-property (point) 'org-summaries))
16116 (setq clocksum (get-text-property (point) :org-clock-minutes))
16117 (outline-next-heading)
16118 (setq end (point))
16119 (when (memq which '(all special))
16120 ;; Get the special properties, like TODO and tags
16121 (goto-char beg)
16122 (when (and (looking-at org-todo-line-regexp) (match-end 2))
16123 (push (cons "TODO" (org-match-string-no-properties 2)) props))
16124 (when (looking-at org-priority-regexp)
16125 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
16126 (when (and (setq value (org-get-tags-string))
16127 (string-match "\\S-" value))
16128 (push (cons "TAGS" value) props))
16129 (when (setq value (org-get-tags-at))
16130 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":") ":"))
16131 props))
16132 (while (re-search-forward org-maybe-keyword-time-regexp end t)
16133 (setq key (if (match-end 1) (substring (org-match-string-no-properties 1) 0 -1))
16134 string (if (equal key clockstr)
16135 (org-no-properties
16136 (org-trim
16137 (buffer-substring
16138 (match-beginning 3) (goto-char (point-at-eol)))))
16139 (substring (org-match-string-no-properties 3) 1 -1)))
16140 (unless key
16141 (if (= (char-after (match-beginning 3)) ?\[)
16142 (setq key "TIMESTAMP_IA")
16143 (setq key "TIMESTAMP")))
16144 (when (or (equal key clockstr) (not (assoc key props)))
16145 (push (cons key string) props)))
16149 (when (memq which '(all standard))
16150 ;; Get the standard properties, like :PORP: ...
16151 (setq range (org-get-property-block beg end))
16152 (when range
16153 (goto-char (car range))
16154 (while (re-search-forward
16155 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
16156 (cdr range) t)
16157 (setq key (org-match-string-no-properties 1)
16158 value (org-trim (or (org-match-string-no-properties 2) "")))
16159 (unless (member key excluded)
16160 (push (cons key (or value "")) props)))))
16161 (if clocksum
16162 (push (cons "CLOCKSUM"
16163 (org-column-number-to-string (/ (float clocksum) 60.)
16164 'add_times))
16165 props))
16166 (append sum-props (nreverse props)))))))
16168 (defun org-entry-get (pom property &optional inherit)
16169 "Get value of PROPERTY for entry at point-or-marker POM.
16170 If INHERIT is non-nil and the entry does not have the property,
16171 then also check higher levels of the hierarchy.
16172 If the property is present but empty, the return value is the empty string.
16173 If the property is not present at all, nil is returned."
16174 (org-with-point-at pom
16175 (if inherit
16176 (org-entry-get-with-inheritance property)
16177 (if (member property org-special-properties)
16178 ;; We need a special property. Use brute force, get all properties.
16179 (cdr (assoc property (org-entry-properties nil 'special)))
16180 (let ((range (org-get-property-block)))
16181 (if (and range
16182 (goto-char (car range))
16183 (re-search-forward
16184 (concat "^[ \t]*:" property ":[ \t]*\\(.*\\S-\\)?")
16185 (cdr range) t))
16186 ;; Found the property, return it.
16187 (if (match-end 1)
16188 (org-match-string-no-properties 1)
16189 "")))))))
16191 (defun org-entry-delete (pom property)
16192 "Delete the property PROPERTY from entry at point-or-marker POM."
16193 (org-with-point-at pom
16194 (if (member property org-special-properties)
16195 nil ; cannot delete these properties.
16196 (let ((range (org-get-property-block)))
16197 (if (and range
16198 (goto-char (car range))
16199 (re-search-forward
16200 (concat "^[ \t]*:" property ":[ \t]*\\(.*\\S-\\)")
16201 (cdr range) t))
16202 (progn
16203 (delete-region (match-beginning 0) (1+ (point-at-eol)))
16205 nil)))))
16207 ;; Multi-values properties are properties that contain multiple values
16208 ;; These values are assumed to be single words, separated by whitespace.
16209 (defun org-entry-add-to-multivalued-property (pom property value)
16210 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
16211 (let* ((old (org-entry-get pom property))
16212 (values (and old (org-split-string old "[ \t]"))))
16213 (unless (member value values)
16214 (setq values (cons value values))
16215 (org-entry-put pom property
16216 (mapconcat 'identity values " ")))))
16218 (defun org-entry-remove-from-multivalued-property (pom property value)
16219 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
16220 (let* ((old (org-entry-get pom property))
16221 (values (and old (org-split-string old "[ \t]"))))
16222 (when (member value values)
16223 (setq values (delete value values))
16224 (org-entry-put pom property
16225 (mapconcat 'identity values " ")))))
16227 (defun org-entry-member-in-multivalued-property (pom property value)
16228 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
16229 (let* ((old (org-entry-get pom property))
16230 (values (and old (org-split-string old "[ \t]"))))
16231 (member value values)))
16233 (defvar org-entry-property-inherited-from (make-marker))
16235 (defun org-entry-get-with-inheritance (property)
16236 "Get entry property, and search higher levels if not present."
16237 (let (tmp)
16238 (save-excursion
16239 (save-restriction
16240 (widen)
16241 (catch 'ex
16242 (while t
16243 (when (setq tmp (org-entry-get nil property))
16244 (org-back-to-heading t)
16245 (move-marker org-entry-property-inherited-from (point))
16246 (throw 'ex tmp))
16247 (or (org-up-heading-safe) (throw 'ex nil)))))
16248 (or tmp (cdr (assoc property org-local-properties))
16249 (cdr (assoc property org-global-properties))))))
16251 (defun org-entry-put (pom property value)
16252 "Set PROPERTY to VALUE for entry at point-or-marker POM."
16253 (org-with-point-at pom
16254 (org-back-to-heading t)
16255 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
16256 range)
16257 (cond
16258 ((equal property "TODO")
16259 (when (and (stringp value) (string-match "\\S-" value)
16260 (not (member value org-todo-keywords-1)))
16261 (error "\"%s\" is not a valid TODO state" value))
16262 (if (or (not value)
16263 (not (string-match "\\S-" value)))
16264 (setq value 'none))
16265 (org-todo value)
16266 (org-set-tags nil 'align))
16267 ((equal property "PRIORITY")
16268 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
16269 (string-to-char value) ?\ ))
16270 (org-set-tags nil 'align))
16271 ((equal property "SCHEDULED")
16272 (if (re-search-forward org-scheduled-time-regexp end t)
16273 (cond
16274 ((eq value 'earlier) (org-timestamp-change -1 'day))
16275 ((eq value 'later) (org-timestamp-change 1 'day))
16276 (t (call-interactively 'org-schedule)))
16277 (call-interactively 'org-schedule)))
16278 ((equal property "DEADLINE")
16279 (if (re-search-forward org-deadline-time-regexp end t)
16280 (cond
16281 ((eq value 'earlier) (org-timestamp-change -1 'day))
16282 ((eq value 'later) (org-timestamp-change 1 'day))
16283 (t (call-interactively 'org-deadline)))
16284 (call-interactively 'org-deadline)))
16285 ((member property org-special-properties)
16286 (error "The %s property can not yet be set with `org-entry-put'"
16287 property))
16288 (t ; a non-special property
16289 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
16290 (setq range (org-get-property-block beg end 'force))
16291 (goto-char (car range))
16292 (if (re-search-forward
16293 (concat "^[ \t]*:" property ":\\(.*\\)") (cdr range) t)
16294 (progn
16295 (delete-region (match-beginning 1) (match-end 1))
16296 (goto-char (match-beginning 1)))
16297 (goto-char (cdr range))
16298 (insert "\n")
16299 (backward-char 1)
16300 (org-indent-line-function)
16301 (insert ":" property ":"))
16302 (and value (insert " " value))
16303 (org-indent-line-function)))))))
16305 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
16306 "Get all property keys in the current buffer.
16307 With INCLUDE-SPECIALS, also list the special properties that relect things
16308 like tags and TODO state.
16309 With INCLUDE-DEFAULTS, also include properties that has special meaning
16310 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING.
16311 With INCLUDE-COLUMNS, also include property names given in COLUMN
16312 formats in the current buffer."
16313 (let (rtn range cfmt cols s p)
16314 (save-excursion
16315 (save-restriction
16316 (widen)
16317 (goto-char (point-min))
16318 (while (re-search-forward org-property-start-re nil t)
16319 (setq range (org-get-property-block))
16320 (goto-char (car range))
16321 (while (re-search-forward
16322 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
16323 (cdr range) t)
16324 (add-to-list 'rtn (org-match-string-no-properties 1)))
16325 (outline-next-heading))))
16327 (when include-specials
16328 (setq rtn (append org-special-properties rtn)))
16330 (when include-defaults
16331 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties))
16333 (when include-columns
16334 (save-excursion
16335 (save-restriction
16336 (widen)
16337 (goto-char (point-min))
16338 (while (re-search-forward
16339 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
16340 nil t)
16341 (setq cfmt (match-string 2) s 0)
16342 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
16343 cfmt s)
16344 (setq s (match-end 0)
16345 p (match-string 1 cfmt))
16346 (unless (or (equal p "ITEM")
16347 (member p org-special-properties))
16348 (add-to-list 'rtn (match-string 1 cfmt))))))))
16350 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
16352 (defun org-property-values (key)
16353 "Return a list of all values of property KEY."
16354 (save-excursion
16355 (save-restriction
16356 (widen)
16357 (goto-char (point-min))
16358 (let ((re (concat "^[ \t]*:" key ":[ \t]*\\(\\S-.*\\)"))
16359 values)
16360 (while (re-search-forward re nil t)
16361 (add-to-list 'values (org-trim (match-string 1))))
16362 (delete "" values)))))
16364 (defun org-insert-property-drawer ()
16365 "Insert a property drawer into the current entry."
16366 (interactive)
16367 (org-back-to-heading t)
16368 (looking-at outline-regexp)
16369 (let ((indent (- (match-end 0)(match-beginning 0)))
16370 (beg (point))
16371 (re (concat "^[ \t]*" org-keyword-time-regexp))
16372 end hiddenp)
16373 (outline-next-heading)
16374 (setq end (point))
16375 (goto-char beg)
16376 (while (re-search-forward re end t))
16377 (setq hiddenp (org-invisible-p))
16378 (end-of-line 1)
16379 (and (equal (char-after) ?\n) (forward-char 1))
16380 (org-skip-over-state-notes)
16381 (skip-chars-backward " \t\n\r")
16382 (if (eq (char-before) ?*) (forward-char 1))
16383 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
16384 (beginning-of-line 0)
16385 (indent-to-column indent)
16386 (beginning-of-line 2)
16387 (indent-to-column indent)
16388 (beginning-of-line 0)
16389 (if hiddenp
16390 (save-excursion
16391 (org-back-to-heading t)
16392 (hide-entry))
16393 (org-flag-drawer t))))
16395 (defun org-set-property (property value)
16396 "In the current entry, set PROPERTY to VALUE.
16397 When called interactively, this will prompt for a property name, offering
16398 completion on existing and default properties. And then it will prompt
16399 for a value, offering competion either on allowed values (via an inherited
16400 xxx_ALL property) or on existing values in other instances of this property
16401 in the current file."
16402 (interactive
16403 (let* ((prop (completing-read
16404 "Property: " (mapcar 'list (org-buffer-property-keys nil t t))))
16405 (cur (org-entry-get nil prop))
16406 (allowed (org-property-get-allowed-values nil prop 'table))
16407 (existing (mapcar 'list (org-property-values prop)))
16408 (val (if allowed
16409 (completing-read "Value: " allowed nil 'req-match)
16410 (completing-read
16411 (concat "Value" (if (and cur (string-match "\\S-" cur))
16412 (concat "[" cur "]") "")
16413 ": ")
16414 existing nil nil "" nil cur))))
16415 (list prop (if (equal val "") cur val))))
16416 (unless (equal (org-entry-get nil property) value)
16417 (org-entry-put nil property value)))
16419 (defun org-delete-property (property)
16420 "In the current entry, delete PROPERTY."
16421 (interactive
16422 (let* ((prop (completing-read
16423 "Property: " (org-entry-properties nil 'standard))))
16424 (list prop)))
16425 (message "Property %s %s" property
16426 (if (org-entry-delete nil property)
16427 "deleted"
16428 "was not present in the entry")))
16430 (defun org-delete-property-globally (property)
16431 "Remove PROPERTY globally, from all entries."
16432 (interactive
16433 (let* ((prop (completing-read
16434 "Globally remove property: "
16435 (mapcar 'list (org-buffer-property-keys)))))
16436 (list prop)))
16437 (save-excursion
16438 (save-restriction
16439 (widen)
16440 (goto-char (point-min))
16441 (let ((cnt 0))
16442 (while (re-search-forward
16443 (concat "^[ \t]*:" (regexp-quote property) ":.*\n?")
16444 nil t)
16445 (setq cnt (1+ cnt))
16446 (replace-match ""))
16447 (message "Property \"%s\" removed from %d entries" property cnt)))))
16449 (defvar org-columns-current-fmt-compiled) ; defined below
16451 (defun org-compute-property-at-point ()
16452 "Compute the property at point.
16453 This looks for an enclosing column format, extracts the operator and
16454 then applies it to the proerty in the column format's scope."
16455 (interactive)
16456 (unless (org-at-property-p)
16457 (error "Not at a property"))
16458 (let ((prop (org-match-string-no-properties 2)))
16459 (org-columns-get-format-and-top-level)
16460 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
16461 (error "No operator defined for property %s" prop))
16462 (org-columns-compute prop)))
16464 (defun org-property-get-allowed-values (pom property &optional table)
16465 "Get allowed values for the property PROPERTY.
16466 When TABLE is non-nil, return an alist that can directly be used for
16467 completion."
16468 (let (vals)
16469 (cond
16470 ((equal property "TODO")
16471 (setq vals (org-with-point-at pom
16472 (append org-todo-keywords-1 '("")))))
16473 ((equal property "PRIORITY")
16474 (let ((n org-lowest-priority))
16475 (while (>= n org-highest-priority)
16476 (push (char-to-string n) vals)
16477 (setq n (1- n)))))
16478 ((member property org-special-properties))
16480 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
16482 (when (and vals (string-match "\\S-" vals))
16483 (setq vals (car (read-from-string (concat "(" vals ")"))))
16484 (setq vals (mapcar (lambda (x)
16485 (cond ((stringp x) x)
16486 ((numberp x) (number-to-string x))
16487 ((symbolp x) (symbol-name x))
16488 (t "???")))
16489 vals)))))
16490 (if table (mapcar 'list vals) vals)))
16492 (defun org-property-previous-allowed-value (&optional previous)
16493 "Switch to the next allowed value for this property."
16494 (interactive)
16495 (org-property-next-allowed-value t))
16497 (defun org-property-next-allowed-value (&optional previous)
16498 "Switch to the next allowed value for this property."
16499 (interactive)
16500 (unless (org-at-property-p)
16501 (error "Not at a property"))
16502 (let* ((key (match-string 2))
16503 (value (match-string 3))
16504 (allowed (or (org-property-get-allowed-values (point) key)
16505 (and (member value '("[ ]" "[-]" "[X]"))
16506 '("[ ]" "[X]"))))
16507 nval)
16508 (unless allowed
16509 (error "Allowed values for this property have not been defined"))
16510 (if previous (setq allowed (reverse allowed)))
16511 (if (member value allowed)
16512 (setq nval (car (cdr (member value allowed)))))
16513 (setq nval (or nval (car allowed)))
16514 (if (equal nval value)
16515 (error "Only one allowed value for this property"))
16516 (org-at-property-p)
16517 (replace-match (concat " :" key ": " nval) t t)
16518 (org-indent-line-function)
16519 (beginning-of-line 1)
16520 (skip-chars-forward " \t")))
16522 (defun org-find-entry-with-id (ident)
16523 "Locate the entry that contains the ID property with exact value IDENT.
16524 IDENT can be a string, a symbol or a number, this function will search for
16525 the string representation of it.
16526 Return the position where this entry starts, or nil if there is no such entry."
16527 (let ((id (cond
16528 ((stringp ident) ident)
16529 ((symbol-name ident) (symbol-name ident))
16530 ((numberp ident) (number-to-string ident))
16531 (t (error "IDENT %s must be a string, symbol or number" ident))))
16532 (case-fold-search nil))
16533 (save-excursion
16534 (save-restriction
16535 (widen)
16536 (goto-char (point-min))
16537 (when (re-search-forward
16538 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
16539 nil t)
16540 (org-back-to-heading)
16541 (point))))))
16543 ;;; Column View
16545 (defvar org-columns-overlays nil
16546 "Holds the list of current column overlays.")
16548 (defvar org-columns-current-fmt nil
16549 "Local variable, holds the currently active column format.")
16550 (defvar org-columns-current-fmt-compiled nil
16551 "Local variable, holds the currently active column format.
16552 This is the compiled version of the format.")
16553 (defvar org-columns-current-widths nil
16554 "Loval variable, holds the currently widths of fields.")
16555 (defvar org-columns-current-maxwidths nil
16556 "Loval variable, holds the currently active maximum column widths.")
16557 (defvar org-columns-begin-marker (make-marker)
16558 "Points to the position where last a column creation command was called.")
16559 (defvar org-columns-top-level-marker (make-marker)
16560 "Points to the position where current columns region starts.")
16562 (defvar org-columns-map (make-sparse-keymap)
16563 "The keymap valid in column display.")
16565 (defun org-columns-content ()
16566 "Switch to contents view while in columns view."
16567 (interactive)
16568 (org-overview)
16569 (org-content))
16571 (org-defkey org-columns-map "c" 'org-columns-content)
16572 (org-defkey org-columns-map "o" 'org-overview)
16573 (org-defkey org-columns-map "e" 'org-columns-edit-value)
16574 (org-defkey org-columns-map "\C-c\C-t" 'org-columns-todo)
16575 (org-defkey org-columns-map "\C-c\C-c" 'org-columns-set-tags-or-toggle)
16576 (org-defkey org-columns-map "\C-c\C-o" 'org-columns-open-link)
16577 (org-defkey org-columns-map "v" 'org-columns-show-value)
16578 (org-defkey org-columns-map "q" 'org-columns-quit)
16579 (org-defkey org-columns-map "r" 'org-columns-redo)
16580 (org-defkey org-columns-map "g" 'org-columns-redo)
16581 (org-defkey org-columns-map [left] 'backward-char)
16582 (org-defkey org-columns-map "\M-b" 'backward-char)
16583 (org-defkey org-columns-map "a" 'org-columns-edit-allowed)
16584 (org-defkey org-columns-map "s" 'org-columns-edit-attributes)
16585 (org-defkey org-columns-map "\M-f" (lambda () (interactive) (goto-char (1+ (point)))))
16586 (org-defkey org-columns-map [right] (lambda () (interactive) (goto-char (1+ (point)))))
16587 (org-defkey org-columns-map [(shift right)] 'org-columns-next-allowed-value)
16588 (org-defkey org-columns-map "n" 'org-columns-next-allowed-value)
16589 (org-defkey org-columns-map [(shift left)] 'org-columns-previous-allowed-value)
16590 (org-defkey org-columns-map "p" 'org-columns-previous-allowed-value)
16591 (org-defkey org-columns-map "<" 'org-columns-narrow)
16592 (org-defkey org-columns-map ">" 'org-columns-widen)
16593 (org-defkey org-columns-map [(meta right)] 'org-columns-move-right)
16594 (org-defkey org-columns-map [(meta left)] 'org-columns-move-left)
16595 (org-defkey org-columns-map [(shift meta right)] 'org-columns-new)
16596 (org-defkey org-columns-map [(shift meta left)] 'org-columns-delete)
16598 (easy-menu-define org-columns-menu org-columns-map "Org Column Menu"
16599 '("Column"
16600 ["Edit property" org-columns-edit-value t]
16601 ["Next allowed value" org-columns-next-allowed-value t]
16602 ["Previous allowed value" org-columns-previous-allowed-value t]
16603 ["Show full value" org-columns-show-value t]
16604 ["Edit allowed values" org-columns-edit-allowed t]
16605 "--"
16606 ["Edit column attributes" org-columns-edit-attributes t]
16607 ["Increase column width" org-columns-widen t]
16608 ["Decrease column width" org-columns-narrow t]
16609 "--"
16610 ["Move column right" org-columns-move-right t]
16611 ["Move column left" org-columns-move-left t]
16612 ["Add column" org-columns-new t]
16613 ["Delete column" org-columns-delete t]
16614 "--"
16615 ["CONTENTS" org-columns-content t]
16616 ["OVERVIEW" org-overview t]
16617 ["Refresh columns display" org-columns-redo t]
16618 "--"
16619 ["Open link" org-columns-open-link t]
16620 "--"
16621 ["Quit" org-columns-quit t]))
16623 (defun org-columns-new-overlay (beg end &optional string face)
16624 "Create a new column overlay and add it to the list."
16625 (let ((ov (org-make-overlay beg end)))
16626 (org-overlay-put ov 'face (or face 'secondary-selection))
16627 (org-overlay-display ov string face)
16628 (push ov org-columns-overlays)
16629 ov))
16631 (defun org-columns-display-here (&optional props)
16632 "Overlay the current line with column display."
16633 (interactive)
16634 (let* ((fmt org-columns-current-fmt-compiled)
16635 (beg (point-at-bol))
16636 (level-face (save-excursion
16637 (beginning-of-line 1)
16638 (and (looking-at "\\(\\**\\)\\(\\* \\)")
16639 (org-get-level-face 2))))
16640 (color (list :foreground
16641 (face-attribute (or level-face 'default) :foreground)))
16642 props pom property ass width f string ov column val modval)
16643 ;; Check if the entry is in another buffer.
16644 (unless props
16645 (if (eq major-mode 'org-agenda-mode)
16646 (setq pom (or (get-text-property (point) 'org-hd-marker)
16647 (get-text-property (point) 'org-marker))
16648 props (if pom (org-entry-properties pom) nil))
16649 (setq props (org-entry-properties nil))))
16650 ;; Walk the format
16651 (while (setq column (pop fmt))
16652 (setq property (car column)
16653 ass (if (equal property "ITEM")
16654 (cons "ITEM"
16655 (save-match-data
16656 (org-no-properties
16657 (org-remove-tabs
16658 (buffer-substring-no-properties
16659 (point-at-bol) (point-at-eol))))))
16660 (assoc property props))
16661 width (or (cdr (assoc property org-columns-current-maxwidths))
16662 (nth 2 column)
16663 (length property))
16664 f (format "%%-%d.%ds | " width width)
16665 val (or (cdr ass) "")
16666 modval (if (equal property "ITEM")
16667 (org-columns-cleanup-item val org-columns-current-fmt-compiled))
16668 string (format f (or modval val)))
16669 ;; Create the overlay
16670 (org-unmodified
16671 (setq ov (org-columns-new-overlay
16672 beg (setq beg (1+ beg)) string
16673 (list color 'org-column)))
16674 ;;; (list (get-text-property (point-at-bol) 'face) 'org-column)))
16675 (org-overlay-put ov 'keymap org-columns-map)
16676 (org-overlay-put ov 'org-columns-key property)
16677 (org-overlay-put ov 'org-columns-value (cdr ass))
16678 (org-overlay-put ov 'org-columns-value-modified modval)
16679 (org-overlay-put ov 'org-columns-pom pom)
16680 (org-overlay-put ov 'org-columns-format f))
16681 (if (or (not (char-after beg))
16682 (equal (char-after beg) ?\n))
16683 (let ((inhibit-read-only t))
16684 (save-excursion
16685 (goto-char beg)
16686 (org-unmodified (insert " ")))))) ;; FIXME: add props and remove later?
16687 ;; Make the rest of the line disappear.
16688 (org-unmodified
16689 (setq ov (org-columns-new-overlay beg (point-at-eol)))
16690 (org-overlay-put ov 'invisible t)
16691 (org-overlay-put ov 'keymap org-columns-map)
16692 (org-overlay-put ov 'intangible t)
16693 (push ov org-columns-overlays)
16694 (setq ov (org-make-overlay (1- (point-at-eol)) (1+ (point-at-eol))))
16695 (org-overlay-put ov 'keymap org-columns-map)
16696 (push ov org-columns-overlays)
16697 (let ((inhibit-read-only t))
16698 (put-text-property (max (point-min) (1- (point-at-bol)))
16699 (min (point-max) (1+ (point-at-eol)))
16700 'read-only "Type `e' to edit property")))))
16702 (defvar org-previous-header-line-format nil
16703 "The header line format before column view was turned on.")
16704 (defvar org-columns-inhibit-recalculation nil
16705 "Inhibit recomputing of columns on column view startup.")
16708 (defvar header-line-format)
16709 (defun org-columns-display-here-title ()
16710 "Overlay the newline before the current line with the table title."
16711 (interactive)
16712 (let ((fmt org-columns-current-fmt-compiled)
16713 string (title "")
16714 property width f column str widths)
16715 (while (setq column (pop fmt))
16716 (setq property (car column)
16717 str (or (nth 1 column) property)
16718 width (or (cdr (assoc property org-columns-current-maxwidths))
16719 (nth 2 column)
16720 (length str))
16721 widths (push width widths)
16722 f (format "%%-%d.%ds | " width width)
16723 string (format f str)
16724 title (concat title string)))
16725 (setq title (concat
16726 (org-add-props " " nil 'display '(space :align-to 0))
16727 (org-add-props title nil 'face '(:weight bold :underline t))))
16728 (org-set-local 'org-previous-header-line-format header-line-format)
16729 (org-set-local 'org-columns-current-widths (nreverse widths))
16730 (setq header-line-format title)))
16732 (defun org-columns-remove-overlays ()
16733 "Remove all currently active column overlays."
16734 (interactive)
16735 (when (marker-buffer org-columns-begin-marker)
16736 (with-current-buffer (marker-buffer org-columns-begin-marker)
16737 (when (local-variable-p 'org-previous-header-line-format)
16738 (setq header-line-format org-previous-header-line-format)
16739 (kill-local-variable 'org-previous-header-line-format))
16740 (move-marker org-columns-begin-marker nil)
16741 (move-marker org-columns-top-level-marker nil)
16742 (org-unmodified
16743 (mapc 'org-delete-overlay org-columns-overlays)
16744 (setq org-columns-overlays nil)
16745 (let ((inhibit-read-only t))
16746 (remove-text-properties (point-min) (point-max) '(read-only t)))))))
16748 (defun org-columns-cleanup-item (item fmt)
16749 "Remove from ITEM what is a column in the format FMT."
16750 (if (not org-complex-heading-regexp)
16751 item
16752 (when (string-match org-complex-heading-regexp item)
16753 (concat
16754 (org-add-props (concat (match-string 1 item) " ") nil
16755 'org-whitespace (* 2 (1- (org-reduced-level (- (match-end 1) (match-beginning 1))))))
16756 (and (match-end 2) (not (assoc "TODO" fmt)) (concat " " (match-string 2 item)))
16757 (and (match-end 3) (not (assoc "PRIORITY" fmt)) (concat " " (match-string 3 item)))
16758 " " (match-string 4 item)
16759 (and (match-end 5) (not (assoc "TAGS" fmt)) (concat " " (match-string 5 item)))))))
16761 (defun org-columns-show-value ()
16762 "Show the full value of the property."
16763 (interactive)
16764 (let ((value (get-char-property (point) 'org-columns-value)))
16765 (message "Value is: %s" (or value ""))))
16767 (defun org-columns-quit ()
16768 "Remove the column overlays and in this way exit column editing."
16769 (interactive)
16770 (org-unmodified
16771 (org-columns-remove-overlays)
16772 (let ((inhibit-read-only t))
16773 (remove-text-properties (point-min) (point-max) '(read-only t))))
16774 (when (eq major-mode 'org-agenda-mode)
16775 (message
16776 "Modification not yet reflected in Agenda buffer, use `r' to refresh")))
16778 (defun org-columns-check-computed ()
16779 "Check if this column value is computed.
16780 If yes, throw an error indicating that changing it does not make sense."
16781 (let ((val (get-char-property (point) 'org-columns-value)))
16782 (when (and (stringp val)
16783 (get-char-property 0 'org-computed val))
16784 (error "This value is computed from the entry's children"))))
16786 (defun org-columns-todo (&optional arg)
16787 "Change the TODO state during column view."
16788 (interactive "P")
16789 (org-columns-edit-value "TODO"))
16791 (defun org-columns-set-tags-or-toggle (&optional arg)
16792 "Toggle checkbox at point, or set tags for current headline."
16793 (interactive "P")
16794 (if (string-match "\\`\\[[ xX-]\\]\\'"
16795 (get-char-property (point) 'org-columns-value))
16796 (org-columns-next-allowed-value)
16797 (org-columns-edit-value "TAGS")))
16799 (defun org-columns-edit-value (&optional key)
16800 "Edit the value of the property at point in column view.
16801 Where possible, use the standard interface for changing this line."
16802 (interactive)
16803 (org-columns-check-computed)
16804 (let* ((external-key key)
16805 (col (current-column))
16806 (key (or key (get-char-property (point) 'org-columns-key)))
16807 (value (get-char-property (point) 'org-columns-value))
16808 (bol (point-at-bol)) (eol (point-at-eol))
16809 (pom (or (get-text-property bol 'org-hd-marker)
16810 (point))) ; keep despite of compiler waring
16811 (line-overlays
16812 (delq nil (mapcar (lambda (x)
16813 (and (eq (overlay-buffer x) (current-buffer))
16814 (>= (overlay-start x) bol)
16815 (<= (overlay-start x) eol)
16817 org-columns-overlays)))
16818 nval eval allowed)
16819 (cond
16820 ((equal key "CLOCKSUM")
16821 (error "This special column cannot be edited"))
16822 ((equal key "ITEM")
16823 (setq eval '(org-with-point-at pom
16824 (org-edit-headline))))
16825 ((equal key "TODO")
16826 (setq eval '(org-with-point-at pom
16827 (let ((current-prefix-arg
16828 (if external-key current-prefix-arg '(4))))
16829 (call-interactively 'org-todo)))))
16830 ((equal key "PRIORITY")
16831 (setq eval '(org-with-point-at pom
16832 (call-interactively 'org-priority))))
16833 ((equal key "TAGS")
16834 (setq eval '(org-with-point-at pom
16835 (let ((org-fast-tag-selection-single-key
16836 (if (eq org-fast-tag-selection-single-key 'expert)
16837 t org-fast-tag-selection-single-key)))
16838 (call-interactively 'org-set-tags)))))
16839 ((equal key "DEADLINE")
16840 (setq eval '(org-with-point-at pom
16841 (call-interactively 'org-deadline))))
16842 ((equal key "SCHEDULED")
16843 (setq eval '(org-with-point-at pom
16844 (call-interactively 'org-schedule))))
16846 (setq allowed (org-property-get-allowed-values pom key 'table))
16847 (if allowed
16848 (setq nval (completing-read "Value: " allowed nil t))
16849 (setq nval (read-string "Edit: " value)))
16850 (setq nval (org-trim nval))
16851 (when (not (equal nval value))
16852 (setq eval '(org-entry-put pom key nval)))))
16853 (when eval
16854 (let ((inhibit-read-only t))
16855 (remove-text-properties (max (point-min) (1- bol)) eol '(read-only t))
16856 (unwind-protect
16857 (progn
16858 (setq org-columns-overlays
16859 (org-delete-all line-overlays org-columns-overlays))
16860 (mapc 'org-delete-overlay line-overlays)
16861 (org-columns-eval eval))
16862 (org-columns-display-here))))
16863 (move-to-column col)
16864 (if (and (org-mode-p)
16865 (nth 3 (assoc key org-columns-current-fmt-compiled)))
16866 (org-columns-update key))))
16868 (defun org-edit-headline () ; FIXME: this is not columns specific
16869 "Edit the current headline, the part without TODO keyword, TAGS."
16870 (org-back-to-heading)
16871 (when (looking-at org-todo-line-regexp)
16872 (let ((pre (buffer-substring (match-beginning 0) (match-beginning 3)))
16873 (txt (match-string 3))
16874 (post "")
16875 txt2)
16876 (if (string-match (org-re "[ \t]+:[[:alnum:]:_@]+:[ \t]*$") txt)
16877 (setq post (match-string 0 txt)
16878 txt (substring txt 0 (match-beginning 0))))
16879 (setq txt2 (read-string "Edit: " txt))
16880 (when (not (equal txt txt2))
16881 (beginning-of-line 1)
16882 (insert pre txt2 post)
16883 (delete-region (point) (point-at-eol))
16884 (org-set-tags nil t)))))
16886 (defun org-columns-edit-allowed ()
16887 "Edit the list of allowed values for the current property."
16888 (interactive)
16889 (let* ((key (get-char-property (point) 'org-columns-key))
16890 (key1 (concat key "_ALL"))
16891 (allowed (org-entry-get (point) key1 t))
16892 nval)
16893 ;; FIXME: Cover editing TODO, TAGS etc in-buffer settings.????
16894 (setq nval (read-string "Allowed: " allowed))
16895 (org-entry-put
16896 (cond ((marker-position org-entry-property-inherited-from)
16897 org-entry-property-inherited-from)
16898 ((marker-position org-columns-top-level-marker)
16899 org-columns-top-level-marker))
16900 key1 nval)))
16902 (defmacro org-no-warnings (&rest body)
16903 (cons (if (fboundp 'with-no-warnings) 'with-no-warnings 'progn) body))
16905 (defun org-columns-eval (form)
16906 (let (hidep)
16907 (save-excursion
16908 (beginning-of-line 1)
16909 ;; `next-line' is needed here, because it skips invisible line.
16910 (condition-case nil (org-no-warnings (next-line 1)) (error nil))
16911 (setq hidep (org-on-heading-p 1)))
16912 (eval form)
16913 (and hidep (hide-entry))))
16915 (defun org-columns-previous-allowed-value ()
16916 "Switch to the previous allowed value for this column."
16917 (interactive)
16918 (org-columns-next-allowed-value t))
16920 (defun org-columns-next-allowed-value (&optional previous)
16921 "Switch to the next allowed value for this column."
16922 (interactive)
16923 (org-columns-check-computed)
16924 (let* ((col (current-column))
16925 (key (get-char-property (point) 'org-columns-key))
16926 (value (get-char-property (point) 'org-columns-value))
16927 (bol (point-at-bol)) (eol (point-at-eol))
16928 (pom (or (get-text-property bol 'org-hd-marker)
16929 (point))) ; keep despite of compiler waring
16930 (line-overlays
16931 (delq nil (mapcar (lambda (x)
16932 (and (eq (overlay-buffer x) (current-buffer))
16933 (>= (overlay-start x) bol)
16934 (<= (overlay-start x) eol)
16936 org-columns-overlays)))
16937 (allowed (or (org-property-get-allowed-values pom key)
16938 (and (memq
16939 (nth 4 (assoc key org-columns-current-fmt-compiled))
16940 '(checkbox checkbox-n-of-m checkbox-percent))
16941 '("[ ]" "[X]"))))
16942 nval)
16943 (when (equal key "ITEM")
16944 (error "Cannot edit item headline from here"))
16945 (unless (or allowed (member key '("SCHEDULED" "DEADLINE")))
16946 (error "Allowed values for this property have not been defined"))
16947 (if (member key '("SCHEDULED" "DEADLINE"))
16948 (setq nval (if previous 'earlier 'later))
16949 (if previous (setq allowed (reverse allowed)))
16950 (if (member value allowed)
16951 (setq nval (car (cdr (member value allowed)))))
16952 (setq nval (or nval (car allowed)))
16953 (if (equal nval value)
16954 (error "Only one allowed value for this property")))
16955 (let ((inhibit-read-only t))
16956 (remove-text-properties (1- bol) eol '(read-only t))
16957 (unwind-protect
16958 (progn
16959 (setq org-columns-overlays
16960 (org-delete-all line-overlays org-columns-overlays))
16961 (mapc 'org-delete-overlay line-overlays)
16962 (org-columns-eval '(org-entry-put pom key nval)))
16963 (org-columns-display-here)))
16964 (move-to-column col)
16965 (if (and (org-mode-p)
16966 (nth 3 (assoc key org-columns-current-fmt-compiled)))
16967 (org-columns-update key))))
16969 (defun org-verify-version (task)
16970 (cond
16971 ((eq task 'columns)
16972 (if (or (featurep 'xemacs)
16973 (< emacs-major-version 22))
16974 (error "Emacs 22 is required for the columns feature")))))
16976 (defun org-columns-open-link (&optional arg)
16977 (interactive "P")
16978 (let ((value (get-char-property (point) 'org-columns-value)))
16979 (org-open-link-from-string value arg)))
16981 (defun org-open-link-from-string (s &optional arg)
16982 "Open a link in the string S, as if it was in Org-mode."
16983 (interactive)
16984 (with-temp-buffer
16985 (let ((org-inhibit-startup t))
16986 (org-mode)
16987 (insert s)
16988 (goto-char (point-min))
16989 (org-open-at-point arg))))
16991 (defun org-columns-get-format-and-top-level ()
16992 (let (fmt)
16993 (when (condition-case nil (org-back-to-heading) (error nil))
16994 (move-marker org-entry-property-inherited-from nil)
16995 (setq fmt (org-entry-get nil "COLUMNS" t)))
16996 (setq fmt (or fmt org-columns-default-format))
16997 (org-set-local 'org-columns-current-fmt fmt)
16998 (org-columns-compile-format fmt)
16999 (if (marker-position org-entry-property-inherited-from)
17000 (move-marker org-columns-top-level-marker
17001 org-entry-property-inherited-from)
17002 (move-marker org-columns-top-level-marker (point)))
17003 fmt))
17005 (defun org-columns ()
17006 "Turn on column view on an org-mode file."
17007 (interactive)
17008 (org-verify-version 'columns)
17009 (org-columns-remove-overlays)
17010 (move-marker org-columns-begin-marker (point))
17011 (let (beg end fmt cache maxwidths)
17012 (setq fmt (org-columns-get-format-and-top-level))
17013 (save-excursion
17014 (goto-char org-columns-top-level-marker)
17015 (setq beg (point))
17016 (unless org-columns-inhibit-recalculation
17017 (org-columns-compute-all))
17018 (setq end (or (condition-case nil (org-end-of-subtree t t) (error nil))
17019 (point-max)))
17020 ;; Get and cache the properties
17021 (goto-char beg)
17022 (when (assoc "CLOCKSUM" org-columns-current-fmt-compiled)
17023 (save-excursion
17024 (save-restriction
17025 (narrow-to-region beg end)
17026 (org-clock-sum))))
17027 (while (re-search-forward (concat "^" outline-regexp) end t)
17028 (push (cons (org-current-line) (org-entry-properties)) cache))
17029 (when cache
17030 (setq maxwidths (org-columns-get-autowidth-alist fmt cache))
17031 (org-set-local 'org-columns-current-maxwidths maxwidths)
17032 (org-columns-display-here-title)
17033 (mapc (lambda (x)
17034 (goto-line (car x))
17035 (org-columns-display-here (cdr x)))
17036 cache)))))
17038 (defun org-columns-new (&optional prop title width op fmt &rest rest)
17039 "Insert a new column, to the leeft o the current column."
17040 (interactive)
17041 (let ((editp (and prop (assoc prop org-columns-current-fmt-compiled)))
17042 cell)
17043 (setq prop (completing-read
17044 "Property: " (mapcar 'list (org-buffer-property-keys t nil t))
17045 nil nil prop))
17046 (setq title (read-string (concat "Column title [" prop "]: ") (or title prop)))
17047 (setq width (read-string "Column width: " (if width (number-to-string width))))
17048 (if (string-match "\\S-" width)
17049 (setq width (string-to-number width))
17050 (setq width nil))
17051 (setq fmt (completing-read "Summary [none]: "
17052 '(("none") ("add_numbers") ("currency") ("add_times") ("checkbox") ("checkbox-n-of-m") ("checkbox-percent"))
17053 nil t))
17054 (if (string-match "\\S-" fmt)
17055 (setq fmt (intern fmt))
17056 (setq fmt nil))
17057 (if (eq fmt 'none) (setq fmt nil))
17058 (if editp
17059 (progn
17060 (setcar editp prop)
17061 (setcdr editp (list title width nil fmt)))
17062 (setq cell (nthcdr (1- (current-column))
17063 org-columns-current-fmt-compiled))
17064 (setcdr cell (cons (list prop title width nil fmt)
17065 (cdr cell))))
17066 (org-columns-store-format)
17067 (org-columns-redo)))
17069 (defun org-columns-delete ()
17070 "Delete the column at point from columns view."
17071 (interactive)
17072 (let* ((n (current-column))
17073 (title (nth 1 (nth n org-columns-current-fmt-compiled))))
17074 (when (y-or-n-p
17075 (format "Are you sure you want to remove column \"%s\"? " title))
17076 (setq org-columns-current-fmt-compiled
17077 (delq (nth n org-columns-current-fmt-compiled)
17078 org-columns-current-fmt-compiled))
17079 (org-columns-store-format)
17080 (org-columns-redo)
17081 (if (>= (current-column) (length org-columns-current-fmt-compiled))
17082 (backward-char 1)))))
17084 (defun org-columns-edit-attributes ()
17085 "Edit the attributes of the current column."
17086 (interactive)
17087 (let* ((n (current-column))
17088 (info (nth n org-columns-current-fmt-compiled)))
17089 (apply 'org-columns-new info)))
17091 (defun org-columns-widen (arg)
17092 "Make the column wider by ARG characters."
17093 (interactive "p")
17094 (let* ((n (current-column))
17095 (entry (nth n org-columns-current-fmt-compiled))
17096 (width (or (nth 2 entry)
17097 (cdr (assoc (car entry) org-columns-current-maxwidths)))))
17098 (setq width (max 1 (+ width arg)))
17099 (setcar (nthcdr 2 entry) width)
17100 (org-columns-store-format)
17101 (org-columns-redo)))
17103 (defun org-columns-narrow (arg)
17104 "Make the column nrrower by ARG characters."
17105 (interactive "p")
17106 (org-columns-widen (- arg)))
17108 (defun org-columns-move-right ()
17109 "Swap this column with the one to the right."
17110 (interactive)
17111 (let* ((n (current-column))
17112 (cell (nthcdr n org-columns-current-fmt-compiled))
17114 (when (>= n (1- (length org-columns-current-fmt-compiled)))
17115 (error "Cannot shift this column further to the right"))
17116 (setq e (car cell))
17117 (setcar cell (car (cdr cell)))
17118 (setcdr cell (cons e (cdr (cdr cell))))
17119 (org-columns-store-format)
17120 (org-columns-redo)
17121 (forward-char 1)))
17123 (defun org-columns-move-left ()
17124 "Swap this column with the one to the left."
17125 (interactive)
17126 (let* ((n (current-column)))
17127 (when (= n 0)
17128 (error "Cannot shift this column further to the left"))
17129 (backward-char 1)
17130 (org-columns-move-right)
17131 (backward-char 1)))
17133 (defun org-columns-store-format ()
17134 "Store the text version of the current columns format in appropriate place.
17135 This is either in the COLUMNS property of the node starting the current column
17136 display, or in the #+COLUMNS line of the current buffer."
17137 (let (fmt (cnt 0))
17138 (setq fmt (org-columns-uncompile-format org-columns-current-fmt-compiled))
17139 (org-set-local 'org-columns-current-fmt fmt)
17140 (if (marker-position org-columns-top-level-marker)
17141 (save-excursion
17142 (goto-char org-columns-top-level-marker)
17143 (if (and (org-at-heading-p)
17144 (org-entry-get nil "COLUMNS"))
17145 (org-entry-put nil "COLUMNS" fmt)
17146 (goto-char (point-min))
17147 ;; Overwrite all #+COLUMNS lines....
17148 (while (re-search-forward "^#\\+COLUMNS:.*" nil t)
17149 (setq cnt (1+ cnt))
17150 (replace-match (concat "#+COLUMNS: " fmt) t t))
17151 (unless (> cnt 0)
17152 (goto-char (point-min))
17153 (or (org-on-heading-p t) (outline-next-heading))
17154 (let ((inhibit-read-only t))
17155 (insert-before-markers "#+COLUMNS: " fmt "\n")))
17156 (org-set-local 'org-columns-default-format fmt))))))
17158 (defvar org-overriding-columns-format nil
17159 "When set, overrides any other definition.")
17160 (defvar org-agenda-view-columns-initially nil
17161 "When set, switch to columns view immediately after creating the agenda.")
17163 (defun org-agenda-columns ()
17164 "Turn on column view in the agenda."
17165 (interactive)
17166 (org-verify-version 'columns)
17167 (org-columns-remove-overlays)
17168 (move-marker org-columns-begin-marker (point))
17169 (let (fmt cache maxwidths m)
17170 (cond
17171 ((and (local-variable-p 'org-overriding-columns-format)
17172 org-overriding-columns-format)
17173 (setq fmt org-overriding-columns-format))
17174 ((setq m (get-text-property (point-at-bol) 'org-hd-marker))
17175 (setq fmt (org-entry-get m "COLUMNS" t)))
17176 ((and (boundp 'org-columns-current-fmt)
17177 (local-variable-p 'org-columns-current-fmt)
17178 org-columns-current-fmt)
17179 (setq fmt org-columns-current-fmt))
17180 ((setq m (next-single-property-change (point-min) 'org-hd-marker))
17181 (setq m (get-text-property m 'org-hd-marker))
17182 (setq fmt (org-entry-get m "COLUMNS" t))))
17183 (setq fmt (or fmt org-columns-default-format))
17184 (org-set-local 'org-columns-current-fmt fmt)
17185 (org-columns-compile-format fmt)
17186 (save-excursion
17187 ;; Get and cache the properties
17188 (goto-char (point-min))
17189 (while (not (eobp))
17190 (when (setq m (or (get-text-property (point) 'org-hd-marker)
17191 (get-text-property (point) 'org-marker)))
17192 (push (cons (org-current-line) (org-entry-properties m)) cache))
17193 (beginning-of-line 2))
17194 (when cache
17195 (setq maxwidths (org-columns-get-autowidth-alist fmt cache))
17196 (org-set-local 'org-columns-current-maxwidths maxwidths)
17197 (org-columns-display-here-title)
17198 (mapc (lambda (x)
17199 (goto-line (car x))
17200 (org-columns-display-here (cdr x)))
17201 cache)))))
17203 (defun org-columns-get-autowidth-alist (s cache)
17204 "Derive the maximum column widths from the format and the cache."
17205 (let ((start 0) rtn)
17206 (while (string-match (org-re "%\\([[:alpha:]][[:alnum:]_-]*\\)") s start)
17207 (push (cons (match-string 1 s) 1) rtn)
17208 (setq start (match-end 0)))
17209 (mapc (lambda (x)
17210 (setcdr x (apply 'max
17211 (mapcar
17212 (lambda (y)
17213 (length (or (cdr (assoc (car x) (cdr y))) " ")))
17214 cache))))
17215 rtn)
17216 rtn))
17218 (defun org-columns-compute-all ()
17219 "Compute all columns that have operators defined."
17220 (org-unmodified
17221 (remove-text-properties (point-min) (point-max) '(org-summaries t)))
17222 (let ((columns org-columns-current-fmt-compiled) col)
17223 (while (setq col (pop columns))
17224 (when (nth 3 col)
17225 (save-excursion
17226 (org-columns-compute (car col)))))))
17228 (defun org-columns-update (property)
17229 "Recompute PROPERTY, and update the columns display for it."
17230 (org-columns-compute property)
17231 (let (fmt val pos)
17232 (save-excursion
17233 (mapc (lambda (ov)
17234 (when (equal (org-overlay-get ov 'org-columns-key) property)
17235 (setq pos (org-overlay-start ov))
17236 (goto-char pos)
17237 (when (setq val (cdr (assoc property
17238 (get-text-property
17239 (point-at-bol) 'org-summaries))))
17240 (setq fmt (org-overlay-get ov 'org-columns-format))
17241 (org-overlay-put ov 'org-columns-value val)
17242 (org-overlay-put ov 'display (format fmt val)))))
17243 org-columns-overlays))))
17245 (defun org-columns-compute (property)
17246 "Sum the values of property PROPERTY hierarchically, for the entire buffer."
17247 (interactive)
17248 (let* ((re (concat "^" outline-regexp))
17249 (lmax 30) ; Does anyone use deeper levels???
17250 (lsum (make-vector lmax 0))
17251 (lflag (make-vector lmax nil))
17252 (level 0)
17253 (ass (assoc property org-columns-current-fmt-compiled))
17254 (format (nth 4 ass))
17255 (printf (nth 5 ass))
17256 (beg org-columns-top-level-marker)
17257 last-level val valflag flag end sumpos sum-alist sum str str1 useval)
17258 (save-excursion
17259 ;; Find the region to compute
17260 (goto-char beg)
17261 (setq end (condition-case nil (org-end-of-subtree t) (error (point-max))))
17262 (goto-char end)
17263 ;; Walk the tree from the back and do the computations
17264 (while (re-search-backward re beg t)
17265 (setq sumpos (match-beginning 0)
17266 last-level level
17267 level (org-outline-level)
17268 val (org-entry-get nil property)
17269 valflag (and val (string-match "\\S-" val)))
17270 (cond
17271 ((< level last-level)
17272 ;; put the sum of lower levels here as a property
17273 (setq sum (aref lsum last-level) ; current sum
17274 flag (aref lflag last-level) ; any valid entries from children?
17275 str (org-column-number-to-string sum format printf)
17276 str1 (org-add-props (copy-sequence str) nil 'org-computed t 'face 'bold)
17277 useval (if flag str1 (if valflag val ""))
17278 sum-alist (get-text-property sumpos 'org-summaries))
17279 (if (assoc property sum-alist)
17280 (setcdr (assoc property sum-alist) useval)
17281 (push (cons property useval) sum-alist)
17282 (org-unmodified
17283 (add-text-properties sumpos (1+ sumpos)
17284 (list 'org-summaries sum-alist))))
17285 (when val
17286 (org-entry-put nil property (if flag str val)))
17287 ;; add current to current level accumulator
17288 (when (or flag valflag)
17289 (aset lsum level (+ (aref lsum level)
17290 (if flag sum (org-column-string-to-number
17291 (if flag str val) format))))
17292 (aset lflag level t))
17293 ;; clear accumulators for deeper levels
17294 (loop for l from (1+ level) to (1- lmax) do
17295 (aset lsum l 0)
17296 (aset lflag l nil)))
17297 ((>= level last-level)
17298 ;; add what we have here to the accumulator for this level
17299 (aset lsum level (+ (aref lsum level)
17300 (org-column-string-to-number (or val "0") format)))
17301 (and valflag (aset lflag level t)))
17302 (t (error "This should not happen")))))))
17304 (defun org-columns-redo ()
17305 "Construct the column display again."
17306 (interactive)
17307 (message "Recomputing columns...")
17308 (save-excursion
17309 (if (marker-position org-columns-begin-marker)
17310 (goto-char org-columns-begin-marker))
17311 (org-columns-remove-overlays)
17312 (if (org-mode-p)
17313 (call-interactively 'org-columns)
17314 (call-interactively 'org-agenda-columns)))
17315 (message "Recomputing columns...done"))
17317 (defun org-columns-not-in-agenda ()
17318 (if (eq major-mode 'org-agenda-mode)
17319 (error "This command is only allowed in Org-mode buffers")))
17322 (defun org-string-to-number (s)
17323 "Convert string to number, and interpret hh:mm:ss."
17324 (if (not (string-match ":" s))
17325 (string-to-number s)
17326 (let ((l (nreverse (org-split-string s ":"))) (sum 0.0))
17327 (while l
17328 (setq sum (+ (string-to-number (pop l)) (/ sum 60))))
17329 sum)))
17331 (defun org-column-number-to-string (n fmt &optional printf)
17332 "Convert a computed column number to a string value, according to FMT."
17333 (cond
17334 ((eq fmt 'add_times)
17335 (let* ((h (floor n)) (m (floor (+ 0.5 (* 60 (- n h))))))
17336 (format "%d:%02d" h m)))
17337 ((eq fmt 'checkbox)
17338 (cond ((= n (floor n)) "[X]")
17339 ((> n 1.) "[-]")
17340 (t "[ ]")))
17341 ((memq fmt '(checkbox-n-of-m checkbox-percent))
17342 (let* ((n1 (floor n)) (n2 (floor (+ .5 (* 1000000 (- n n1))))))
17343 (org-nofm-to-completion n1 (+ n2 n1) (eq fmt 'checkbox-percent))))
17344 (printf (format printf n))
17345 ((eq fmt 'currency)
17346 (format "%.2f" n))
17347 (t (number-to-string n))))
17349 (defun org-nofm-to-completion (n m &optional percent)
17350 (if (not percent)
17351 (format "[%d/%d]" n m)
17352 (format "[%d%%]"(floor (+ 0.5 (* 100. (/ (* 1.0 n) m)))))))
17354 (defun org-column-string-to-number (s fmt)
17355 "Convert a column value to a number that can be used for column computing."
17356 (cond
17357 ((string-match ":" s)
17358 (let ((l (nreverse (org-split-string s ":"))) (sum 0.0))
17359 (while l
17360 (setq sum (+ (string-to-number (pop l)) (/ sum 60))))
17361 sum))
17362 ((memq fmt '(checkbox checkbox-n-of-m checkbox-percent))
17363 (if (equal s "[X]") 1. 0.000001))
17364 (t (string-to-number s))))
17366 (defun org-columns-uncompile-format (cfmt)
17367 "Turn the compiled columns format back into a string representation."
17368 (let ((rtn "") e s prop title op width fmt printf)
17369 (while (setq e (pop cfmt))
17370 (setq prop (car e)
17371 title (nth 1 e)
17372 width (nth 2 e)
17373 op (nth 3 e)
17374 fmt (nth 4 e)
17375 printf (nth 5 e))
17376 (cond
17377 ((eq fmt 'add_times) (setq op ":"))
17378 ((eq fmt 'checkbox) (setq op "X"))
17379 ((eq fmt 'checkbox-n-of-m) (setq op "X/"))
17380 ((eq fmt 'checkbox-percent) (setq op "X%"))
17381 ((eq fmt 'add_numbers) (setq op "+"))
17382 ((eq fmt 'currency) (setq op "$")))
17383 (if (and op printf) (setq op (concat op ";" printf)))
17384 (if (equal title prop) (setq title nil))
17385 (setq s (concat "%" (if width (number-to-string width))
17386 prop
17387 (if title (concat "(" title ")"))
17388 (if op (concat "{" op "}"))))
17389 (setq rtn (concat rtn " " s)))
17390 (org-trim rtn)))
17392 (defun org-columns-compile-format (fmt)
17393 "Turn a column format string into an alist of specifications.
17394 The alist has one entry for each column in the format. The elements of
17395 that list are:
17396 property the property
17397 title the title field for the columns
17398 width the column width in characters, can be nil for automatic
17399 operator the operator if any
17400 format the output format for computed results, derived from operator
17401 printf a printf format for computed values"
17402 (let ((start 0) width prop title op f printf)
17403 (setq org-columns-current-fmt-compiled nil)
17404 (while (string-match
17405 (org-re "%\\([0-9]+\\)?\\([[:alnum:]_-]+\\)\\(?:(\\([^)]+\\))\\)?\\(?:{\\([^}]+\\)}\\)?\\s-*")
17406 fmt start)
17407 (setq start (match-end 0)
17408 width (match-string 1 fmt)
17409 prop (match-string 2 fmt)
17410 title (or (match-string 3 fmt) prop)
17411 op (match-string 4 fmt)
17412 f nil
17413 printf nil)
17414 (if width (setq width (string-to-number width)))
17415 (when (and op (string-match ";" op))
17416 (setq printf (substring op (match-end 0))
17417 op (substring op 0 (match-beginning 0))))
17418 (cond
17419 ((equal op "+") (setq f 'add_numbers))
17420 ((equal op "$") (setq f 'currency))
17421 ((equal op ":") (setq f 'add_times))
17422 ((equal op "X") (setq f 'checkbox))
17423 ((equal op "X/") (setq f 'checkbox-n-of-m))
17424 ((equal op "X%") (setq f 'checkbox-percent))
17426 (push (list prop title width op f printf) org-columns-current-fmt-compiled))
17427 (setq org-columns-current-fmt-compiled
17428 (nreverse org-columns-current-fmt-compiled))))
17431 ;;; Dynamic block for Column view
17433 (defun org-columns-capture-view ()
17434 "Get the column view of the current buffer and return it as a list.
17435 The list will contains the title row and all other rows. Each row is
17436 a list of fields."
17437 (save-excursion
17438 (let* ((title (mapcar 'cadr org-columns-current-fmt-compiled))
17439 (n (length title)) row tbl)
17440 (goto-char (point-min))
17441 (while (re-search-forward "^\\*+ " nil t)
17442 (when (get-char-property (match-beginning 0) 'org-columns-key)
17443 (setq row nil)
17444 (loop for i from 0 to (1- n) do
17445 (push (or (get-char-property (+ (match-beginning 0) i) 'org-columns-value-modified)
17446 (get-char-property (+ (match-beginning 0) i) 'org-columns-value)
17448 row))
17449 (setq row (nreverse row))
17450 (push row tbl)))
17451 (append (list title 'hline) (nreverse tbl)))))
17453 (defun org-dblock-write:columnview (params)
17454 "Write the column view table.
17455 PARAMS is a property list of parameters:
17457 :width enforce same column widths with <N> specifiers.
17458 :id the :ID: property of the entry where the columns view
17459 should be built, as a string. When `local', call locally.
17460 When `global' call column view with the cursor at the beginning
17461 of the buffer (usually this means that the whole buffer switches
17462 to column view).
17463 :hlines When t, insert a hline before each item. When a number, insert
17464 a hline before each level <= that number.
17465 :vlines When t, make each column a colgroup to enforce vertical lines."
17466 (let ((pos (move-marker (make-marker) (point)))
17467 (hlines (plist-get params :hlines))
17468 (vlines (plist-get params :vlines))
17469 tbl id idpos nfields tmp)
17470 (save-excursion
17471 (save-restriction
17472 (when (setq id (plist-get params :id))
17473 (cond ((not id) nil)
17474 ((eq id 'global) (goto-char (point-min)))
17475 ((eq id 'local) nil)
17476 ((setq idpos (org-find-entry-with-id id))
17477 (goto-char idpos))
17478 (t (error "Cannot find entry with :ID: %s" id))))
17479 (org-columns)
17480 (setq tbl (org-columns-capture-view))
17481 (setq nfields (length (car tbl)))
17482 (org-columns-quit)))
17483 (goto-char pos)
17484 (move-marker pos nil)
17485 (when tbl
17486 (when (plist-get params :hlines)
17487 (setq tmp nil)
17488 (while tbl
17489 (if (eq (car tbl) 'hline)
17490 (push (pop tbl) tmp)
17491 (if (string-match "\\` *\\(\\*+\\)" (caar tbl))
17492 (if (and (not (eq (car tmp) 'hline))
17493 (or (eq hlines t)
17494 (and (numberp hlines) (<= (- (match-end 1) (match-beginning 1)) hlines))))
17495 (push 'hline tmp)))
17496 (push (pop tbl) tmp)))
17497 (setq tbl (nreverse tmp)))
17498 (when vlines
17499 (setq tbl (mapcar (lambda (x)
17500 (if (eq 'hline x) x (cons "" x)))
17501 tbl))
17502 (setq tbl (append tbl (list (cons "/" (make-list nfields "<>"))))))
17503 (setq pos (point))
17504 (insert (org-listtable-to-string tbl))
17505 (when (plist-get params :width)
17506 (insert "\n|" (mapconcat (lambda (x) (format "<%d>" (max 3 x)))
17507 org-columns-current-widths "|")))
17508 (goto-char pos)
17509 (org-table-align))))
17511 (defun org-listtable-to-string (tbl)
17512 "Convert a listtable TBL to a string that contains the Org-mode table.
17513 The table still need to be alligned. The resulting string has no leading
17514 and tailing newline characters."
17515 (mapconcat
17516 (lambda (x)
17517 (cond
17518 ((listp x)
17519 (concat "|" (mapconcat 'identity x "|") "|"))
17520 ((eq x 'hline) "|-|")
17521 (t (error "Garbage in listtable: %s" x))))
17522 tbl "\n"))
17524 (defun org-insert-columns-dblock ()
17525 "Create a dynamic block capturing a column view table."
17526 (interactive)
17527 (let ((defaults '(:name "columnview" :hlines 1))
17528 (id (completing-read
17529 "Capture columns (local, global, entry with :ID: property) [local]: "
17530 (append '(("global") ("local"))
17531 (mapcar 'list (org-property-values "ID"))))))
17532 (if (equal id "") (setq id 'local))
17533 (if (equal id "global") (setq id 'global))
17534 (setq defaults (append defaults (list :id id)))
17535 (org-create-dblock defaults)
17536 (org-update-dblock)))
17538 ;;;; Timestamps
17540 (defvar org-last-changed-timestamp nil)
17541 (defvar org-time-was-given) ; dynamically scoped parameter
17542 (defvar org-end-time-was-given) ; dynamically scoped parameter
17543 (defvar org-ts-what) ; dynamically scoped parameter
17545 (defun org-time-stamp (arg)
17546 "Prompt for a date/time and insert a time stamp.
17547 If the user specifies a time like HH:MM, or if this command is called
17548 with a prefix argument, the time stamp will contain date and time.
17549 Otherwise, only the date will be included. All parts of a date not
17550 specified by the user will be filled in from the current date/time.
17551 So if you press just return without typing anything, the time stamp
17552 will represent the current date/time. If there is already a timestamp
17553 at the cursor, it will be modified."
17554 (interactive "P")
17555 (let* ((ts nil)
17556 (default-time
17557 ;; Default time is either today, or, when entering a range,
17558 ;; the range start.
17559 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
17560 (save-excursion
17561 (re-search-backward
17562 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
17563 (- (point) 20) t)))
17564 (apply 'encode-time (org-parse-time-string (match-string 1)))
17565 (current-time)))
17566 (default-input (and ts (org-get-compact-tod ts)))
17567 org-time-was-given org-end-time-was-given time)
17568 (cond
17569 ((and (org-at-timestamp-p)
17570 (eq last-command 'org-time-stamp)
17571 (eq this-command 'org-time-stamp))
17572 (insert "--")
17573 (setq time (let ((this-command this-command))
17574 (org-read-date arg 'totime nil nil default-time default-input)))
17575 (org-insert-time-stamp time (or org-time-was-given arg)))
17576 ((org-at-timestamp-p)
17577 (setq time (let ((this-command this-command))
17578 (org-read-date arg 'totime nil nil default-time default-input)))
17579 (when (org-at-timestamp-p) ; just to get the match data
17580 (replace-match "")
17581 (setq org-last-changed-timestamp
17582 (org-insert-time-stamp
17583 time (or org-time-was-given arg)
17584 nil nil nil (list org-end-time-was-given))))
17585 (message "Timestamp updated"))
17587 (setq time (let ((this-command this-command))
17588 (org-read-date arg 'totime nil nil default-time default-input)))
17589 (org-insert-time-stamp time (or org-time-was-given arg)
17590 nil nil nil (list org-end-time-was-given))))))
17592 ;; FIXME: can we use this for something else????
17593 ;; like computing time differences?????
17594 (defun org-get-compact-tod (s)
17595 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
17596 (let* ((t1 (match-string 1 s))
17597 (h1 (string-to-number (match-string 2 s)))
17598 (m1 (string-to-number (match-string 3 s)))
17599 (t2 (and (match-end 4) (match-string 5 s)))
17600 (h2 (and t2 (string-to-number (match-string 6 s))))
17601 (m2 (and t2 (string-to-number (match-string 7 s))))
17602 dh dm)
17603 (if (not t2)
17605 (setq dh (- h2 h1) dm (- m2 m1))
17606 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
17607 (concat t1 "+" (number-to-string dh)
17608 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
17610 (defun org-time-stamp-inactive (&optional arg)
17611 "Insert an inactive time stamp.
17612 An inactive time stamp is enclosed in square brackets instead of angle
17613 brackets. It is inactive in the sense that it does not trigger agenda entries,
17614 does not link to the calendar and cannot be changed with the S-cursor keys.
17615 So these are more for recording a certain time/date."
17616 (interactive "P")
17617 (let (org-time-was-given org-end-time-was-given time)
17618 (setq time (org-read-date arg 'totime))
17619 (org-insert-time-stamp time (or org-time-was-given arg) 'inactive
17620 nil nil (list org-end-time-was-given))))
17622 (defvar org-date-ovl (org-make-overlay 1 1))
17623 (org-overlay-put org-date-ovl 'face 'org-warning)
17624 (org-detach-overlay org-date-ovl)
17626 (defvar org-ans1) ; dynamically scoped parameter
17627 (defvar org-ans2) ; dynamically scoped parameter
17629 (defvar org-plain-time-of-day-regexp) ; defined below
17631 (defvar org-read-date-overlay nil)
17632 (defvar org-dcst nil) ; dynamically scoped
17634 (defun org-read-date (&optional with-time to-time from-string prompt
17635 default-time default-input)
17636 "Read a date, possibly a time, and make things smooth for the user.
17637 The prompt will suggest to enter an ISO date, but you can also enter anything
17638 which will at least partially be understood by `parse-time-string'.
17639 Unrecognized parts of the date will default to the current day, month, year,
17640 hour and minute. If this command is called to replace a timestamp at point,
17641 of to enter the second timestamp of a range, the default time is taken from the
17642 existing stamp. For example,
17643 3-2-5 --> 2003-02-05
17644 feb 15 --> currentyear-02-15
17645 sep 12 9 --> 2009-09-12
17646 12:45 --> today 12:45
17647 22 sept 0:34 --> currentyear-09-22 0:34
17648 12 --> currentyear-currentmonth-12
17649 Fri --> nearest Friday (today or later)
17650 etc.
17652 Furthermore you can specify a relative date by giving, as the *first* thing
17653 in the input: a plus/minus sign, a number and a letter [dwmy] to indicate
17654 change in days weeks, months, years.
17655 With a single plus or minus, the date is relative to today. With a double
17656 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
17657 +4d --> four days from today
17658 +4 --> same as above
17659 +2w --> two weeks from today
17660 ++5 --> five days from default date
17662 The function understands only English month and weekday abbreviations,
17663 but this can be configured with the variables `parse-time-months' and
17664 `parse-time-weekdays'.
17666 While prompting, a calendar is popped up - you can also select the
17667 date with the mouse (button 1). The calendar shows a period of three
17668 months. To scroll it to other months, use the keys `>' and `<'.
17669 If you don't like the calendar, turn it off with
17670 \(setq org-read-date-popup-calendar nil)
17672 With optional argument TO-TIME, the date will immediately be converted
17673 to an internal time.
17674 With an optional argument WITH-TIME, the prompt will suggest to also
17675 insert a time. Note that when WITH-TIME is not set, you can still
17676 enter a time, and this function will inform the calling routine about
17677 this change. The calling routine may then choose to change the format
17678 used to insert the time stamp into the buffer to include the time.
17679 With optional argument FROM-STRING, read from this string instead from
17680 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
17681 the time/date that is used for everything that is not specified by the
17682 user."
17683 (require 'parse-time)
17684 (let* ((org-time-stamp-rounding-minutes
17685 (if (equal with-time '(16)) 0 org-time-stamp-rounding-minutes))
17686 (org-dcst org-display-custom-times)
17687 (ct (org-current-time))
17688 (def (or default-time ct))
17689 (defdecode (decode-time def))
17690 (dummy (progn
17691 (when (< (nth 2 defdecode) org-extend-today-until)
17692 (setcar (nthcdr 2 defdecode) -1)
17693 (setcar (nthcdr 1 defdecode) 59)
17694 (setq def (apply 'encode-time defdecode)
17695 defdecode (decode-time def)))))
17696 (calendar-move-hook nil)
17697 (view-diary-entries-initially nil)
17698 (view-calendar-holidays-initially nil)
17699 (timestr (format-time-string
17700 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") def))
17701 (prompt (concat (if prompt (concat prompt " ") "")
17702 (format "Date+time [%s]: " timestr)))
17703 ans (org-ans0 "") org-ans1 org-ans2 final)
17705 (cond
17706 (from-string (setq ans from-string))
17707 (org-read-date-popup-calendar
17708 (save-excursion
17709 (save-window-excursion
17710 (calendar)
17711 (calendar-forward-day (- (time-to-days def)
17712 (calendar-absolute-from-gregorian
17713 (calendar-current-date))))
17714 (org-eval-in-calendar nil t)
17715 (let* ((old-map (current-local-map))
17716 (map (copy-keymap calendar-mode-map))
17717 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
17718 (org-defkey map (kbd "RET") 'org-calendar-select)
17719 (org-defkey map (if (featurep 'xemacs) [button1] [mouse-1])
17720 'org-calendar-select-mouse)
17721 (org-defkey map (if (featurep 'xemacs) [button2] [mouse-2])
17722 'org-calendar-select-mouse)
17723 (org-defkey minibuffer-local-map [(meta shift left)]
17724 (lambda () (interactive)
17725 (org-eval-in-calendar '(calendar-backward-month 1))))
17726 (org-defkey minibuffer-local-map [(meta shift right)]
17727 (lambda () (interactive)
17728 (org-eval-in-calendar '(calendar-forward-month 1))))
17729 (org-defkey minibuffer-local-map [(meta shift up)]
17730 (lambda () (interactive)
17731 (org-eval-in-calendar '(calendar-backward-year 1))))
17732 (org-defkey minibuffer-local-map [(meta shift down)]
17733 (lambda () (interactive)
17734 (org-eval-in-calendar '(calendar-forward-year 1))))
17735 (org-defkey minibuffer-local-map [(shift up)]
17736 (lambda () (interactive)
17737 (org-eval-in-calendar '(calendar-backward-week 1))))
17738 (org-defkey minibuffer-local-map [(shift down)]
17739 (lambda () (interactive)
17740 (org-eval-in-calendar '(calendar-forward-week 1))))
17741 (org-defkey minibuffer-local-map [(shift left)]
17742 (lambda () (interactive)
17743 (org-eval-in-calendar '(calendar-backward-day 1))))
17744 (org-defkey minibuffer-local-map [(shift right)]
17745 (lambda () (interactive)
17746 (org-eval-in-calendar '(calendar-forward-day 1))))
17747 (org-defkey minibuffer-local-map ">"
17748 (lambda () (interactive)
17749 (org-eval-in-calendar '(scroll-calendar-left 1))))
17750 (org-defkey minibuffer-local-map "<"
17751 (lambda () (interactive)
17752 (org-eval-in-calendar '(scroll-calendar-right 1))))
17753 (unwind-protect
17754 (progn
17755 (use-local-map map)
17756 (add-hook 'post-command-hook 'org-read-date-display)
17757 (setq org-ans0 (read-string prompt default-input nil nil))
17758 ;; org-ans0: from prompt
17759 ;; org-ans1: from mouse click
17760 ;; org-ans2: from calendar motion
17761 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
17762 (remove-hook 'post-command-hook 'org-read-date-display)
17763 (use-local-map old-map)
17764 (when org-read-date-overlay
17765 (org-delete-overlay org-read-date-overlay)
17766 (setq org-read-date-overlay nil)))))))
17768 (t ; Naked prompt only
17769 (unwind-protect
17770 (setq ans (read-string prompt default-input nil timestr))
17771 (when org-read-date-overlay
17772 (org-delete-overlay org-read-date-overlay)
17773 (setq org-read-date-overlay nil)))))
17775 (setq final (org-read-date-analyze ans def defdecode))
17777 (if to-time
17778 (apply 'encode-time final)
17779 (if (and (boundp 'org-time-was-given) org-time-was-given)
17780 (format "%04d-%02d-%02d %02d:%02d"
17781 (nth 5 final) (nth 4 final) (nth 3 final)
17782 (nth 2 final) (nth 1 final))
17783 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
17784 (defvar def)
17785 (defvar defdecode)
17786 (defvar with-time)
17787 (defun org-read-date-display ()
17788 "Display the currrent date prompt interpretation in the minibuffer."
17789 (when org-read-date-display-live
17790 (when org-read-date-overlay
17791 (org-delete-overlay org-read-date-overlay))
17792 (let ((p (point)))
17793 (end-of-line 1)
17794 (while (not (equal (buffer-substring
17795 (max (point-min) (- (point) 4)) (point))
17796 " "))
17797 (insert " "))
17798 (goto-char p))
17799 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
17800 " " (or org-ans1 org-ans2)))
17801 (org-end-time-was-given nil)
17802 (f (org-read-date-analyze ans def defdecode))
17803 (fmts (if org-dcst
17804 org-time-stamp-custom-formats
17805 org-time-stamp-formats))
17806 (fmt (if (or with-time
17807 (and (boundp 'org-time-was-given) org-time-was-given))
17808 (cdr fmts)
17809 (car fmts)))
17810 (txt (concat "=> " (format-time-string fmt (apply 'encode-time f)))))
17811 (when (and org-end-time-was-given
17812 (string-match org-plain-time-of-day-regexp txt))
17813 (setq txt (concat (substring txt 0 (match-end 0)) "-"
17814 org-end-time-was-given
17815 (substring txt (match-end 0)))))
17816 (setq org-read-date-overlay
17817 (make-overlay (1- (point-at-eol)) (point-at-eol)))
17818 (org-overlay-display org-read-date-overlay txt 'secondary-selection))))
17820 (defun org-read-date-analyze (ans def defdecode)
17821 "Analyze the combined answer of the date prompt."
17822 ;; FIXME: cleanup and comment
17823 (let (delta deltan deltaw deltadef year month day
17824 hour minute second wday pm h2 m2 tl wday1)
17826 (when (setq delta (org-read-date-get-relative ans (current-time) def))
17827 (setq ans (replace-match "" t t ans)
17828 deltan (car delta)
17829 deltaw (nth 1 delta)
17830 deltadef (nth 2 delta)))
17832 ;; Help matching ISO dates with single digit month ot day, like 2006-8-11.
17833 (when (string-match
17834 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
17835 (setq year (if (match-end 2)
17836 (string-to-number (match-string 2 ans))
17837 (string-to-number (format-time-string "%Y")))
17838 month (string-to-number (match-string 3 ans))
17839 day (string-to-number (match-string 4 ans)))
17840 (if (< year 100) (setq year (+ 2000 year)))
17841 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
17842 t nil ans)))
17843 ;; Help matching am/pm times, because `parse-time-string' does not do that.
17844 ;; If there is a time with am/pm, and *no* time without it, we convert
17845 ;; so that matching will be successful.
17846 (loop for i from 1 to 2 do ; twice, for end time as well
17847 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
17848 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
17849 (setq hour (string-to-number (match-string 1 ans))
17850 minute (if (match-end 3)
17851 (string-to-number (match-string 3 ans))
17853 pm (equal ?p
17854 (string-to-char (downcase (match-string 4 ans)))))
17855 (if (and (= hour 12) (not pm))
17856 (setq hour 0)
17857 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
17858 (setq ans (replace-match (format "%02d:%02d" hour minute)
17859 t t ans))))
17861 ;; Check if a time range is given as a duration
17862 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
17863 (setq hour (string-to-number (match-string 1 ans))
17864 h2 (+ hour (string-to-number (match-string 3 ans)))
17865 minute (string-to-number (match-string 2 ans))
17866 m2 (+ minute (if (match-end 5) (string-to-number (match-string 5 ans))0)))
17867 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
17868 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2) t t ans)))
17870 ;; Check if there is a time range
17871 (when (boundp 'org-end-time-was-given)
17872 (setq org-time-was-given nil)
17873 (when (and (string-match org-plain-time-of-day-regexp ans)
17874 (match-end 8))
17875 (setq org-end-time-was-given (match-string 8 ans))
17876 (setq ans (concat (substring ans 0 (match-beginning 7))
17877 (substring ans (match-end 7))))))
17879 (setq tl (parse-time-string ans)
17880 day (or (nth 3 tl) (nth 3 defdecode))
17881 month (or (nth 4 tl)
17882 (if (and org-read-date-prefer-future
17883 (nth 3 tl) (< (nth 3 tl) (nth 3 defdecode)))
17884 (1+ (nth 4 defdecode))
17885 (nth 4 defdecode)))
17886 year (or (nth 5 tl)
17887 (if (and org-read-date-prefer-future
17888 (nth 4 tl) (< (nth 4 tl) (nth 4 defdecode)))
17889 (1+ (nth 5 defdecode))
17890 (nth 5 defdecode)))
17891 hour (or (nth 2 tl) (nth 2 defdecode))
17892 minute (or (nth 1 tl) (nth 1 defdecode))
17893 second (or (nth 0 tl) 0)
17894 wday (nth 6 tl))
17895 (when deltan
17896 (unless deltadef
17897 (let ((now (decode-time (current-time))))
17898 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
17899 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
17900 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
17901 ((equal deltaw "m") (setq month (+ month deltan)))
17902 ((equal deltaw "y") (setq year (+ year deltan)))))
17903 (when (and wday (not (nth 3 tl)))
17904 ;; Weekday was given, but no day, so pick that day in the week
17905 ;; on or after the derived date.
17906 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
17907 (unless (equal wday wday1)
17908 (setq day (+ day (% (- wday wday1 -7) 7)))))
17909 (if (and (boundp 'org-time-was-given)
17910 (nth 2 tl))
17911 (setq org-time-was-given t))
17912 (if (< year 100) (setq year (+ 2000 year)))
17913 (if (< year 1970) (setq year (nth 5 defdecode))) ; not representable
17914 (list second minute hour day month year)))
17916 (defvar parse-time-weekdays)
17918 (defun org-read-date-get-relative (s today default)
17919 "Check string S for special relative date string.
17920 TODAY and DEFAULT are internal times, for today and for a default.
17921 Return shift list (N what def-flag)
17922 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
17923 N is the number of WHATs to shift.
17924 DEF-FLAG is t when a double ++ or -- indicates shift relative to
17925 the DEFAULT date rather than TODAY."
17926 (when (string-match
17927 (concat
17928 "\\`[ \t]*\\([-+]\\{1,2\\}\\)"
17929 "\\([0-9]+\\)?"
17930 "\\([dwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
17931 "\\([ \t]\\|$\\)") s)
17932 (let* ((dir (if (match-end 1)
17933 (string-to-char (substring (match-string 1 s) -1))
17934 ?+))
17935 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
17936 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
17937 (what (if (match-end 3) (match-string 3 s) "d"))
17938 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
17939 (date (if rel default today))
17940 (wday (nth 6 (decode-time date)))
17941 delta)
17942 (if wday1
17943 (progn
17944 (setq delta (mod (+ 7 (- wday1 wday)) 7))
17945 (if (= dir ?-) (setq delta (- delta 7)))
17946 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
17947 (list delta "d" rel))
17948 (list (* n (if (= dir ?-) -1 1)) what rel)))))
17950 (defun org-eval-in-calendar (form &optional keepdate)
17951 "Eval FORM in the calendar window and return to current window.
17952 Also, store the cursor date in variable org-ans2."
17953 (let ((sw (selected-window)))
17954 (select-window (get-buffer-window "*Calendar*"))
17955 (eval form)
17956 (when (and (not keepdate) (calendar-cursor-to-date))
17957 (let* ((date (calendar-cursor-to-date))
17958 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17959 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
17960 (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
17961 (select-window sw)))
17963 ; ;; Update the prompt to show new default date
17964 ; (save-excursion
17965 ; (goto-char (point-min))
17966 ; (when (and org-ans2
17967 ; (re-search-forward "\\[[-0-9]+\\]" nil t)
17968 ; (get-text-property (match-end 0) 'field))
17969 ; (let ((inhibit-read-only t))
17970 ; (replace-match (concat "[" org-ans2 "]") t t)
17971 ; (add-text-properties (point-min) (1+ (match-end 0))
17972 ; (text-properties-at (1+ (point-min)))))))))
17974 (defun org-calendar-select ()
17975 "Return to `org-read-date' with the date currently selected.
17976 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
17977 (interactive)
17978 (when (calendar-cursor-to-date)
17979 (let* ((date (calendar-cursor-to-date))
17980 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17981 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
17982 (if (active-minibuffer-window) (exit-minibuffer))))
17984 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
17985 "Insert a date stamp for the date given by the internal TIME.
17986 WITH-HM means, use the stamp format that includes the time of the day.
17987 INACTIVE means use square brackets instead of angular ones, so that the
17988 stamp will not contribute to the agenda.
17989 PRE and POST are optional strings to be inserted before and after the
17990 stamp.
17991 The command returns the inserted time stamp."
17992 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
17993 stamp)
17994 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
17995 (insert-before-markers (or pre ""))
17996 (insert-before-markers (setq stamp (format-time-string fmt time)))
17997 (when (listp extra)
17998 (setq extra (car extra))
17999 (if (and (stringp extra)
18000 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
18001 (setq extra (format "-%02d:%02d"
18002 (string-to-number (match-string 1 extra))
18003 (string-to-number (match-string 2 extra))))
18004 (setq extra nil)))
18005 (when extra
18006 (backward-char 1)
18007 (insert-before-markers extra)
18008 (forward-char 1))
18009 (insert-before-markers (or post ""))
18010 stamp))
18012 (defun org-toggle-time-stamp-overlays ()
18013 "Toggle the use of custom time stamp formats."
18014 (interactive)
18015 (setq org-display-custom-times (not org-display-custom-times))
18016 (unless org-display-custom-times
18017 (let ((p (point-min)) (bmp (buffer-modified-p)))
18018 (while (setq p (next-single-property-change p 'display))
18019 (if (and (get-text-property p 'display)
18020 (eq (get-text-property p 'face) 'org-date))
18021 (remove-text-properties
18022 p (setq p (next-single-property-change p 'display))
18023 '(display t))))
18024 (set-buffer-modified-p bmp)))
18025 (if (featurep 'xemacs)
18026 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
18027 (org-restart-font-lock)
18028 (setq org-table-may-need-update t)
18029 (if org-display-custom-times
18030 (message "Time stamps are overlayed with custom format")
18031 (message "Time stamp overlays removed")))
18033 (defun org-display-custom-time (beg end)
18034 "Overlay modified time stamp format over timestamp between BED and END."
18035 (let* ((ts (buffer-substring beg end))
18036 t1 w1 with-hm tf time str w2 (off 0))
18037 (save-match-data
18038 (setq t1 (org-parse-time-string ts t))
18039 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( \\+[0-9]+[dwmy]\\)?\\'" ts)
18040 (setq off (- (match-end 0) (match-beginning 0)))))
18041 (setq end (- end off))
18042 (setq w1 (- end beg)
18043 with-hm (and (nth 1 t1) (nth 2 t1))
18044 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
18045 time (org-fix-decoded-time t1)
18046 str (org-add-props
18047 (format-time-string
18048 (substring tf 1 -1) (apply 'encode-time time))
18049 nil 'mouse-face 'highlight)
18050 w2 (length str))
18051 (if (not (= w2 w1))
18052 (add-text-properties (1+ beg) (+ 2 beg)
18053 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
18054 (if (featurep 'xemacs)
18055 (progn
18056 (put-text-property beg end 'invisible t)
18057 (put-text-property beg end 'end-glyph (make-glyph str)))
18058 (put-text-property beg end 'display str))))
18060 (defun org-translate-time (string)
18061 "Translate all timestamps in STRING to custom format.
18062 But do this only if the variable `org-display-custom-times' is set."
18063 (when org-display-custom-times
18064 (save-match-data
18065 (let* ((start 0)
18066 (re org-ts-regexp-both)
18067 t1 with-hm inactive tf time str beg end)
18068 (while (setq start (string-match re string start))
18069 (setq beg (match-beginning 0)
18070 end (match-end 0)
18071 t1 (save-match-data
18072 (org-parse-time-string (substring string beg end) t))
18073 with-hm (and (nth 1 t1) (nth 2 t1))
18074 inactive (equal (substring string beg (1+ beg)) "[")
18075 tf (funcall (if with-hm 'cdr 'car)
18076 org-time-stamp-custom-formats)
18077 time (org-fix-decoded-time t1)
18078 str (format-time-string
18079 (concat
18080 (if inactive "[" "<") (substring tf 1 -1)
18081 (if inactive "]" ">"))
18082 (apply 'encode-time time))
18083 string (replace-match str t t string)
18084 start (+ start (length str)))))))
18085 string)
18087 (defun org-fix-decoded-time (time)
18088 "Set 0 instead of nil for the first 6 elements of time.
18089 Don't touch the rest."
18090 (let ((n 0))
18091 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
18093 (defun org-days-to-time (timestamp-string)
18094 "Difference between TIMESTAMP-STRING and now in days."
18095 (- (time-to-days (org-time-string-to-time timestamp-string))
18096 (time-to-days (current-time))))
18098 (defun org-deadline-close (timestamp-string &optional ndays)
18099 "Is the time in TIMESTAMP-STRING close to the current date?"
18100 (setq ndays (or ndays (org-get-wdays timestamp-string)))
18101 (and (< (org-days-to-time timestamp-string) ndays)
18102 (not (org-entry-is-done-p))))
18104 (defun org-get-wdays (ts)
18105 "Get the deadline lead time appropriate for timestring TS."
18106 (cond
18107 ((<= org-deadline-warning-days 0)
18108 ;; 0 or negative, enforce this value no matter what
18109 (- org-deadline-warning-days))
18110 ((string-match "-\\([0-9]+\\)\\([dwmy]\\)\\(\\'\\|>\\)" ts)
18111 ;; lead time is specified.
18112 (floor (* (string-to-number (match-string 1 ts))
18113 (cdr (assoc (match-string 2 ts)
18114 '(("d" . 1) ("w" . 7)
18115 ("m" . 30.4) ("y" . 365.25)))))))
18116 ;; go for the default.
18117 (t org-deadline-warning-days)))
18119 (defun org-calendar-select-mouse (ev)
18120 "Return to `org-read-date' with the date currently selected.
18121 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
18122 (interactive "e")
18123 (mouse-set-point ev)
18124 (when (calendar-cursor-to-date)
18125 (let* ((date (calendar-cursor-to-date))
18126 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
18127 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
18128 (if (active-minibuffer-window) (exit-minibuffer))))
18130 (defun org-check-deadlines (ndays)
18131 "Check if there are any deadlines due or past due.
18132 A deadline is considered due if it happens within `org-deadline-warning-days'
18133 days from today's date. If the deadline appears in an entry marked DONE,
18134 it is not shown. The prefix arg NDAYS can be used to test that many
18135 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
18136 (interactive "P")
18137 (let* ((org-warn-days
18138 (cond
18139 ((equal ndays '(4)) 100000)
18140 (ndays (prefix-numeric-value ndays))
18141 (t (abs org-deadline-warning-days))))
18142 (case-fold-search nil)
18143 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
18144 (callback
18145 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
18147 (message "%d deadlines past-due or due within %d days"
18148 (org-occur regexp nil callback)
18149 org-warn-days)))
18151 (defun org-check-before-date (date)
18152 "Check if there are deadlines or scheduled entries before DATE."
18153 (interactive (list (org-read-date)))
18154 (let ((case-fold-search nil)
18155 (regexp (concat "\\<\\(" org-deadline-string
18156 "\\|" org-scheduled-string
18157 "\\) *<\\([^>]+\\)>"))
18158 (callback
18159 (lambda () (time-less-p
18160 (org-time-string-to-time (match-string 2))
18161 (org-time-string-to-time date)))))
18162 (message "%d entries before %s"
18163 (org-occur regexp nil callback) date)))
18165 (defun org-evaluate-time-range (&optional to-buffer)
18166 "Evaluate a time range by computing the difference between start and end.
18167 Normally the result is just printed in the echo area, but with prefix arg
18168 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
18169 If the time range is actually in a table, the result is inserted into the
18170 next column.
18171 For time difference computation, a year is assumed to be exactly 365
18172 days in order to avoid rounding problems."
18173 (interactive "P")
18175 (org-clock-update-time-maybe)
18176 (save-excursion
18177 (unless (org-at-date-range-p t)
18178 (goto-char (point-at-bol))
18179 (re-search-forward org-tr-regexp-both (point-at-eol) t))
18180 (if (not (org-at-date-range-p t))
18181 (error "Not at a time-stamp range, and none found in current line")))
18182 (let* ((ts1 (match-string 1))
18183 (ts2 (match-string 2))
18184 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
18185 (match-end (match-end 0))
18186 (time1 (org-time-string-to-time ts1))
18187 (time2 (org-time-string-to-time ts2))
18188 (t1 (time-to-seconds time1))
18189 (t2 (time-to-seconds time2))
18190 (diff (abs (- t2 t1)))
18191 (negative (< (- t2 t1) 0))
18192 ;; (ys (floor (* 365 24 60 60)))
18193 (ds (* 24 60 60))
18194 (hs (* 60 60))
18195 (fy "%dy %dd %02d:%02d")
18196 (fy1 "%dy %dd")
18197 (fd "%dd %02d:%02d")
18198 (fd1 "%dd")
18199 (fh "%02d:%02d")
18200 y d h m align)
18201 (if havetime
18202 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
18204 d (floor (/ diff ds)) diff (mod diff ds)
18205 h (floor (/ diff hs)) diff (mod diff hs)
18206 m (floor (/ diff 60)))
18207 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
18209 d (floor (+ (/ diff ds) 0.5))
18210 h 0 m 0))
18211 (if (not to-buffer)
18212 (message "%s" (org-make-tdiff-string y d h m))
18213 (if (org-at-table-p)
18214 (progn
18215 (goto-char match-end)
18216 (setq align t)
18217 (and (looking-at " *|") (goto-char (match-end 0))))
18218 (goto-char match-end))
18219 (if (looking-at
18220 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
18221 (replace-match ""))
18222 (if negative (insert " -"))
18223 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
18224 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
18225 (insert " " (format fh h m))))
18226 (if align (org-table-align))
18227 (message "Time difference inserted")))))
18229 (defun org-make-tdiff-string (y d h m)
18230 (let ((fmt "")
18231 (l nil))
18232 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
18233 l (push y l)))
18234 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
18235 l (push d l)))
18236 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
18237 l (push h l)))
18238 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
18239 l (push m l)))
18240 (apply 'format fmt (nreverse l))))
18242 (defun org-time-string-to-time (s)
18243 (apply 'encode-time (org-parse-time-string s)))
18245 (defun org-time-string-to-absolute (s &optional daynr prefer)
18246 "Convert a time stamp to an absolute day number.
18247 If there is a specifyer for a cyclic time stamp, get the closest date to
18248 DAYNR."
18249 (cond
18250 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
18251 (if (org-diary-sexp-entry (match-string 1 s) "" date)
18252 daynr
18253 (+ daynr 1000)))
18254 ((and daynr (string-match "\\+[0-9]+[dwmy]" s))
18255 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
18256 (time-to-days (current-time))) (match-string 0 s)
18257 prefer))
18258 (t (time-to-days (apply 'encode-time (org-parse-time-string s))))))
18260 (defun org-time-from-absolute (d)
18261 "Return the time corresponding to date D.
18262 D may be an absolute day number, or a calendar-type list (month day year)."
18263 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
18264 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
18266 (defun org-calendar-holiday ()
18267 "List of holidays, for Diary display in Org-mode."
18268 (require 'holidays)
18269 (let ((hl (funcall
18270 (if (fboundp 'calendar-check-holidays)
18271 'calendar-check-holidays 'check-calendar-holidays) date)))
18272 (if hl (mapconcat 'identity hl "; "))))
18274 (defun org-diary-sexp-entry (sexp entry date)
18275 "Process a SEXP diary ENTRY for DATE."
18276 (require 'diary-lib)
18277 (let ((result (if calendar-debug-sexp
18278 (let ((stack-trace-on-error t))
18279 (eval (car (read-from-string sexp))))
18280 (condition-case nil
18281 (eval (car (read-from-string sexp)))
18282 (error
18283 (beep)
18284 (message "Bad sexp at line %d in %s: %s"
18285 (org-current-line)
18286 (buffer-file-name) sexp)
18287 (sleep-for 2))))))
18288 (cond ((stringp result) result)
18289 ((and (consp result)
18290 (stringp (cdr result))) (cdr result))
18291 (result entry)
18292 (t nil))))
18294 (defun org-diary-to-ical-string (frombuf)
18295 "Get iCalendar entries from diary entries in buffer FROMBUF.
18296 This uses the icalendar.el library."
18297 (let* ((tmpdir (if (featurep 'xemacs)
18298 (temp-directory)
18299 temporary-file-directory))
18300 (tmpfile (make-temp-name
18301 (expand-file-name "orgics" tmpdir)))
18302 buf rtn b e)
18303 (save-excursion
18304 (set-buffer frombuf)
18305 (icalendar-export-region (point-min) (point-max) tmpfile)
18306 (setq buf (find-buffer-visiting tmpfile))
18307 (set-buffer buf)
18308 (goto-char (point-min))
18309 (if (re-search-forward "^BEGIN:VEVENT" nil t)
18310 (setq b (match-beginning 0)))
18311 (goto-char (point-max))
18312 (if (re-search-backward "^END:VEVENT" nil t)
18313 (setq e (match-end 0)))
18314 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
18315 (kill-buffer buf)
18316 (kill-buffer frombuf)
18317 (delete-file tmpfile)
18318 rtn))
18320 (defun org-closest-date (start current change prefer)
18321 "Find the date closest to CURRENT that is consistent with START and CHANGE.
18322 When PREFER is `past' return a date that is either CURRENT or past.
18323 When PREFER is `future', return a date that is either CURRENT or future."
18324 ;; Make the proper lists from the dates
18325 (catch 'exit
18326 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
18327 dn dw sday cday n1 n2
18328 d m y y1 y2 date1 date2 nmonths nm ny m2)
18330 (setq start (org-date-to-gregorian start)
18331 current (org-date-to-gregorian
18332 (if org-agenda-repeating-timestamp-show-all
18333 current
18334 (time-to-days (current-time))))
18335 sday (calendar-absolute-from-gregorian start)
18336 cday (calendar-absolute-from-gregorian current))
18338 (if (<= cday sday) (throw 'exit sday))
18340 (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
18341 (setq dn (string-to-number (match-string 1 change))
18342 dw (cdr (assoc (match-string 2 change) a1)))
18343 (error "Invalid change specifyer: %s" change))
18344 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
18345 (cond
18346 ((eq dw 'day)
18347 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
18348 n2 (+ n1 dn)))
18349 ((eq dw 'year)
18350 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
18351 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
18352 (setq date1 (list m d y1)
18353 n1 (calendar-absolute-from-gregorian date1)
18354 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
18355 n2 (calendar-absolute-from-gregorian date2)))
18356 ((eq dw 'month)
18357 ;; approx number of month between the tow dates
18358 (setq nmonths (floor (/ (- cday sday) 30.436875)))
18359 ;; How often does dn fit in there?
18360 (setq d (nth 1 start) m (car start) y (nth 2 start)
18361 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
18362 m (+ m nm)
18363 ny (floor (/ m 12))
18364 y (+ y ny)
18365 m (- m (* ny 12)))
18366 (while (> m 12) (setq m (- m 12) y (1+ y)))
18367 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
18368 (setq m2 (+ m dn) y2 y)
18369 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
18370 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
18371 (while (< n2 cday)
18372 (setq n1 n2 m m2 y y2)
18373 (setq m2 (+ m dn) y2 y)
18374 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
18375 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
18377 (if org-agenda-repeating-timestamp-show-all
18378 (cond
18379 ((eq prefer 'past) n1)
18380 ((eq prefer 'future) (if (= cday n1) n1 n2))
18381 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
18382 (cond
18383 ((eq prefer 'past) n1)
18384 ((eq prefer 'future) (if (= cday n1) n1 n2))
18385 (t (if (= cday n1) n1 n2)))))))
18387 (defun org-date-to-gregorian (date)
18388 "Turn any specification of DATE into a gregorian date for the calendar."
18389 (cond ((integerp date) (calendar-gregorian-from-absolute date))
18390 ((and (listp date) (= (length date) 3)) date)
18391 ((stringp date)
18392 (setq date (org-parse-time-string date))
18393 (list (nth 4 date) (nth 3 date) (nth 5 date)))
18394 ((listp date)
18395 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
18397 (defun org-parse-time-string (s &optional nodefault)
18398 "Parse the standard Org-mode time string.
18399 This should be a lot faster than the normal `parse-time-string'.
18400 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
18401 hour and minute fields will be nil if not given."
18402 (if (string-match org-ts-regexp0 s)
18403 (list 0
18404 (if (or (match-beginning 8) (not nodefault))
18405 (string-to-number (or (match-string 8 s) "0")))
18406 (if (or (match-beginning 7) (not nodefault))
18407 (string-to-number (or (match-string 7 s) "0")))
18408 (string-to-number (match-string 4 s))
18409 (string-to-number (match-string 3 s))
18410 (string-to-number (match-string 2 s))
18411 nil nil nil)
18412 (make-list 9 0)))
18414 (defun org-timestamp-up (&optional arg)
18415 "Increase the date item at the cursor by one.
18416 If the cursor is on the year, change the year. If it is on the month or
18417 the day, change that.
18418 With prefix ARG, change by that many units."
18419 (interactive "p")
18420 (org-timestamp-change (prefix-numeric-value arg)))
18422 (defun org-timestamp-down (&optional arg)
18423 "Decrease the date item at the cursor by one.
18424 If the cursor is on the year, change the year. If it is on the month or
18425 the day, change that.
18426 With prefix ARG, change by that many units."
18427 (interactive "p")
18428 (org-timestamp-change (- (prefix-numeric-value arg))))
18430 (defun org-timestamp-up-day (&optional arg)
18431 "Increase the date in the time stamp by one day.
18432 With prefix ARG, change that many days."
18433 (interactive "p")
18434 (if (and (not (org-at-timestamp-p t))
18435 (org-on-heading-p))
18436 (org-todo 'up)
18437 (org-timestamp-change (prefix-numeric-value arg) 'day)))
18439 (defun org-timestamp-down-day (&optional arg)
18440 "Decrease the date in the time stamp by one day.
18441 With prefix ARG, change that many days."
18442 (interactive "p")
18443 (if (and (not (org-at-timestamp-p t))
18444 (org-on-heading-p))
18445 (org-todo 'down)
18446 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
18448 (defsubst org-pos-in-match-range (pos n)
18449 (and (match-beginning n)
18450 (<= (match-beginning n) pos)
18451 (>= (match-end n) pos)))
18453 (defun org-at-timestamp-p (&optional inactive-ok)
18454 "Determine if the cursor is in or at a timestamp."
18455 (interactive)
18456 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
18457 (pos (point))
18458 (ans (or (looking-at tsr)
18459 (save-excursion
18460 (skip-chars-backward "^[<\n\r\t")
18461 (if (> (point) (point-min)) (backward-char 1))
18462 (and (looking-at tsr)
18463 (> (- (match-end 0) pos) -1))))))
18464 (and ans
18465 (boundp 'org-ts-what)
18466 (setq org-ts-what
18467 (cond
18468 ((= pos (match-beginning 0)) 'bracket)
18469 ((= pos (1- (match-end 0))) 'bracket)
18470 ((org-pos-in-match-range pos 2) 'year)
18471 ((org-pos-in-match-range pos 3) 'month)
18472 ((org-pos-in-match-range pos 7) 'hour)
18473 ((org-pos-in-match-range pos 8) 'minute)
18474 ((or (org-pos-in-match-range pos 4)
18475 (org-pos-in-match-range pos 5)) 'day)
18476 ((and (> pos (or (match-end 8) (match-end 5)))
18477 (< pos (match-end 0)))
18478 (- pos (or (match-end 8) (match-end 5))))
18479 (t 'day))))
18480 ans))
18482 (defun org-toggle-timestamp-type ()
18484 (interactive)
18485 (when (org-at-timestamp-p t)
18486 (save-excursion
18487 (goto-char (match-beginning 0))
18488 (insert (if (equal (char-after) ?<) "[" "<")) (delete-char 1)
18489 (goto-char (1- (match-end 0)))
18490 (insert (if (equal (char-after) ?>) "]" ">")) (delete-char 1))
18491 (message "Timestamp is now %sactive"
18492 (if (equal (char-before) ?>) "in" ""))))
18494 (defun org-timestamp-change (n &optional what)
18495 "Change the date in the time stamp at point.
18496 The date will be changed by N times WHAT. WHAT can be `day', `month',
18497 `year', `minute', `second'. If WHAT is not given, the cursor position
18498 in the timestamp determines what will be changed."
18499 (let ((pos (point))
18500 with-hm inactive
18501 org-ts-what
18502 extra
18503 ts time time0)
18504 (if (not (org-at-timestamp-p t))
18505 (error "Not at a timestamp"))
18506 (if (and (not what) (eq org-ts-what 'bracket))
18507 (org-toggle-timestamp-type)
18508 (if (and (not what) (not (eq org-ts-what 'day))
18509 org-display-custom-times
18510 (get-text-property (point) 'display)
18511 (not (get-text-property (1- (point)) 'display)))
18512 (setq org-ts-what 'day))
18513 (setq org-ts-what (or what org-ts-what)
18514 inactive (= (char-after (match-beginning 0)) ?\[)
18515 ts (match-string 0))
18516 (replace-match "")
18517 (if (string-match
18518 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( [-+][0-9]+[dwmy]\\)*\\)[]>]"
18520 (setq extra (match-string 1 ts)))
18521 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
18522 (setq with-hm t))
18523 (setq time0 (org-parse-time-string ts))
18524 (setq time
18525 (encode-time (or (car time0) 0)
18526 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
18527 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
18528 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
18529 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
18530 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
18531 (nthcdr 6 time0)))
18532 (when (integerp org-ts-what)
18533 (setq extra (org-modify-ts-extra extra org-ts-what n)))
18534 (if (eq what 'calendar)
18535 (let ((cal-date (org-get-date-from-calendar)))
18536 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
18537 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
18538 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
18539 (setcar time0 (or (car time0) 0))
18540 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
18541 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
18542 (setq time (apply 'encode-time time0))))
18543 (setq org-last-changed-timestamp
18544 (org-insert-time-stamp time with-hm inactive nil nil extra))
18545 (org-clock-update-time-maybe)
18546 (goto-char pos)
18547 ;; Try to recenter the calendar window, if any
18548 (if (and org-calendar-follow-timestamp-change
18549 (get-buffer-window "*Calendar*" t)
18550 (memq org-ts-what '(day month year)))
18551 (org-recenter-calendar (time-to-days time))))))
18553 ;; FIXME: does not yet work for lead times
18554 (defun org-modify-ts-extra (s pos n)
18555 "Change the different parts of the lead-time and repeat fields in timestamp."
18556 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
18557 ng h m new)
18558 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( \\+\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
18559 (cond
18560 ((or (org-pos-in-match-range pos 2)
18561 (org-pos-in-match-range pos 3))
18562 (setq m (string-to-number (match-string 3 s))
18563 h (string-to-number (match-string 2 s)))
18564 (if (org-pos-in-match-range pos 2)
18565 (setq h (+ h n))
18566 (setq m (+ m n)))
18567 (if (< m 0) (setq m (+ m 60) h (1- h)))
18568 (if (> m 59) (setq m (- m 60) h (1+ h)))
18569 (setq h (min 24 (max 0 h)))
18570 (setq ng 1 new (format "-%02d:%02d" h m)))
18571 ((org-pos-in-match-range pos 6)
18572 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
18573 ((org-pos-in-match-range pos 5)
18574 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s))))))))
18576 (when ng
18577 (setq s (concat
18578 (substring s 0 (match-beginning ng))
18580 (substring s (match-end ng))))))
18583 (defun org-recenter-calendar (date)
18584 "If the calendar is visible, recenter it to DATE."
18585 (let* ((win (selected-window))
18586 (cwin (get-buffer-window "*Calendar*" t))
18587 (calendar-move-hook nil))
18588 (when cwin
18589 (select-window cwin)
18590 (calendar-goto-date (if (listp date) date
18591 (calendar-gregorian-from-absolute date)))
18592 (select-window win))))
18594 (defun org-goto-calendar (&optional arg)
18595 "Go to the Emacs calendar at the current date.
18596 If there is a time stamp in the current line, go to that date.
18597 A prefix ARG can be used to force the current date."
18598 (interactive "P")
18599 (let ((tsr org-ts-regexp) diff
18600 (calendar-move-hook nil)
18601 (view-calendar-holidays-initially nil)
18602 (view-diary-entries-initially nil))
18603 (if (or (org-at-timestamp-p)
18604 (save-excursion
18605 (beginning-of-line 1)
18606 (looking-at (concat ".*" tsr))))
18607 (let ((d1 (time-to-days (current-time)))
18608 (d2 (time-to-days
18609 (org-time-string-to-time (match-string 1)))))
18610 (setq diff (- d2 d1))))
18611 (calendar)
18612 (calendar-goto-today)
18613 (if (and diff (not arg)) (calendar-forward-day diff))))
18615 (defun org-get-date-from-calendar ()
18616 "Return a list (month day year) of date at point in calendar."
18617 (with-current-buffer "*Calendar*"
18618 (save-match-data
18619 (calendar-cursor-to-date))))
18621 (defun org-date-from-calendar ()
18622 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
18623 If there is already a time stamp at the cursor position, update it."
18624 (interactive)
18625 (if (org-at-timestamp-p t)
18626 (org-timestamp-change 0 'calendar)
18627 (let ((cal-date (org-get-date-from-calendar)))
18628 (org-insert-time-stamp
18629 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
18631 (defvar appt-time-msg-list)
18633 ;;;###autoload
18634 (defun org-agenda-to-appt (&optional refresh filter)
18635 "Activate appointments found in `org-agenda-files'.
18636 With a \\[universal-argument] prefix, refresh the list of
18637 appointements.
18639 If FILTER is t, interactively prompt the user for a regular
18640 expression, and filter out entries that don't match it.
18642 If FILTER is a string, use this string as a regular expression
18643 for filtering entries out.
18645 FILTER can also be an alist with the car of each cell being
18646 either 'headline or 'category. For example:
18648 '((headline \"IMPORTANT\")
18649 (category \"Work\"))
18651 will only add headlines containing IMPORTANT or headlines
18652 belonging to the \"Work\" category."
18653 (interactive "P")
18654 (require 'calendar)
18655 (if refresh (setq appt-time-msg-list nil))
18656 (if (eq filter t)
18657 (setq filter (read-from-minibuffer "Regexp filter: ")))
18658 (let* ((cnt 0) ; count added events
18659 (org-agenda-new-buffers nil)
18660 (org-deadline-warning-days 0)
18661 (today (org-date-to-gregorian
18662 (time-to-days (current-time))))
18663 (files (org-agenda-files)) entries file)
18664 ;; Get all entries which may contain an appt
18665 (while (setq file (pop files))
18666 (setq entries
18667 (append entries
18668 (org-agenda-get-day-entries
18669 file today :timestamp :scheduled :deadline))))
18670 (setq entries (delq nil entries))
18671 ;; Map thru entries and find if we should filter them out
18672 (mapc
18673 (lambda(x)
18674 (let* ((evt (org-trim (get-text-property 1 'txt x)))
18675 (cat (get-text-property 1 'org-category x))
18676 (tod (get-text-property 1 'time-of-day x))
18677 (ok (or (null filter)
18678 (and (stringp filter) (string-match filter evt))
18679 (and (listp filter)
18680 (or (string-match
18681 (cadr (assoc 'category filter)) cat)
18682 (string-match
18683 (cadr (assoc 'headline filter)) evt))))))
18684 ;; FIXME: Shall we remove text-properties for the appt text?
18685 ;; (setq evt (set-text-properties 0 (length evt) nil evt))
18686 (when (and ok tod)
18687 (setq tod (number-to-string tod)
18688 tod (when (string-match
18689 "\\([0-9]\\{1,2\\}\\)\\([0-9]\\{2\\}\\)" tod)
18690 (concat (match-string 1 tod) ":"
18691 (match-string 2 tod))))
18692 (appt-add tod evt)
18693 (setq cnt (1+ cnt))))) entries)
18694 (org-release-buffers org-agenda-new-buffers)
18695 (if (eq cnt 0)
18696 (message "No event to add")
18697 (message "Added %d event%s for today" cnt (if (> cnt 1) "s" "")))))
18699 ;;; The clock for measuring work time.
18701 (defvar org-mode-line-string "")
18702 (put 'org-mode-line-string 'risky-local-variable t)
18704 (defvar org-mode-line-timer nil)
18705 (defvar org-clock-heading "")
18706 (defvar org-clock-start-time "")
18708 (defun org-update-mode-line ()
18709 (let* ((delta (- (time-to-seconds (current-time))
18710 (time-to-seconds org-clock-start-time)))
18711 (h (floor delta 3600))
18712 (m (floor (- delta (* 3600 h)) 60)))
18713 (setq org-mode-line-string
18714 (propertize (format "-[%d:%02d (%s)]" h m org-clock-heading)
18715 'help-echo "Org-mode clock is running"))
18716 (force-mode-line-update)))
18718 (defvar org-clock-marker (make-marker)
18719 "Marker recording the last clock-in.")
18720 (defvar org-clock-mode-line-entry nil
18721 "Information for the modeline about the running clock.")
18723 (defun org-clock-in ()
18724 "Start the clock on the current item.
18725 If necessary, clock-out of the currently active clock."
18726 (interactive)
18727 (org-clock-out t)
18728 (let (ts)
18729 (save-excursion
18730 (org-back-to-heading t)
18731 (when (and org-clock-in-switch-to-state
18732 (not (looking-at (concat outline-regexp "[ \t]*"
18733 org-clock-in-switch-to-state
18734 "\\>"))))
18735 (org-todo org-clock-in-switch-to-state))
18736 (if (and org-clock-heading-function
18737 (functionp org-clock-heading-function))
18738 (setq org-clock-heading (funcall org-clock-heading-function))
18739 (if (looking-at org-complex-heading-regexp)
18740 (setq org-clock-heading (match-string 4))
18741 (setq org-clock-heading "???")))
18742 (setq org-clock-heading (propertize org-clock-heading 'face nil))
18743 (org-clock-find-position)
18745 (insert "\n") (backward-char 1)
18746 (indent-relative)
18747 (insert org-clock-string " ")
18748 (setq org-clock-start-time (current-time))
18749 (setq ts (org-insert-time-stamp (current-time) 'with-hm 'inactive))
18750 (move-marker org-clock-marker (point) (buffer-base-buffer))
18751 (or global-mode-string (setq global-mode-string '("")))
18752 (or (memq 'org-mode-line-string global-mode-string)
18753 (setq global-mode-string
18754 (append global-mode-string '(org-mode-line-string))))
18755 (org-update-mode-line)
18756 (setq org-mode-line-timer (run-with-timer 60 60 'org-update-mode-line))
18757 (message "Clock started at %s" ts))))
18759 (defun org-clock-find-position ()
18760 "Find the location where the next clock line should be inserted."
18761 (org-back-to-heading t)
18762 (catch 'exit
18763 (let ((beg (point-at-bol 2)) (end (progn (outline-next-heading) (point)))
18764 (re (concat "^[ \t]*" org-clock-string))
18765 (cnt 0)
18766 first last)
18767 (goto-char beg)
18768 (when (eobp) (newline) (setq end (max (point) end)))
18769 (when (re-search-forward "^[ \t]*:CLOCK:" end t)
18770 ;; we seem to have a CLOCK drawer, so go there.
18771 (beginning-of-line 2)
18772 (throw 'exit t))
18773 ;; Lets count the CLOCK lines
18774 (goto-char beg)
18775 (while (re-search-forward re end t)
18776 (setq first (or first (match-beginning 0))
18777 last (match-beginning 0)
18778 cnt (1+ cnt)))
18779 (when (and (integerp org-clock-into-drawer)
18780 (>= (1+ cnt) org-clock-into-drawer))
18781 ;; Wrap current entries into a new drawer
18782 (goto-char last)
18783 (beginning-of-line 2)
18784 (if (org-at-item-p) (org-end-of-item))
18785 (insert ":END:\n")
18786 (beginning-of-line 0)
18787 (org-indent-line-function)
18788 (goto-char first)
18789 (insert ":CLOCK:\n")
18790 (beginning-of-line 0)
18791 (org-indent-line-function)
18792 (org-flag-drawer t)
18793 (beginning-of-line 2)
18794 (throw 'exit nil))
18796 (goto-char beg)
18797 (while (and (looking-at (concat "[ \t]*" org-keyword-time-regexp))
18798 (not (equal (match-string 1) org-clock-string)))
18799 ;; Planning info, skip to after it
18800 (beginning-of-line 2)
18801 (or (bolp) (newline)))
18802 (when (eq t org-clock-into-drawer)
18803 (insert ":CLOCK:\n:END:\n")
18804 (beginning-of-line -1)
18805 (org-indent-line-function)
18806 (org-flag-drawer t)
18807 (beginning-of-line 2)
18808 (org-indent-line-function)))))
18810 (defun org-clock-out (&optional fail-quietly)
18811 "Stop the currently running clock.
18812 If there is no running clock, throw an error, unless FAIL-QUIETLY is set."
18813 (interactive)
18814 (catch 'exit
18815 (if (not (marker-buffer org-clock-marker))
18816 (if fail-quietly (throw 'exit t) (error "No active clock")))
18817 (let (ts te s h m)
18818 (save-excursion
18819 (set-buffer (marker-buffer org-clock-marker))
18820 (goto-char org-clock-marker)
18821 (beginning-of-line 1)
18822 (if (and (looking-at (concat "[ \t]*" org-keyword-time-regexp))
18823 (equal (match-string 1) org-clock-string))
18824 (setq ts (match-string 2))
18825 (if fail-quietly (throw 'exit nil) (error "Clock start time is gone")))
18826 (goto-char (match-end 0))
18827 (delete-region (point) (point-at-eol))
18828 (insert "--")
18829 (setq te (org-insert-time-stamp (current-time) 'with-hm 'inactive))
18830 (setq s (- (time-to-seconds (apply 'encode-time (org-parse-time-string te)))
18831 (time-to-seconds (apply 'encode-time (org-parse-time-string ts))))
18832 h (floor (/ s 3600))
18833 s (- s (* 3600 h))
18834 m (floor (/ s 60))
18835 s (- s (* 60 s)))
18836 (insert " => " (format "%2d:%02d" h m))
18837 (move-marker org-clock-marker nil)
18838 (when org-log-note-clock-out
18839 (org-add-log-maybe 'clock-out))
18840 (when org-mode-line-timer
18841 (cancel-timer org-mode-line-timer)
18842 (setq org-mode-line-timer nil))
18843 (setq global-mode-string
18844 (delq 'org-mode-line-string global-mode-string))
18845 (force-mode-line-update)
18846 (message "Clock stopped at %s after HH:MM = %d:%02d" te h m)))))
18848 (defun org-clock-cancel ()
18849 "Cancel the running clock be removing the start timestamp."
18850 (interactive)
18851 (if (not (marker-buffer org-clock-marker))
18852 (error "No active clock"))
18853 (save-excursion
18854 (set-buffer (marker-buffer org-clock-marker))
18855 (goto-char org-clock-marker)
18856 (delete-region (1- (point-at-bol)) (point-at-eol)))
18857 (setq global-mode-string
18858 (delq 'org-mode-line-string global-mode-string))
18859 (force-mode-line-update)
18860 (message "Clock canceled"))
18862 (defun org-clock-goto (&optional delete-windows)
18863 "Go to the currently clocked-in entry."
18864 (interactive "P")
18865 (if (not (marker-buffer org-clock-marker))
18866 (error "No active clock"))
18867 (switch-to-buffer-other-window
18868 (marker-buffer org-clock-marker))
18869 (if delete-windows (delete-other-windows))
18870 (goto-char org-clock-marker)
18871 (org-show-entry)
18872 (org-back-to-heading)
18873 (recenter))
18875 (defvar org-clock-file-total-minutes nil
18876 "Holds the file total time in minutes, after a call to `org-clock-sum'.")
18877 (make-variable-buffer-local 'org-clock-file-total-minutes)
18879 (defun org-clock-sum (&optional tstart tend)
18880 "Sum the times for each subtree.
18881 Puts the resulting times in minutes as a text property on each headline."
18882 (interactive)
18883 (let* ((bmp (buffer-modified-p))
18884 (re (concat "^\\(\\*+\\)[ \t]\\|^[ \t]*"
18885 org-clock-string
18886 "[ \t]*\\(?:\\(\\[.*?\\]\\)-+\\(\\[.*?\\]\\)\\|=>[ \t]+\\([0-9]+\\):\\([0-9]+\\)\\)"))
18887 (lmax 30)
18888 (ltimes (make-vector lmax 0))
18889 (t1 0)
18890 (level 0)
18891 ts te dt
18892 time)
18893 (remove-text-properties (point-min) (point-max) '(:org-clock-minutes t))
18894 (save-excursion
18895 (goto-char (point-max))
18896 (while (re-search-backward re nil t)
18897 (cond
18898 ((match-end 2)
18899 ;; Two time stamps
18900 (setq ts (match-string 2)
18901 te (match-string 3)
18902 ts (time-to-seconds
18903 (apply 'encode-time (org-parse-time-string ts)))
18904 te (time-to-seconds
18905 (apply 'encode-time (org-parse-time-string te)))
18906 ts (if tstart (max ts tstart) ts)
18907 te (if tend (min te tend) te)
18908 dt (- te ts)
18909 t1 (if (> dt 0) (+ t1 (floor (/ dt 60))) t1)))
18910 ((match-end 4)
18911 ;; A naket time
18912 (setq t1 (+ t1 (string-to-number (match-string 5))
18913 (* 60 (string-to-number (match-string 4))))))
18914 (t ;; A headline
18915 (setq level (- (match-end 1) (match-beginning 1)))
18916 (when (or (> t1 0) (> (aref ltimes level) 0))
18917 (loop for l from 0 to level do
18918 (aset ltimes l (+ (aref ltimes l) t1)))
18919 (setq t1 0 time (aref ltimes level))
18920 (loop for l from level to (1- lmax) do
18921 (aset ltimes l 0))
18922 (goto-char (match-beginning 0))
18923 (put-text-property (point) (point-at-eol) :org-clock-minutes time)))))
18924 (setq org-clock-file-total-minutes (aref ltimes 0)))
18925 (set-buffer-modified-p bmp)))
18927 (defun org-clock-display (&optional total-only)
18928 "Show subtree times in the entire buffer.
18929 If TOTAL-ONLY is non-nil, only show the total time for the entire file
18930 in the echo area."
18931 (interactive)
18932 (org-remove-clock-overlays)
18933 (let (time h m p)
18934 (org-clock-sum)
18935 (unless total-only
18936 (save-excursion
18937 (goto-char (point-min))
18938 (while (or (and (equal (setq p (point)) (point-min))
18939 (get-text-property p :org-clock-minutes))
18940 (setq p (next-single-property-change
18941 (point) :org-clock-minutes)))
18942 (goto-char p)
18943 (when (setq time (get-text-property p :org-clock-minutes))
18944 (org-put-clock-overlay time (funcall outline-level))))
18945 (setq h (/ org-clock-file-total-minutes 60)
18946 m (- org-clock-file-total-minutes (* 60 h)))
18947 ;; Arrange to remove the overlays upon next change.
18948 (when org-remove-highlights-with-change
18949 (org-add-hook 'before-change-functions 'org-remove-clock-overlays
18950 nil 'local))))
18951 (message "Total file time: %d:%02d (%d hours and %d minutes)" h m h m)))
18953 (defvar org-clock-overlays nil)
18954 (make-variable-buffer-local 'org-clock-overlays)
18956 (defun org-put-clock-overlay (time &optional level)
18957 "Put an overlays on the current line, displaying TIME.
18958 If LEVEL is given, prefix time with a corresponding number of stars.
18959 This creates a new overlay and stores it in `org-clock-overlays', so that it
18960 will be easy to remove."
18961 (let* ((c 60) (h (floor (/ time 60))) (m (- time (* 60 h)))
18962 (l (if level (org-get-legal-level level 0) 0))
18963 (off 0)
18964 ov tx)
18965 (move-to-column c)
18966 (unless (eolp) (skip-chars-backward "^ \t"))
18967 (skip-chars-backward " \t")
18968 (setq ov (org-make-overlay (1- (point)) (point-at-eol))
18969 tx (concat (buffer-substring (1- (point)) (point))
18970 (make-string (+ off (max 0 (- c (current-column)))) ?.)
18971 (org-add-props (format "%s %2d:%02d%s"
18972 (make-string l ?*) h m
18973 (make-string (- 16 l) ?\ ))
18974 '(face secondary-selection))
18975 ""))
18976 (if (not (featurep 'xemacs))
18977 (org-overlay-put ov 'display tx)
18978 (org-overlay-put ov 'invisible t)
18979 (org-overlay-put ov 'end-glyph (make-glyph tx)))
18980 (push ov org-clock-overlays)))
18982 (defun org-remove-clock-overlays (&optional beg end noremove)
18983 "Remove the occur highlights from the buffer.
18984 BEG and END are ignored. If NOREMOVE is nil, remove this function
18985 from the `before-change-functions' in the current buffer."
18986 (interactive)
18987 (unless org-inhibit-highlight-removal
18988 (mapc 'org-delete-overlay org-clock-overlays)
18989 (setq org-clock-overlays nil)
18990 (unless noremove
18991 (remove-hook 'before-change-functions
18992 'org-remove-clock-overlays 'local))))
18994 (defun org-clock-out-if-current ()
18995 "Clock out if the current entry contains the running clock.
18996 This is used to stop the clock after a TODO entry is marked DONE,
18997 and is only done if the variable `org-clock-out-when-done' is not nil."
18998 (when (and org-clock-out-when-done
18999 (member state org-done-keywords)
19000 (equal (marker-buffer org-clock-marker) (current-buffer))
19001 (< (point) org-clock-marker)
19002 (> (save-excursion (outline-next-heading) (point))
19003 org-clock-marker))
19004 ;; Clock out, but don't accept a logging message for this.
19005 (let ((org-log-note-clock-out nil))
19006 (org-clock-out))))
19008 (add-hook 'org-after-todo-state-change-hook
19009 'org-clock-out-if-current)
19011 (defun org-check-running-clock ()
19012 "Check if the current buffer contains the running clock.
19013 If yes, offer to stop it and to save the buffer with the changes."
19014 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
19015 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
19016 (buffer-name))))
19017 (org-clock-out)
19018 (when (y-or-n-p "Save changed buffer?")
19019 (save-buffer))))
19021 (defun org-clock-report (&optional arg)
19022 "Create a table containing a report about clocked time.
19023 If the cursor is inside an existing clocktable block, then the table
19024 will be updated. If not, a new clocktable will be inserted.
19025 When called with a prefix argument, move to the first clock table in the
19026 buffer and update it."
19027 (interactive "P")
19028 (org-remove-clock-overlays)
19029 (when arg
19030 (org-find-dblock "clocktable")
19031 (org-show-entry))
19032 (if (org-in-clocktable-p)
19033 (goto-char (org-in-clocktable-p))
19034 (org-create-dblock (list :name "clocktable"
19035 :maxlevel 2 :scope 'file)))
19036 (org-update-dblock))
19038 (defun org-in-clocktable-p ()
19039 "Check if the cursor is in a clocktable."
19040 (let ((pos (point)) start)
19041 (save-excursion
19042 (end-of-line 1)
19043 (and (re-search-backward "^#\\+BEGIN:[ \t]+clocktable" nil t)
19044 (setq start (match-beginning 0))
19045 (re-search-forward "^#\\+END:.*" nil t)
19046 (>= (match-end 0) pos)
19047 start))))
19049 (defun org-clock-update-time-maybe ()
19050 "If this is a CLOCK line, update it and return t.
19051 Otherwise, return nil."
19052 (interactive)
19053 (save-excursion
19054 (beginning-of-line 1)
19055 (skip-chars-forward " \t")
19056 (when (looking-at org-clock-string)
19057 (let ((re (concat "[ \t]*" org-clock-string
19058 " *[[<]\\([^]>]+\\)[]>]-+[[<]\\([^]>]+\\)[]>]"
19059 "\\([ \t]*=>.*\\)?"))
19060 ts te h m s)
19061 (if (not (looking-at re))
19063 (and (match-end 3) (delete-region (match-beginning 3) (match-end 3)))
19064 (end-of-line 1)
19065 (setq ts (match-string 1)
19066 te (match-string 2))
19067 (setq s (- (time-to-seconds
19068 (apply 'encode-time (org-parse-time-string te)))
19069 (time-to-seconds
19070 (apply 'encode-time (org-parse-time-string ts))))
19071 h (floor (/ s 3600))
19072 s (- s (* 3600 h))
19073 m (floor (/ s 60))
19074 s (- s (* 60 s)))
19075 (insert " => " (format "%2d:%02d" h m))
19076 t)))))
19078 (defun org-clock-special-range (key &optional time as-strings)
19079 "Return two times bordering a special time range.
19080 Key is a symbol specifying the range and can be one of `today', `yesterday',
19081 `thisweek', `lastweek', `thismonth', `lastmonth', `thisyear', `lastyear'.
19082 A week starts Monday 0:00 and ends Sunday 24:00.
19083 The range is determined relative to TIME. TIME defaults to the current time.
19084 The return value is a cons cell with two internal times like the ones
19085 returned by `current time' or `encode-time'. if AS-STRINGS is non-nil,
19086 the returned times will be formatted strings."
19087 (let* ((tm (decode-time (or time (current-time))))
19088 (s 0) (m (nth 1 tm)) (h (nth 2 tm))
19089 (d (nth 3 tm)) (month (nth 4 tm)) (y (nth 5 tm))
19090 (dow (nth 6 tm))
19091 s1 m1 h1 d1 month1 y1 diff ts te fm)
19092 (cond
19093 ((eq key 'today)
19094 (setq h 0 m 0 h1 24 m1 0))
19095 ((eq key 'yesterday)
19096 (setq d (1- d) h 0 m 0 h1 24 m1 0))
19097 ((eq key 'thisweek)
19098 (setq diff (if (= dow 0) 6 (1- dow))
19099 m 0 h 0 d (- d diff) d1 (+ 7 d)))
19100 ((eq key 'lastweek)
19101 (setq diff (+ 7 (if (= dow 0) 6 (1- dow)))
19102 m 0 h 0 d (- d diff) d1 (+ 7 d)))
19103 ((eq key 'thismonth)
19104 (setq d 1 h 0 m 0 d1 1 month1 (1+ month) h1 0 m1 0))
19105 ((eq key 'lastmonth)
19106 (setq d 1 h 0 m 0 d1 1 month (1- month) month1 (1+ month) h1 0 m1 0))
19107 ((eq key 'thisyear)
19108 (setq m 0 h 0 d 1 month 1 y1 (1+ y)))
19109 ((eq key 'lastyear)
19110 (setq m 0 h 0 d 1 month 1 y (1- y) y1 (1+ y)))
19111 (t (error "No such time block %s" key)))
19112 (setq ts (encode-time s m h d month y)
19113 te (encode-time (or s1 s) (or m1 m) (or h1 h)
19114 (or d1 d) (or month1 month) (or y1 y)))
19115 (setq fm (cdr org-time-stamp-formats))
19116 (if as-strings
19117 (cons (format-time-string fm ts) (format-time-string fm te))
19118 (cons ts te))))
19120 (defun org-dblock-write:clocktable (params)
19121 "Write the standard clocktable."
19122 (catch 'exit
19123 (let* ((hlchars '((1 . "*") (2 . "/")))
19124 (ins (make-marker))
19125 (total-time nil)
19126 (scope (plist-get params :scope))
19127 (tostring (plist-get params :tostring))
19128 (multifile (plist-get params :multifile))
19129 (header (plist-get params :header))
19130 (maxlevel (or (plist-get params :maxlevel) 3))
19131 (step (plist-get params :step))
19132 (emph (plist-get params :emphasize))
19133 (ts (plist-get params :tstart))
19134 (te (plist-get params :tend))
19135 (block (plist-get params :block))
19136 ipos time h m p level hlc hdl
19137 cc beg end pos tbl)
19138 (when step
19139 (org-clocktable-steps params)
19140 (throw 'exit nil))
19141 (when block
19142 (setq cc (org-clock-special-range block nil t)
19143 ts (car cc) te (cdr cc)))
19144 (if ts (setq ts (time-to-seconds
19145 (apply 'encode-time (org-parse-time-string ts)))))
19146 (if te (setq te (time-to-seconds
19147 (apply 'encode-time (org-parse-time-string te)))))
19148 (move-marker ins (point))
19149 (setq ipos (point))
19151 ;; Get the right scope
19152 (setq pos (point))
19153 (save-restriction
19154 (cond
19155 ((not scope))
19156 ((eq scope 'file) (widen))
19157 ((eq scope 'subtree) (org-narrow-to-subtree))
19158 ((eq scope 'tree)
19159 (while (org-up-heading-safe))
19160 (org-narrow-to-subtree))
19161 ((and (symbolp scope) (string-match "^tree\\([0-9]+\\)$"
19162 (symbol-name scope)))
19163 (setq level (string-to-number (match-string 1 (symbol-name scope))))
19164 (catch 'exit
19165 (while (org-up-heading-safe)
19166 (looking-at outline-regexp)
19167 (if (<= (org-reduced-level (funcall outline-level)) level)
19168 (throw 'exit nil))))
19169 (org-narrow-to-subtree))
19170 ((or (listp scope) (eq scope 'agenda))
19171 (let* ((files (if (listp scope) scope (org-agenda-files)))
19172 (scope 'agenda)
19173 (p1 (copy-sequence params))
19174 file)
19175 (plist-put p1 :tostring t)
19176 (plist-put p1 :multifile t)
19177 (plist-put p1 :scope 'file)
19178 (org-prepare-agenda-buffers files)
19179 (while (setq file (pop files))
19180 (with-current-buffer (find-buffer-visiting file)
19181 (push (org-clocktable-add-file
19182 file (org-dblock-write:clocktable p1)) tbl)
19183 (setq total-time (+ (or total-time 0)
19184 org-clock-file-total-minutes)))))))
19185 (goto-char pos)
19187 (unless (eq scope 'agenda)
19188 (org-clock-sum ts te)
19189 (goto-char (point-min))
19190 (while (setq p (next-single-property-change (point) :org-clock-minutes))
19191 (goto-char p)
19192 (when (setq time (get-text-property p :org-clock-minutes))
19193 (save-excursion
19194 (beginning-of-line 1)
19195 (when (and (looking-at (org-re "\\(\\*+\\)[ \t]+\\(.*?\\)\\([ \t]+:[[:alnum:]_@:]+:\\)?[ \t]*$"))
19196 (setq level (org-reduced-level
19197 (- (match-end 1) (match-beginning 1))))
19198 (<= level maxlevel))
19199 (setq hlc (if emph (or (cdr (assoc level hlchars)) "") "")
19200 hdl (match-string 2)
19201 h (/ time 60)
19202 m (- time (* 60 h)))
19203 (if (and (not multifile) (= level 1)) (push "|-" tbl))
19204 (push (concat
19205 "| " (int-to-string level) "|" hlc hdl hlc " |"
19206 (make-string (1- level) ?|)
19207 hlc (format "%d:%02d" h m) hlc
19208 " |") tbl))))))
19209 (setq tbl (nreverse tbl))
19210 (if tostring
19211 (if tbl (mapconcat 'identity tbl "\n") nil)
19212 (goto-char ins)
19213 (insert-before-markers
19214 (or header
19215 (concat
19216 "Clock summary at ["
19217 (substring
19218 (format-time-string (cdr org-time-stamp-formats))
19219 1 -1)
19220 "]."
19221 (if block
19222 (format " Considered range is /%s/." block)
19224 "\n\n"))
19225 (if (eq scope 'agenda) "|File" "")
19226 "|L|Headline|Time|\n")
19227 (setq total-time (or total-time org-clock-file-total-minutes)
19228 h (/ total-time 60)
19229 m (- total-time (* 60 h)))
19230 (insert-before-markers
19231 "|-\n|"
19232 (if (eq scope 'agenda) "|" "")
19234 "*Total time*| "
19235 (format "*%d:%02d*" h m)
19236 "|\n|-\n")
19237 (setq tbl (delq nil tbl))
19238 (if (and (stringp (car tbl)) (> (length (car tbl)) 1)
19239 (equal (substring (car tbl) 0 2) "|-"))
19240 (pop tbl))
19241 (insert-before-markers (mapconcat
19242 'identity (delq nil tbl)
19243 (if (eq scope 'agenda) "\n|-\n" "\n")))
19244 (backward-delete-char 1)
19245 (goto-char ipos)
19246 (skip-chars-forward "^|")
19247 (org-table-align))))))
19249 (defun org-clocktable-steps (params)
19250 (let* ((p1 (copy-sequence params))
19251 (ts (plist-get p1 :tstart))
19252 (te (plist-get p1 :tend))
19253 (step0 (plist-get p1 :step))
19254 (step (cdr (assoc step0 '((day . 86400) (week . 604800)))))
19255 (block (plist-get p1 :block))
19257 (when block
19258 (setq cc (org-clock-special-range block nil t)
19259 ts (car cc) te (cdr cc)))
19260 (if ts (setq ts (time-to-seconds
19261 (apply 'encode-time (org-parse-time-string ts)))))
19262 (if te (setq te (time-to-seconds
19263 (apply 'encode-time (org-parse-time-string te)))))
19264 (plist-put p1 :header "")
19265 (plist-put p1 :step nil)
19266 (plist-put p1 :block nil)
19267 (while (< ts te)
19268 (or (bolp) (insert "\n"))
19269 (plist-put p1 :tstart (format-time-string
19270 (car org-time-stamp-formats)
19271 (seconds-to-time ts)))
19272 (plist-put p1 :tend (format-time-string
19273 (car org-time-stamp-formats)
19274 (seconds-to-time (setq ts (+ ts step)))))
19275 (insert "\n" (if (eq step0 'day) "Daily report: " "Weekly report starting on: ")
19276 (plist-get p1 :tstart) "\n")
19277 (org-dblock-write:clocktable p1)
19278 (re-search-forward "#\\+END:")
19279 (end-of-line 0))))
19282 (defun org-clocktable-add-file (file table)
19283 (if table
19284 (let ((lines (org-split-string table "\n"))
19285 (ff (file-name-nondirectory file)))
19286 (mapconcat 'identity
19287 (mapcar (lambda (x)
19288 (if (string-match org-table-dataline-regexp x)
19289 (concat "|" ff x)
19291 lines)
19292 "\n"))))
19294 ;; FIXME: I don't think anybody uses this, ask David
19295 (defun org-collect-clock-time-entries ()
19296 "Return an internal list with clocking information.
19297 This list has one entry for each CLOCK interval.
19298 FIXME: describe the elements."
19299 (interactive)
19300 (let ((re (concat "^[ \t]*" org-clock-string
19301 " *\\[\\(.*?\\)\\]--\\[\\(.*?\\)\\]"))
19302 rtn beg end next cont level title total closedp leafp
19303 clockpos titlepos h m donep)
19304 (save-excursion
19305 (org-clock-sum)
19306 (goto-char (point-min))
19307 (while (re-search-forward re nil t)
19308 (setq clockpos (match-beginning 0)
19309 beg (match-string 1) end (match-string 2)
19310 cont (match-end 0))
19311 (setq beg (apply 'encode-time (org-parse-time-string beg))
19312 end (apply 'encode-time (org-parse-time-string end)))
19313 (org-back-to-heading t)
19314 (setq donep (org-entry-is-done-p))
19315 (setq titlepos (point)
19316 total (or (get-text-property (1+ (point)) :org-clock-minutes) 0)
19317 h (/ total 60) m (- total (* 60 h))
19318 total (cons h m))
19319 (looking-at "\\(\\*+\\) +\\(.*\\)")
19320 (setq level (- (match-end 1) (match-beginning 1))
19321 title (org-match-string-no-properties 2))
19322 (save-excursion (outline-next-heading) (setq next (point)))
19323 (setq closedp (re-search-forward org-closed-time-regexp next t))
19324 (goto-char next)
19325 (setq leafp (and (looking-at "^\\*+ ")
19326 (<= (- (match-end 0) (point)) level)))
19327 (push (list beg end clockpos closedp donep
19328 total title titlepos level leafp)
19329 rtn)
19330 (goto-char cont)))
19331 (nreverse rtn)))
19333 ;;;; Agenda, and Diary Integration
19335 ;;; Define the Org-agenda-mode
19337 (defvar org-agenda-mode-map (make-sparse-keymap)
19338 "Keymap for `org-agenda-mode'.")
19340 (defvar org-agenda-menu) ; defined later in this file.
19341 (defvar org-agenda-follow-mode nil)
19342 (defvar org-agenda-show-log nil)
19343 (defvar org-agenda-redo-command nil)
19344 (defvar org-agenda-query-string nil)
19345 (defvar org-agenda-mode-hook nil)
19346 (defvar org-agenda-type nil)
19347 (defvar org-agenda-force-single-file nil)
19349 (defun org-agenda-mode ()
19350 "Mode for time-sorted view on action items in Org-mode files.
19352 The following commands are available:
19354 \\{org-agenda-mode-map}"
19355 (interactive)
19356 (kill-all-local-variables)
19357 (setq org-agenda-undo-list nil
19358 org-agenda-pending-undo-list nil)
19359 (setq major-mode 'org-agenda-mode)
19360 ;; Keep global-font-lock-mode from turning on font-lock-mode
19361 (org-set-local 'font-lock-global-modes (list 'not major-mode))
19362 (setq mode-name "Org-Agenda")
19363 (use-local-map org-agenda-mode-map)
19364 (easy-menu-add org-agenda-menu)
19365 (if org-startup-truncated (setq truncate-lines t))
19366 (org-add-hook 'post-command-hook 'org-agenda-post-command-hook nil 'local)
19367 (org-add-hook 'pre-command-hook 'org-unhighlight nil 'local)
19368 ;; Make sure properties are removed when copying text
19369 (when (boundp 'buffer-substring-filters)
19370 (org-set-local 'buffer-substring-filters
19371 (cons (lambda (x)
19372 (set-text-properties 0 (length x) nil x) x)
19373 buffer-substring-filters)))
19374 (unless org-agenda-keep-modes
19375 (setq org-agenda-follow-mode org-agenda-start-with-follow-mode
19376 org-agenda-show-log nil))
19377 (easy-menu-change
19378 '("Agenda") "Agenda Files"
19379 (append
19380 (list
19381 (vector
19382 (if (get 'org-agenda-files 'org-restrict)
19383 "Restricted to single file"
19384 "Edit File List")
19385 '(org-edit-agenda-file-list)
19386 (not (get 'org-agenda-files 'org-restrict)))
19387 "--")
19388 (mapcar 'org-file-menu-entry (org-agenda-files))))
19389 (org-agenda-set-mode-name)
19390 (apply
19391 (if (fboundp 'run-mode-hooks) 'run-mode-hooks 'run-hooks)
19392 (list 'org-agenda-mode-hook)))
19394 (substitute-key-definition 'undo 'org-agenda-undo
19395 org-agenda-mode-map global-map)
19396 (org-defkey org-agenda-mode-map "\C-i" 'org-agenda-goto)
19397 (org-defkey org-agenda-mode-map [(tab)] 'org-agenda-goto)
19398 (org-defkey org-agenda-mode-map "\C-m" 'org-agenda-switch-to)
19399 (org-defkey org-agenda-mode-map "\C-k" 'org-agenda-kill)
19400 (org-defkey org-agenda-mode-map "\C-c$" 'org-agenda-archive)
19401 (org-defkey org-agenda-mode-map "\C-c\C-x\C-s" 'org-agenda-archive)
19402 (org-defkey org-agenda-mode-map "$" 'org-agenda-archive)
19403 (org-defkey org-agenda-mode-map "\C-c\C-o" 'org-agenda-open-link)
19404 (org-defkey org-agenda-mode-map " " 'org-agenda-show)
19405 (org-defkey org-agenda-mode-map "\C-c\C-t" 'org-agenda-todo)
19406 (org-defkey org-agenda-mode-map [(control shift right)] 'org-agenda-todo-nextset)
19407 (org-defkey org-agenda-mode-map [(control shift left)] 'org-agenda-todo-previousset)
19408 (org-defkey org-agenda-mode-map "\C-c\C-xb" 'org-agenda-tree-to-indirect-buffer)
19409 (org-defkey org-agenda-mode-map "b" 'org-agenda-tree-to-indirect-buffer)
19410 (org-defkey org-agenda-mode-map "o" 'delete-other-windows)
19411 (org-defkey org-agenda-mode-map "L" 'org-agenda-recenter)
19412 (org-defkey org-agenda-mode-map "t" 'org-agenda-todo)
19413 (org-defkey org-agenda-mode-map "a" 'org-agenda-toggle-archive-tag)
19414 (org-defkey org-agenda-mode-map ":" 'org-agenda-set-tags)
19415 (org-defkey org-agenda-mode-map "." 'org-agenda-goto-today)
19416 (org-defkey org-agenda-mode-map "j" 'org-agenda-goto-date)
19417 (org-defkey org-agenda-mode-map "d" 'org-agenda-day-view)
19418 (org-defkey org-agenda-mode-map "w" 'org-agenda-week-view)
19419 (org-defkey org-agenda-mode-map "m" 'org-agenda-month-view)
19420 (org-defkey org-agenda-mode-map "y" 'org-agenda-year-view)
19421 (org-defkey org-agenda-mode-map [(shift right)] 'org-agenda-date-later)
19422 (org-defkey org-agenda-mode-map [(shift left)] 'org-agenda-date-earlier)
19423 (org-defkey org-agenda-mode-map [?\C-c ?\C-x (right)] 'org-agenda-date-later)
19424 (org-defkey org-agenda-mode-map [?\C-c ?\C-x (left)] 'org-agenda-date-earlier)
19426 (org-defkey org-agenda-mode-map ">" 'org-agenda-date-prompt)
19427 (org-defkey org-agenda-mode-map "\C-c\C-s" 'org-agenda-schedule)
19428 (org-defkey org-agenda-mode-map "\C-c\C-d" 'org-agenda-deadline)
19429 (let ((l '(1 2 3 4 5 6 7 8 9 0)))
19430 (while l (org-defkey org-agenda-mode-map
19431 (int-to-string (pop l)) 'digit-argument)))
19433 (org-defkey org-agenda-mode-map "f" 'org-agenda-follow-mode)
19434 (org-defkey org-agenda-mode-map "l" 'org-agenda-log-mode)
19435 (org-defkey org-agenda-mode-map "D" 'org-agenda-toggle-diary)
19436 (org-defkey org-agenda-mode-map "G" 'org-agenda-toggle-time-grid)
19437 (org-defkey org-agenda-mode-map "r" 'org-agenda-redo)
19438 (org-defkey org-agenda-mode-map "g" 'org-agenda-redo)
19439 (org-defkey org-agenda-mode-map "e" 'org-agenda-execute)
19440 (org-defkey org-agenda-mode-map "q" 'org-agenda-quit)
19441 (org-defkey org-agenda-mode-map "x" 'org-agenda-exit)
19442 (org-defkey org-agenda-mode-map "\C-x\C-w" 'org-write-agenda)
19443 (org-defkey org-agenda-mode-map "s" 'org-save-all-org-buffers)
19444 (org-defkey org-agenda-mode-map "\C-x\C-s" 'org-save-all-org-buffers)
19445 (org-defkey org-agenda-mode-map "P" 'org-agenda-show-priority)
19446 (org-defkey org-agenda-mode-map "T" 'org-agenda-show-tags)
19447 (org-defkey org-agenda-mode-map "n" 'next-line)
19448 (org-defkey org-agenda-mode-map "p" 'previous-line)
19449 (org-defkey org-agenda-mode-map "\C-c\C-n" 'org-agenda-next-date-line)
19450 (org-defkey org-agenda-mode-map "\C-c\C-p" 'org-agenda-previous-date-line)
19451 (org-defkey org-agenda-mode-map "," 'org-agenda-priority)
19452 (org-defkey org-agenda-mode-map "\C-c," 'org-agenda-priority)
19453 (org-defkey org-agenda-mode-map "i" 'org-agenda-diary-entry)
19454 (org-defkey org-agenda-mode-map "c" 'org-agenda-goto-calendar)
19455 (eval-after-load "calendar"
19456 '(org-defkey calendar-mode-map org-calendar-to-agenda-key
19457 'org-calendar-goto-agenda))
19458 (org-defkey org-agenda-mode-map "C" 'org-agenda-convert-date)
19459 (org-defkey org-agenda-mode-map "M" 'org-agenda-phases-of-moon)
19460 (org-defkey org-agenda-mode-map "S" 'org-agenda-sunrise-sunset)
19461 (org-defkey org-agenda-mode-map "h" 'org-agenda-holidays)
19462 (org-defkey org-agenda-mode-map "H" 'org-agenda-holidays)
19463 (org-defkey org-agenda-mode-map "\C-c\C-x\C-i" 'org-agenda-clock-in)
19464 (org-defkey org-agenda-mode-map "I" 'org-agenda-clock-in)
19465 (org-defkey org-agenda-mode-map "\C-c\C-x\C-o" 'org-agenda-clock-out)
19466 (org-defkey org-agenda-mode-map "O" 'org-agenda-clock-out)
19467 (org-defkey org-agenda-mode-map "\C-c\C-x\C-x" 'org-agenda-clock-cancel)
19468 (org-defkey org-agenda-mode-map "X" 'org-agenda-clock-cancel)
19469 (org-defkey org-agenda-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
19470 (org-defkey org-agenda-mode-map "J" 'org-clock-goto)
19471 (org-defkey org-agenda-mode-map "+" 'org-agenda-priority-up)
19472 (org-defkey org-agenda-mode-map "-" 'org-agenda-priority-down)
19473 (org-defkey org-agenda-mode-map [(shift up)] 'org-agenda-priority-up)
19474 (org-defkey org-agenda-mode-map [(shift down)] 'org-agenda-priority-down)
19475 (org-defkey org-agenda-mode-map [?\C-c ?\C-x (up)] 'org-agenda-priority-up)
19476 (org-defkey org-agenda-mode-map [?\C-c ?\C-x (down)] 'org-agenda-priority-down)
19477 (org-defkey org-agenda-mode-map [(right)] 'org-agenda-later)
19478 (org-defkey org-agenda-mode-map [(left)] 'org-agenda-earlier)
19479 (org-defkey org-agenda-mode-map "\C-c\C-x\C-c" 'org-agenda-columns)
19481 (org-defkey org-agenda-mode-map "[" 'org-agenda-manipulate-query-add)
19482 (org-defkey org-agenda-mode-map "]" 'org-agenda-manipulate-query-subtract)
19483 (org-defkey org-agenda-mode-map "{" 'org-agenda-manipulate-query-add-re)
19484 (org-defkey org-agenda-mode-map "}" 'org-agenda-manipulate-query-subtract-re)
19486 (defvar org-agenda-keymap (copy-keymap org-agenda-mode-map)
19487 "Local keymap for agenda entries from Org-mode.")
19489 (org-defkey org-agenda-keymap
19490 (if (featurep 'xemacs) [(button2)] [(mouse-2)]) 'org-agenda-goto-mouse)
19491 (org-defkey org-agenda-keymap
19492 (if (featurep 'xemacs) [(button3)] [(mouse-3)]) 'org-agenda-show-mouse)
19493 (when org-agenda-mouse-1-follows-link
19494 (org-defkey org-agenda-keymap [follow-link] 'mouse-face))
19495 (easy-menu-define org-agenda-menu org-agenda-mode-map "Agenda menu"
19496 '("Agenda"
19497 ("Agenda Files")
19498 "--"
19499 ["Show" org-agenda-show t]
19500 ["Go To (other window)" org-agenda-goto t]
19501 ["Go To (this window)" org-agenda-switch-to t]
19502 ["Follow Mode" org-agenda-follow-mode
19503 :style toggle :selected org-agenda-follow-mode :active t]
19504 ["Tree to indirect frame" org-agenda-tree-to-indirect-buffer t]
19505 "--"
19506 ["Cycle TODO" org-agenda-todo t]
19507 ["Archive subtree" org-agenda-archive t]
19508 ["Delete subtree" org-agenda-kill t]
19509 "--"
19510 ["Goto Today" org-agenda-goto-today (org-agenda-check-type nil 'agenda 'timeline)]
19511 ["Next Dates" org-agenda-later (org-agenda-check-type nil 'agenda)]
19512 ["Previous Dates" org-agenda-earlier (org-agenda-check-type nil 'agenda)]
19513 ["Jump to date" org-agenda-goto-date (org-agenda-check-type nil 'agenda)]
19514 "--"
19515 ("Tags and Properties"
19516 ["Show all Tags" org-agenda-show-tags t]
19517 ["Set Tags current line" org-agenda-set-tags (not (org-region-active-p))]
19518 ["Change tag in region" org-agenda-set-tags (org-region-active-p)]
19519 "--"
19520 ["Column View" org-columns t])
19521 ("Date/Schedule"
19522 ["Schedule" org-agenda-schedule t]
19523 ["Set Deadline" org-agenda-deadline t]
19524 "--"
19525 ["Change Date +1 day" org-agenda-date-later (org-agenda-check-type nil 'agenda 'timeline)]
19526 ["Change Date -1 day" org-agenda-date-earlier (org-agenda-check-type nil 'agenda 'timeline)]
19527 ["Change Date to ..." org-agenda-date-prompt (org-agenda-check-type nil 'agenda 'timeline)])
19528 ("Clock"
19529 ["Clock in" org-agenda-clock-in t]
19530 ["Clock out" org-agenda-clock-out t]
19531 ["Clock cancel" org-agenda-clock-cancel t]
19532 ["Goto running clock" org-clock-goto t])
19533 ("Priority"
19534 ["Set Priority" org-agenda-priority t]
19535 ["Increase Priority" org-agenda-priority-up t]
19536 ["Decrease Priority" org-agenda-priority-down t]
19537 ["Show Priority" org-agenda-show-priority t])
19538 ("Calendar/Diary"
19539 ["New Diary Entry" org-agenda-diary-entry (org-agenda-check-type nil 'agenda 'timeline)]
19540 ["Goto Calendar" org-agenda-goto-calendar (org-agenda-check-type nil 'agenda 'timeline)]
19541 ["Phases of the Moon" org-agenda-phases-of-moon (org-agenda-check-type nil 'agenda 'timeline)]
19542 ["Sunrise/Sunset" org-agenda-sunrise-sunset (org-agenda-check-type nil 'agenda 'timeline)]
19543 ["Holidays" org-agenda-holidays (org-agenda-check-type nil 'agenda 'timeline)]
19544 ["Convert" org-agenda-convert-date (org-agenda-check-type nil 'agenda 'timeline)]
19545 "--"
19546 ["Create iCalendar file" org-export-icalendar-combine-agenda-files t])
19547 "--"
19548 ("View"
19549 ["Day View" org-agenda-day-view :active (org-agenda-check-type nil 'agenda)
19550 :style radio :selected (equal org-agenda-ndays 1)]
19551 ["Week View" org-agenda-week-view :active (org-agenda-check-type nil 'agenda)
19552 :style radio :selected (equal org-agenda-ndays 7)]
19553 ["Month View" org-agenda-month-view :active (org-agenda-check-type nil 'agenda)
19554 :style radio :selected (member org-agenda-ndays '(28 29 30 31))]
19555 ["Year View" org-agenda-year-view :active (org-agenda-check-type nil 'agenda)
19556 :style radio :selected (member org-agenda-ndays '(365 366))]
19557 "--"
19558 ["Show Logbook entries" org-agenda-log-mode
19559 :style toggle :selected org-agenda-show-log :active (org-agenda-check-type nil 'agenda 'timeline)]
19560 ["Include Diary" org-agenda-toggle-diary
19561 :style toggle :selected org-agenda-include-diary :active (org-agenda-check-type nil 'agenda)]
19562 ["Use Time Grid" org-agenda-toggle-time-grid
19563 :style toggle :selected org-agenda-use-time-grid :active (org-agenda-check-type nil 'agenda)])
19564 ["Write view to file" org-write-agenda t]
19565 ["Rebuild buffer" org-agenda-redo t]
19566 ["Save all Org-mode Buffers" org-save-all-org-buffers t]
19567 "--"
19568 ["Undo Remote Editing" org-agenda-undo org-agenda-undo-list]
19569 "--"
19570 ["Quit" org-agenda-quit t]
19571 ["Exit and Release Buffers" org-agenda-exit t]
19574 ;;; Agenda undo
19576 (defvar org-agenda-allow-remote-undo t
19577 "Non-nil means, allow remote undo from the agenda buffer.")
19578 (defvar org-agenda-undo-list nil
19579 "List of undoable operations in the agenda since last refresh.")
19580 (defvar org-agenda-undo-has-started-in nil
19581 "Buffers that have already seen `undo-start' in the current undo sequence.")
19582 (defvar org-agenda-pending-undo-list nil
19583 "In a series of undo commands, this is the list of remaning undo items.")
19585 (defmacro org-if-unprotected (&rest body)
19586 "Execute BODY if there is no `org-protected' text property at point."
19587 (declare (debug t))
19588 `(unless (get-text-property (point) 'org-protected)
19589 ,@body))
19591 (defmacro org-with-remote-undo (_buffer &rest _body)
19592 "Execute BODY while recording undo information in two buffers."
19593 (declare (indent 1) (debug t))
19594 `(let ((_cline (org-current-line))
19595 (_cmd this-command)
19596 (_buf1 (current-buffer))
19597 (_buf2 ,_buffer)
19598 (_undo1 buffer-undo-list)
19599 (_undo2 (with-current-buffer ,_buffer buffer-undo-list))
19600 _c1 _c2)
19601 ,@_body
19602 (when org-agenda-allow-remote-undo
19603 (setq _c1 (org-verify-change-for-undo
19604 _undo1 (with-current-buffer _buf1 buffer-undo-list))
19605 _c2 (org-verify-change-for-undo
19606 _undo2 (with-current-buffer _buf2 buffer-undo-list)))
19607 (when (or _c1 _c2)
19608 ;; make sure there are undo boundaries
19609 (and _c1 (with-current-buffer _buf1 (undo-boundary)))
19610 (and _c2 (with-current-buffer _buf2 (undo-boundary)))
19611 ;; remember which buffer to undo
19612 (push (list _cmd _cline _buf1 _c1 _buf2 _c2)
19613 org-agenda-undo-list)))))
19615 (defun org-agenda-undo ()
19616 "Undo a remote editing step in the agenda.
19617 This undoes changes both in the agenda buffer and in the remote buffer
19618 that have been changed along."
19619 (interactive)
19620 (or org-agenda-allow-remote-undo
19621 (error "Check the variable `org-agenda-allow-remote-undo' to activate remote undo."))
19622 (if (not (eq this-command last-command))
19623 (setq org-agenda-undo-has-started-in nil
19624 org-agenda-pending-undo-list org-agenda-undo-list))
19625 (if (not org-agenda-pending-undo-list)
19626 (error "No further undo information"))
19627 (let* ((entry (pop org-agenda-pending-undo-list))
19628 buf line cmd rembuf)
19629 (setq cmd (pop entry) line (pop entry))
19630 (setq rembuf (nth 2 entry))
19631 (org-with-remote-undo rembuf
19632 (while (bufferp (setq buf (pop entry)))
19633 (if (pop entry)
19634 (with-current-buffer buf
19635 (let ((last-undo-buffer buf)
19636 (inhibit-read-only t))
19637 (unless (memq buf org-agenda-undo-has-started-in)
19638 (push buf org-agenda-undo-has-started-in)
19639 (make-local-variable 'pending-undo-list)
19640 (undo-start))
19641 (while (and pending-undo-list
19642 (listp pending-undo-list)
19643 (not (car pending-undo-list)))
19644 (pop pending-undo-list))
19645 (undo-more 1))))))
19646 (goto-line line)
19647 (message "`%s' undone (buffer %s)" cmd (buffer-name rembuf))))
19649 (defun org-verify-change-for-undo (l1 l2)
19650 "Verify that a real change occurred between the undo lists L1 and L2."
19651 (while (and l1 (listp l1) (null (car l1))) (pop l1))
19652 (while (and l2 (listp l2) (null (car l2))) (pop l2))
19653 (not (eq l1 l2)))
19655 ;;; Agenda dispatch
19657 (defvar org-agenda-restrict nil)
19658 (defvar org-agenda-restrict-begin (make-marker))
19659 (defvar org-agenda-restrict-end (make-marker))
19660 (defvar org-agenda-last-dispatch-buffer nil)
19661 (defvar org-agenda-overriding-restriction nil)
19663 ;;;###autoload
19664 (defun org-agenda (arg &optional keys restriction)
19665 "Dispatch agenda commands to collect entries to the agenda buffer.
19666 Prompts for a command to execute. Any prefix arg will be passed
19667 on to the selected command. The default selections are:
19669 a Call `org-agenda-list' to display the agenda for current day or week.
19670 t Call `org-todo-list' to display the global todo list.
19671 T Call `org-todo-list' to display the global todo list, select only
19672 entries with a specific TODO keyword (the user gets a prompt).
19673 m Call `org-tags-view' to display headlines with tags matching
19674 a condition (the user is prompted for the condition).
19675 M Like `m', but select only TODO entries, no ordinary headlines.
19676 L Create a timeline for the current buffer.
19677 e Export views to associated files.
19679 More commands can be added by configuring the variable
19680 `org-agenda-custom-commands'. In particular, specific tags and TODO keyword
19681 searches can be pre-defined in this way.
19683 If the current buffer is in Org-mode and visiting a file, you can also
19684 first press `<' once to indicate that the agenda should be temporarily
19685 \(until the next use of \\[org-agenda]) restricted to the current file.
19686 Pressing `<' twice means to restrict to the current subtree or region
19687 \(if active)."
19688 (interactive "P")
19689 (catch 'exit
19690 (let* ((prefix-descriptions nil)
19691 (org-agenda-custom-commands-orig org-agenda-custom-commands)
19692 (org-agenda-custom-commands
19693 ;; normalize different versions
19694 (delq nil
19695 (mapcar
19696 (lambda (x)
19697 (cond ((stringp (cdr x))
19698 (push x prefix-descriptions)
19699 nil)
19700 ((stringp (nth 1 x)) x)
19701 ((not (nth 1 x)) (cons (car x) (cons "" (cddr x))))
19702 (t (cons (car x) (cons "" (cdr x))))))
19703 org-agenda-custom-commands)))
19704 (buf (current-buffer))
19705 (bfn (buffer-file-name (buffer-base-buffer)))
19706 entry key type match lprops ans)
19707 ;; Turn off restriction unless there is an overriding one
19708 (unless org-agenda-overriding-restriction
19709 (put 'org-agenda-files 'org-restrict nil)
19710 (setq org-agenda-restrict nil)
19711 (move-marker org-agenda-restrict-begin nil)
19712 (move-marker org-agenda-restrict-end nil))
19713 ;; Delete old local properties
19714 (put 'org-agenda-redo-command 'org-lprops nil)
19715 ;; Remember where this call originated
19716 (setq org-agenda-last-dispatch-buffer (current-buffer))
19717 (unless keys
19718 (setq ans (org-agenda-get-restriction-and-command prefix-descriptions)
19719 keys (car ans)
19720 restriction (cdr ans)))
19721 ;; Estabish the restriction, if any
19722 (when (and (not org-agenda-overriding-restriction) restriction)
19723 (put 'org-agenda-files 'org-restrict (list bfn))
19724 (cond
19725 ((eq restriction 'region)
19726 (setq org-agenda-restrict t)
19727 (move-marker org-agenda-restrict-begin (region-beginning))
19728 (move-marker org-agenda-restrict-end (region-end)))
19729 ((eq restriction 'subtree)
19730 (save-excursion
19731 (setq org-agenda-restrict t)
19732 (org-back-to-heading t)
19733 (move-marker org-agenda-restrict-begin (point))
19734 (move-marker org-agenda-restrict-end
19735 (progn (org-end-of-subtree t)))))))
19737 (require 'calendar) ; FIXME: can we avoid this for some commands?
19738 ;; For example the todo list should not need it (but does...)
19739 (cond
19740 ((setq entry (assoc keys org-agenda-custom-commands))
19741 (if (or (symbolp (nth 2 entry)) (functionp (nth 2 entry)))
19742 (progn
19743 (setq type (nth 2 entry) match (nth 3 entry) lprops (nth 4 entry))
19744 (put 'org-agenda-redo-command 'org-lprops lprops)
19745 (cond
19746 ((eq type 'agenda)
19747 (org-let lprops '(org-agenda-list current-prefix-arg)))
19748 ((eq type 'alltodo)
19749 (org-let lprops '(org-todo-list current-prefix-arg)))
19750 ((eq type 'search)
19751 (org-let lprops '(org-search-view current-prefix-arg match)))
19752 ((eq type 'stuck)
19753 (org-let lprops '(org-agenda-list-stuck-projects
19754 current-prefix-arg)))
19755 ((eq type 'tags)
19756 (org-let lprops '(org-tags-view current-prefix-arg match)))
19757 ((eq type 'tags-todo)
19758 (org-let lprops '(org-tags-view '(4) match)))
19759 ((eq type 'todo)
19760 (org-let lprops '(org-todo-list match)))
19761 ((eq type 'tags-tree)
19762 (org-check-for-org-mode)
19763 (org-let lprops '(org-tags-sparse-tree current-prefix-arg match)))
19764 ((eq type 'todo-tree)
19765 (org-check-for-org-mode)
19766 (org-let lprops
19767 '(org-occur (concat "^" outline-regexp "[ \t]*"
19768 (regexp-quote match) "\\>"))))
19769 ((eq type 'occur-tree)
19770 (org-check-for-org-mode)
19771 (org-let lprops '(org-occur match)))
19772 ((functionp type)
19773 (org-let lprops '(funcall type match)))
19774 ((fboundp type)
19775 (org-let lprops '(funcall type match)))
19776 (t (error "Invalid custom agenda command type %s" type))))
19777 (org-run-agenda-series (nth 1 entry) (cddr entry))))
19778 ((equal keys "C")
19779 (setq org-agenda-custom-commands org-agenda-custom-commands-orig)
19780 (customize-variable 'org-agenda-custom-commands))
19781 ((equal keys "a") (call-interactively 'org-agenda-list))
19782 ((equal keys "s") (call-interactively 'org-search-view))
19783 ((equal keys "t") (call-interactively 'org-todo-list))
19784 ((equal keys "T") (org-call-with-arg 'org-todo-list (or arg '(4))))
19785 ((equal keys "m") (call-interactively 'org-tags-view))
19786 ((equal keys "M") (org-call-with-arg 'org-tags-view (or arg '(4))))
19787 ((equal keys "e") (call-interactively 'org-store-agenda-views))
19788 ((equal keys "L")
19789 (unless (org-mode-p)
19790 (error "This is not an Org-mode file"))
19791 (unless restriction
19792 (put 'org-agenda-files 'org-restrict (list bfn))
19793 (org-call-with-arg 'org-timeline arg)))
19794 ((equal keys "#") (call-interactively 'org-agenda-list-stuck-projects))
19795 ((equal keys "/") (call-interactively 'org-occur-in-agenda-files))
19796 ((equal keys "!") (customize-variable 'org-stuck-projects))
19797 (t (error "Invalid agenda key"))))))
19799 (defun org-agenda-normalize-custom-commands (cmds)
19800 (delq nil
19801 (mapcar
19802 (lambda (x)
19803 (cond ((stringp (cdr x)) nil)
19804 ((stringp (nth 1 x)) x)
19805 ((not (nth 1 x)) (cons (car x) (cons "" (cddr x))))
19806 (t (cons (car x) (cons "" (cdr x))))))
19807 cmds)))
19809 (defun org-agenda-get-restriction-and-command (prefix-descriptions)
19810 "The user interface for selecting an agenda command."
19811 (catch 'exit
19812 (let* ((bfn (buffer-file-name (buffer-base-buffer)))
19813 (restrict-ok (and bfn (org-mode-p)))
19814 (region-p (org-region-active-p))
19815 (custom org-agenda-custom-commands)
19816 (selstring "")
19817 restriction second-time
19818 c entry key type match prefixes rmheader header-end custom1 desc)
19819 (save-window-excursion
19820 (delete-other-windows)
19821 (org-switch-to-buffer-other-window " *Agenda Commands*")
19822 (erase-buffer)
19823 (insert (eval-when-compile
19824 (let ((header
19826 Press key for an agenda command: < Buffer,subtree/region restriction
19827 -------------------------------- > Remove restriction
19828 a Agenda for current week or day e Export agenda views
19829 t List of all TODO entries T Entries with special TODO kwd
19830 m Match a TAGS query M Like m, but only TODO entries
19831 L Timeline for current buffer # List stuck projects (!=configure)
19832 s Search for keywords C Configure custom agenda commands
19833 / Multi-occur
19835 (start 0))
19836 (while (string-match
19837 "\\(^\\| \\|(\\)\\(\\S-\\)\\( \\|=\\)"
19838 header start)
19839 (setq start (match-end 0))
19840 (add-text-properties (match-beginning 2) (match-end 2)
19841 '(face bold) header))
19842 header)))
19843 (setq header-end (move-marker (make-marker) (point)))
19844 (while t
19845 (setq custom1 custom)
19846 (when (eq rmheader t)
19847 (goto-line 1)
19848 (re-search-forward ":" nil t)
19849 (delete-region (match-end 0) (point-at-eol))
19850 (forward-char 1)
19851 (looking-at "-+")
19852 (delete-region (match-end 0) (point-at-eol))
19853 (move-marker header-end (match-end 0)))
19854 (goto-char header-end)
19855 (delete-region (point) (point-max))
19856 (while (setq entry (pop custom1))
19857 (setq key (car entry) desc (nth 1 entry)
19858 type (nth 2 entry) match (nth 3 entry))
19859 (if (> (length key) 1)
19860 (add-to-list 'prefixes (string-to-char key))
19861 (insert
19862 (format
19863 "\n%-4s%-14s: %s"
19864 (org-add-props (copy-sequence key)
19865 '(face bold))
19866 (cond
19867 ((string-match "\\S-" desc) desc)
19868 ((eq type 'agenda) "Agenda for current week or day")
19869 ((eq type 'alltodo) "List of all TODO entries")
19870 ((eq type 'search) "Word search")
19871 ((eq type 'stuck) "List of stuck projects")
19872 ((eq type 'todo) "TODO keyword")
19873 ((eq type 'tags) "Tags query")
19874 ((eq type 'tags-todo) "Tags (TODO)")
19875 ((eq type 'tags-tree) "Tags tree")
19876 ((eq type 'todo-tree) "TODO kwd tree")
19877 ((eq type 'occur-tree) "Occur tree")
19878 ((functionp type) (if (symbolp type)
19879 (symbol-name type)
19880 "Lambda expression"))
19881 (t "???"))
19882 (cond
19883 ((stringp match)
19884 (org-add-props match nil 'face 'org-warning))
19885 (match
19886 (format "set of %d commands" (length match)))
19887 (t ""))))))
19888 (when prefixes
19889 (mapc (lambda (x)
19890 (insert
19891 (format "\n%s %s"
19892 (org-add-props (char-to-string x)
19893 nil 'face 'bold)
19894 (or (cdr (assoc (concat selstring (char-to-string x))
19895 prefix-descriptions))
19896 "Prefix key"))))
19897 prefixes))
19898 (goto-char (point-min))
19899 (when (fboundp 'fit-window-to-buffer)
19900 (if second-time
19901 (if (not (pos-visible-in-window-p (point-max)))
19902 (fit-window-to-buffer))
19903 (setq second-time t)
19904 (fit-window-to-buffer)))
19905 (message "Press key for agenda command%s:"
19906 (if (or restrict-ok org-agenda-overriding-restriction)
19907 (if org-agenda-overriding-restriction
19908 " (restriction lock active)"
19909 (if restriction
19910 (format " (restricted to %s)" restriction)
19911 " (unrestricted)"))
19912 ""))
19913 (setq c (read-char-exclusive))
19914 (message "")
19915 (cond
19916 ((assoc (char-to-string c) custom)
19917 (setq selstring (concat selstring (char-to-string c)))
19918 (throw 'exit (cons selstring restriction)))
19919 ((memq c prefixes)
19920 (setq selstring (concat selstring (char-to-string c))
19921 prefixes nil
19922 rmheader (or rmheader t)
19923 custom (delq nil (mapcar
19924 (lambda (x)
19925 (if (or (= (length (car x)) 1)
19926 (/= (string-to-char (car x)) c))
19928 (cons (substring (car x) 1) (cdr x))))
19929 custom))))
19930 ((and (not restrict-ok) (memq c '(?1 ?0 ?<)))
19931 (message "Restriction is only possible in Org-mode buffers")
19932 (ding) (sit-for 1))
19933 ((eq c ?1)
19934 (org-agenda-remove-restriction-lock 'noupdate)
19935 (setq restriction 'buffer))
19936 ((eq c ?0)
19937 (org-agenda-remove-restriction-lock 'noupdate)
19938 (setq restriction (if region-p 'region 'subtree)))
19939 ((eq c ?<)
19940 (org-agenda-remove-restriction-lock 'noupdate)
19941 (setq restriction
19942 (cond
19943 ((eq restriction 'buffer)
19944 (if region-p 'region 'subtree))
19945 ((memq restriction '(subtree region))
19946 nil)
19947 (t 'buffer))))
19948 ((eq c ?>)
19949 (org-agenda-remove-restriction-lock 'noupdate)
19950 (setq restriction nil))
19951 ((and (equal selstring "") (memq c '(?s ?a ?t ?m ?L ?C ?e ?T ?M ?# ?! ?/)))
19952 (throw 'exit (cons (setq selstring (char-to-string c)) restriction)))
19953 ((and (> (length selstring) 0) (eq c ?\d))
19954 (delete-window)
19955 (org-agenda-get-restriction-and-command prefix-descriptions))
19957 ((equal c ?q) (error "Abort"))
19958 (t (error "Invalid key %c" c))))))))
19960 (defun org-run-agenda-series (name series)
19961 (org-prepare-agenda name)
19962 (let* ((org-agenda-multi t)
19963 (redo (list 'org-run-agenda-series name (list 'quote series)))
19964 (cmds (car series))
19965 (gprops (nth 1 series))
19966 match ;; The byte compiler incorrectly complains about this. Keep it!
19967 cmd type lprops)
19968 (while (setq cmd (pop cmds))
19969 (setq type (car cmd) match (nth 1 cmd) lprops (nth 2 cmd))
19970 (cond
19971 ((eq type 'agenda)
19972 (org-let2 gprops lprops
19973 '(call-interactively 'org-agenda-list)))
19974 ((eq type 'alltodo)
19975 (org-let2 gprops lprops
19976 '(call-interactively 'org-todo-list)))
19977 ((eq type 'search)
19978 (org-let2 gprops lprops
19979 '(org-search-view current-prefix-arg match)))
19980 ((eq type 'stuck)
19981 (org-let2 gprops lprops
19982 '(call-interactively 'org-agenda-list-stuck-projects)))
19983 ((eq type 'tags)
19984 (org-let2 gprops lprops
19985 '(org-tags-view current-prefix-arg match)))
19986 ((eq type 'tags-todo)
19987 (org-let2 gprops lprops
19988 '(org-tags-view '(4) match)))
19989 ((eq type 'todo)
19990 (org-let2 gprops lprops
19991 '(org-todo-list match)))
19992 ((fboundp type)
19993 (org-let2 gprops lprops
19994 '(funcall type match)))
19995 (t (error "Invalid type in command series"))))
19996 (widen)
19997 (setq org-agenda-redo-command redo)
19998 (goto-char (point-min)))
19999 (org-finalize-agenda))
20001 ;;;###autoload
20002 (defmacro org-batch-agenda (cmd-key &rest parameters)
20003 "Run an agenda command in batch mode and send the result to STDOUT.
20004 If CMD-KEY is a string of length 1, it is used as a key in
20005 `org-agenda-custom-commands' and triggers this command. If it is a
20006 longer string it is used as a tags/todo match string.
20007 Paramters are alternating variable names and values that will be bound
20008 before running the agenda command."
20009 (let (pars)
20010 (while parameters
20011 (push (list (pop parameters) (if parameters (pop parameters))) pars))
20012 (if (> (length cmd-key) 2)
20013 (eval (list 'let (nreverse pars)
20014 (list 'org-tags-view nil cmd-key)))
20015 (eval (list 'let (nreverse pars) (list 'org-agenda nil cmd-key))))
20016 (set-buffer org-agenda-buffer-name)
20017 (princ (org-encode-for-stdout (buffer-string)))))
20019 (defun org-encode-for-stdout (string)
20020 (if (fboundp 'encode-coding-string)
20021 (encode-coding-string string buffer-file-coding-system)
20022 string))
20024 (defvar org-agenda-info nil)
20026 ;;;###autoload
20027 (defmacro org-batch-agenda-csv (cmd-key &rest parameters)
20028 "Run an agenda command in batch mode and send the result to STDOUT.
20029 If CMD-KEY is a string of length 1, it is used as a key in
20030 `org-agenda-custom-commands' and triggers this command. If it is a
20031 longer string it is used as a tags/todo match string.
20032 Paramters are alternating variable names and values that will be bound
20033 before running the agenda command.
20035 The output gives a line for each selected agenda item. Each
20036 item is a list of comma-separated values, like this:
20038 category,head,type,todo,tags,date,time,extra,priority-l,priority-n
20040 category The category of the item
20041 head The headline, without TODO kwd, TAGS and PRIORITY
20042 type The type of the agenda entry, can be
20043 todo selected in TODO match
20044 tagsmatch selected in tags match
20045 diary imported from diary
20046 deadline a deadline on given date
20047 scheduled scheduled on given date
20048 timestamp entry has timestamp on given date
20049 closed entry was closed on given date
20050 upcoming-deadline warning about deadline
20051 past-scheduled forwarded scheduled item
20052 block entry has date block including g. date
20053 todo The todo keyword, if any
20054 tags All tags including inherited ones, separated by colons
20055 date The relevant date, like 2007-2-14
20056 time The time, like 15:00-16:50
20057 extra Sting with extra planning info
20058 priority-l The priority letter if any was given
20059 priority-n The computed numerical priority
20060 agenda-day The day in the agenda where this is listed"
20062 (let (pars)
20063 (while parameters
20064 (push (list (pop parameters) (if parameters (pop parameters))) pars))
20065 (push (list 'org-agenda-remove-tags t) pars)
20066 (if (> (length cmd-key) 2)
20067 (eval (list 'let (nreverse pars)
20068 (list 'org-tags-view nil cmd-key)))
20069 (eval (list 'let (nreverse pars) (list 'org-agenda nil cmd-key))))
20070 (set-buffer org-agenda-buffer-name)
20071 (let* ((lines (org-split-string (buffer-string) "\n"))
20072 line)
20073 (while (setq line (pop lines))
20074 (catch 'next
20075 (if (not (get-text-property 0 'org-category line)) (throw 'next nil))
20076 (setq org-agenda-info
20077 (org-fix-agenda-info (text-properties-at 0 line)))
20078 (princ
20079 (org-encode-for-stdout
20080 (mapconcat 'org-agenda-export-csv-mapper
20081 '(org-category txt type todo tags date time-of-day extra
20082 priority-letter priority agenda-day)
20083 ",")))
20084 (princ "\n"))))))
20086 (defun org-fix-agenda-info (props)
20087 "Make sure all properties on an agenda item have a canonical form,
20088 so the export commands can easily use it."
20089 (let (tmp re)
20090 (when (setq tmp (plist-get props 'tags))
20091 (setq props (plist-put props 'tags (mapconcat 'identity tmp ":"))))
20092 (when (setq tmp (plist-get props 'date))
20093 (if (integerp tmp) (setq tmp (calendar-gregorian-from-absolute tmp)))
20094 (let ((calendar-date-display-form '(year "-" month "-" day)))
20095 '((format "%4d, %9s %2s, %4s" dayname monthname day year))
20097 (setq tmp (calendar-date-string tmp)))
20098 (setq props (plist-put props 'date tmp)))
20099 (when (setq tmp (plist-get props 'day))
20100 (if (integerp tmp) (setq tmp (calendar-gregorian-from-absolute tmp)))
20101 (let ((calendar-date-display-form '(year "-" month "-" day)))
20102 (setq tmp (calendar-date-string tmp)))
20103 (setq props (plist-put props 'day tmp))
20104 (setq props (plist-put props 'agenda-day tmp)))
20105 (when (setq tmp (plist-get props 'txt))
20106 (when (string-match "\\[#\\([A-Z0-9]\\)\\] ?" tmp)
20107 (plist-put props 'priority-letter (match-string 1 tmp))
20108 (setq tmp (replace-match "" t t tmp)))
20109 (when (and (setq re (plist-get props 'org-todo-regexp))
20110 (setq re (concat "\\`\\.*" re " ?"))
20111 (string-match re tmp))
20112 (plist-put props 'todo (match-string 1 tmp))
20113 (setq tmp (replace-match "" t t tmp)))
20114 (plist-put props 'txt tmp)))
20115 props)
20117 (defun org-agenda-export-csv-mapper (prop)
20118 (let ((res (plist-get org-agenda-info prop)))
20119 (setq res
20120 (cond
20121 ((not res) "")
20122 ((stringp res) res)
20123 (t (prin1-to-string res))))
20124 (while (string-match "," res)
20125 (setq res (replace-match ";" t t res)))
20126 (org-trim res)))
20129 ;;;###autoload
20130 (defun org-store-agenda-views (&rest parameters)
20131 (interactive)
20132 (eval (list 'org-batch-store-agenda-views)))
20134 ;; FIXME, why is this a macro?????
20135 ;;;###autoload
20136 (defmacro org-batch-store-agenda-views (&rest parameters)
20137 "Run all custom agenda commands that have a file argument."
20138 (let ((cmds (org-agenda-normalize-custom-commands org-agenda-custom-commands))
20139 (pop-up-frames nil)
20140 (dir default-directory)
20141 pars cmd thiscmdkey files opts)
20142 (while parameters
20143 (push (list (pop parameters) (if parameters (pop parameters))) pars))
20144 (setq pars (reverse pars))
20145 (save-window-excursion
20146 (while cmds
20147 (setq cmd (pop cmds)
20148 thiscmdkey (car cmd)
20149 opts (nth 4 cmd)
20150 files (nth 5 cmd))
20151 (if (stringp files) (setq files (list files)))
20152 (when files
20153 (eval (list 'let (append org-agenda-exporter-settings opts pars)
20154 (list 'org-agenda nil thiscmdkey)))
20155 (set-buffer org-agenda-buffer-name)
20156 (while files
20157 (eval (list 'let (append org-agenda-exporter-settings opts pars)
20158 (list 'org-write-agenda
20159 (expand-file-name (pop files) dir) t))))
20160 (and (get-buffer org-agenda-buffer-name)
20161 (kill-buffer org-agenda-buffer-name)))))))
20163 (defun org-write-agenda (file &optional nosettings)
20164 "Write the current buffer (an agenda view) as a file.
20165 Depending on the extension of the file name, plain text (.txt),
20166 HTML (.html or .htm) or Postscript (.ps) is produced.
20167 If NOSETTINGS is given, do not scope the settings of
20168 `org-agenda-exporter-settings' into the export commands. This is used when
20169 the settings have already been scoped and we do not wish to overrule other,
20170 higher priority settings."
20171 (interactive "FWrite agenda to file: ")
20172 (if (not (file-writable-p file))
20173 (error "Cannot write agenda to file %s" file))
20174 (cond
20175 ((string-match "\\.html?\\'" file) (require 'htmlize))
20176 ((string-match "\\.ps\\'" file) (require 'ps-print)))
20177 (org-let (if nosettings nil org-agenda-exporter-settings)
20178 '(save-excursion
20179 (save-window-excursion
20180 (cond
20181 ((string-match "\\.html?\\'" file)
20182 (set-buffer (htmlize-buffer (current-buffer)))
20184 (when (and org-agenda-export-html-style
20185 (string-match "<style>" org-agenda-export-html-style))
20186 ;; replace <style> section with org-agenda-export-html-style
20187 (goto-char (point-min))
20188 (kill-region (- (search-forward "<style") 6)
20189 (search-forward "</style>"))
20190 (insert org-agenda-export-html-style))
20191 (write-file file)
20192 (kill-buffer (current-buffer))
20193 (message "HTML written to %s" file))
20194 ((string-match "\\.ps\\'" file)
20195 (ps-print-buffer-with-faces file)
20196 (message "Postscript written to %s" file))
20198 (let ((bs (buffer-string)))
20199 (find-file file)
20200 (insert bs)
20201 (save-buffer 0)
20202 (kill-buffer (current-buffer))
20203 (message "Plain text written to %s" file))))))
20204 (set-buffer org-agenda-buffer-name)))
20206 (defmacro org-no-read-only (&rest body)
20207 "Inhibit read-only for BODY."
20208 `(let ((inhibit-read-only t)) ,@body))
20210 (defun org-check-for-org-mode ()
20211 "Make sure current buffer is in org-mode. Error if not."
20212 (or (org-mode-p)
20213 (error "Cannot execute org-mode agenda command on buffer in %s."
20214 major-mode)))
20216 (defun org-fit-agenda-window ()
20217 "Fit the window to the buffer size."
20218 (and (memq org-agenda-window-setup '(reorganize-frame))
20219 (fboundp 'fit-window-to-buffer)
20220 (fit-window-to-buffer
20222 (floor (* (frame-height) (cdr org-agenda-window-frame-fractions)))
20223 (floor (* (frame-height) (car org-agenda-window-frame-fractions))))))
20225 ;;; Agenda file list
20227 (defun org-agenda-files (&optional unrestricted)
20228 "Get the list of agenda files.
20229 Optional UNRESTRICTED means return the full list even if a restriction
20230 is currently in place."
20231 (let ((files
20232 (cond
20233 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
20234 ((stringp org-agenda-files) (org-read-agenda-file-list))
20235 ((listp org-agenda-files) org-agenda-files)
20236 (t (error "Invalid value of `org-agenda-files'")))))
20237 (setq files (apply 'append
20238 (mapcar (lambda (f)
20239 (if (file-directory-p f)
20240 (directory-files f t
20241 org-agenda-file-regexp)
20242 (list f)))
20243 files)))
20244 (if org-agenda-skip-unavailable-files
20245 (delq nil
20246 (mapcar (function
20247 (lambda (file)
20248 (and (file-readable-p file) file)))
20249 files))
20250 files))) ; `org-check-agenda-file' will remove them from the list
20252 (defun org-edit-agenda-file-list ()
20253 "Edit the list of agenda files.
20254 Depending on setup, this either uses customize to edit the variable
20255 `org-agenda-files', or it visits the file that is holding the list. In the
20256 latter case, the buffer is set up in a way that saving it automatically kills
20257 the buffer and restores the previous window configuration."
20258 (interactive)
20259 (if (stringp org-agenda-files)
20260 (let ((cw (current-window-configuration)))
20261 (find-file org-agenda-files)
20262 (org-set-local 'org-window-configuration cw)
20263 (org-add-hook 'after-save-hook
20264 (lambda ()
20265 (set-window-configuration
20266 (prog1 org-window-configuration
20267 (kill-buffer (current-buffer))))
20268 (org-install-agenda-files-menu)
20269 (message "New agenda file list installed"))
20270 nil 'local)
20271 (message "%s" (substitute-command-keys
20272 "Edit list and finish with \\[save-buffer]")))
20273 (customize-variable 'org-agenda-files)))
20275 (defun org-store-new-agenda-file-list (list)
20276 "Set new value for the agenda file list and save it correcly."
20277 (if (stringp org-agenda-files)
20278 (let ((f org-agenda-files) b)
20279 (while (setq b (find-buffer-visiting f)) (kill-buffer b))
20280 (with-temp-file f
20281 (insert (mapconcat 'identity list "\n") "\n")))
20282 (let ((org-mode-hook nil) (default-major-mode 'fundamental-mode))
20283 (setq org-agenda-files list)
20284 (customize-save-variable 'org-agenda-files org-agenda-files))))
20286 (defun org-read-agenda-file-list ()
20287 "Read the list of agenda files from a file."
20288 (when (stringp org-agenda-files)
20289 (with-temp-buffer
20290 (insert-file-contents org-agenda-files)
20291 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*"))))
20294 ;;;###autoload
20295 (defun org-cycle-agenda-files ()
20296 "Cycle through the files in `org-agenda-files'.
20297 If the current buffer visits an agenda file, find the next one in the list.
20298 If the current buffer does not, find the first agenda file."
20299 (interactive)
20300 (let* ((fs (org-agenda-files t))
20301 (files (append fs (list (car fs))))
20302 (tcf (if buffer-file-name (file-truename buffer-file-name)))
20303 file)
20304 (unless files (error "No agenda files"))
20305 (catch 'exit
20306 (while (setq file (pop files))
20307 (if (equal (file-truename file) tcf)
20308 (when (car files)
20309 (find-file (car files))
20310 (throw 'exit t))))
20311 (find-file (car fs)))
20312 (if (buffer-base-buffer) (switch-to-buffer (buffer-base-buffer)))))
20314 (defun org-agenda-file-to-front (&optional to-end)
20315 "Move/add the current file to the top of the agenda file list.
20316 If the file is not present in the list, it is added to the front. If it is
20317 present, it is moved there. With optional argument TO-END, add/move to the
20318 end of the list."
20319 (interactive "P")
20320 (let ((org-agenda-skip-unavailable-files nil)
20321 (file-alist (mapcar (lambda (x)
20322 (cons (file-truename x) x))
20323 (org-agenda-files t)))
20324 (ctf (file-truename buffer-file-name))
20325 x had)
20326 (setq x (assoc ctf file-alist) had x)
20328 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
20329 (if to-end
20330 (setq file-alist (append (delq x file-alist) (list x)))
20331 (setq file-alist (cons x (delq x file-alist))))
20332 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
20333 (org-install-agenda-files-menu)
20334 (message "File %s to %s of agenda file list"
20335 (if had "moved" "added") (if to-end "end" "front"))))
20337 (defun org-remove-file (&optional file)
20338 "Remove current file from the list of files in variable `org-agenda-files'.
20339 These are the files which are being checked for agenda entries.
20340 Optional argument FILE means, use this file instead of the current."
20341 (interactive)
20342 (let* ((org-agenda-skip-unavailable-files nil)
20343 (file (or file buffer-file-name))
20344 (true-file (file-truename file))
20345 (afile (abbreviate-file-name file))
20346 (files (delq nil (mapcar
20347 (lambda (x)
20348 (if (equal true-file
20349 (file-truename x))
20350 nil x))
20351 (org-agenda-files t)))))
20352 (if (not (= (length files) (length (org-agenda-files t))))
20353 (progn
20354 (org-store-new-agenda-file-list files)
20355 (org-install-agenda-files-menu)
20356 (message "Removed file: %s" afile))
20357 (message "File was not in list: %s (not removed)" afile))))
20359 (defun org-file-menu-entry (file)
20360 (vector file (list 'find-file file) t))
20362 (defun org-check-agenda-file (file)
20363 "Make sure FILE exists. If not, ask user what to do."
20364 (when (not (file-exists-p file))
20365 (message "non-existent file %s. [R]emove from list or [A]bort?"
20366 (abbreviate-file-name file))
20367 (let ((r (downcase (read-char-exclusive))))
20368 (cond
20369 ((equal r ?r)
20370 (org-remove-file file)
20371 (throw 'nextfile t))
20372 (t (error "Abort"))))))
20374 ;;; Agenda prepare and finalize
20376 (defvar org-agenda-multi nil) ; dynammically scoped
20377 (defvar org-agenda-buffer-name "*Org Agenda*")
20378 (defvar org-pre-agenda-window-conf nil)
20379 (defvar org-agenda-name nil)
20380 (defun org-prepare-agenda (&optional name)
20381 (setq org-todo-keywords-for-agenda nil)
20382 (setq org-done-keywords-for-agenda nil)
20383 (if org-agenda-multi
20384 (progn
20385 (setq buffer-read-only nil)
20386 (goto-char (point-max))
20387 (unless (or (bobp) org-agenda-compact-blocks)
20388 (insert "\n" (make-string (window-width) ?=) "\n"))
20389 (narrow-to-region (point) (point-max)))
20390 (org-agenda-reset-markers)
20391 (org-prepare-agenda-buffers (org-agenda-files))
20392 (setq org-todo-keywords-for-agenda
20393 (org-uniquify org-todo-keywords-for-agenda))
20394 (setq org-done-keywords-for-agenda
20395 (org-uniquify org-done-keywords-for-agenda))
20396 (let* ((abuf (get-buffer-create org-agenda-buffer-name))
20397 (awin (get-buffer-window abuf)))
20398 (cond
20399 ((equal (current-buffer) abuf) nil)
20400 (awin (select-window awin))
20401 ((not (setq org-pre-agenda-window-conf (current-window-configuration))))
20402 ((equal org-agenda-window-setup 'current-window)
20403 (switch-to-buffer abuf))
20404 ((equal org-agenda-window-setup 'other-window)
20405 (org-switch-to-buffer-other-window abuf))
20406 ((equal org-agenda-window-setup 'other-frame)
20407 (switch-to-buffer-other-frame abuf))
20408 ((equal org-agenda-window-setup 'reorganize-frame)
20409 (delete-other-windows)
20410 (org-switch-to-buffer-other-window abuf))))
20411 (setq buffer-read-only nil)
20412 (erase-buffer)
20413 (org-agenda-mode)
20414 (and name (not org-agenda-name)
20415 (org-set-local 'org-agenda-name name)))
20416 (setq buffer-read-only nil))
20418 (defun org-finalize-agenda ()
20419 "Finishing touch for the agenda buffer, called just before displaying it."
20420 (unless org-agenda-multi
20421 (save-excursion
20422 (let ((inhibit-read-only t))
20423 (goto-char (point-min))
20424 (while (org-activate-bracket-links (point-max))
20425 (add-text-properties (match-beginning 0) (match-end 0)
20426 '(face org-link)))
20427 (org-agenda-align-tags)
20428 (unless org-agenda-with-colors
20429 (remove-text-properties (point-min) (point-max) '(face nil))))
20430 (if (and (boundp 'org-overriding-columns-format)
20431 org-overriding-columns-format)
20432 (org-set-local 'org-overriding-columns-format
20433 org-overriding-columns-format))
20434 (if (and (boundp 'org-agenda-view-columns-initially)
20435 org-agenda-view-columns-initially)
20436 (org-agenda-columns))
20437 (when org-agenda-fontify-priorities
20438 (org-fontify-priorities))
20439 (run-hooks 'org-finalize-agenda-hook)
20440 (setq org-agenda-type (get-text-property (point) 'org-agenda-type))
20443 (defun org-fontify-priorities ()
20444 "Make highest priority lines bold, and lowest italic."
20445 (interactive)
20446 (mapc (lambda (o) (if (eq (org-overlay-get o 'org-type) 'org-priority)
20447 (org-delete-overlay o)))
20448 (org-overlays-in (point-min) (point-max)))
20449 (save-excursion
20450 (let ((inhibit-read-only t)
20451 b e p ov h l)
20452 (goto-char (point-min))
20453 (while (re-search-forward "\\[#\\(.\\)\\]" nil t)
20454 (setq h (or (get-char-property (point) 'org-highest-priority)
20455 org-highest-priority)
20456 l (or (get-char-property (point) 'org-lowest-priority)
20457 org-lowest-priority)
20458 p (string-to-char (match-string 1))
20459 b (match-beginning 0) e (point-at-eol)
20460 ov (org-make-overlay b e))
20461 (org-overlay-put
20462 ov 'face
20463 (cond ((listp org-agenda-fontify-priorities)
20464 (cdr (assoc p org-agenda-fontify-priorities)))
20465 ((equal p l) 'italic)
20466 ((equal p h) 'bold)))
20467 (org-overlay-put ov 'org-type 'org-priority)))))
20469 (defun org-prepare-agenda-buffers (files)
20470 "Create buffers for all agenda files, protect archived trees and comments."
20471 (interactive)
20472 (let ((pa '(:org-archived t))
20473 (pc '(:org-comment t))
20474 (pall '(:org-archived t :org-comment t))
20475 (inhibit-read-only t)
20476 (rea (concat ":" org-archive-tag ":"))
20477 bmp file re)
20478 (save-excursion
20479 (save-restriction
20480 (while (setq file (pop files))
20481 (if (bufferp file)
20482 (set-buffer file)
20483 (org-check-agenda-file file)
20484 (set-buffer (org-get-agenda-file-buffer file)))
20485 (widen)
20486 (setq bmp (buffer-modified-p))
20487 (org-refresh-category-properties)
20488 (setq org-todo-keywords-for-agenda
20489 (append org-todo-keywords-for-agenda org-todo-keywords-1))
20490 (setq org-done-keywords-for-agenda
20491 (append org-done-keywords-for-agenda org-done-keywords))
20492 (save-excursion
20493 (remove-text-properties (point-min) (point-max) pall)
20494 (when org-agenda-skip-archived-trees
20495 (goto-char (point-min))
20496 (while (re-search-forward rea nil t)
20497 (if (org-on-heading-p t)
20498 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
20499 (goto-char (point-min))
20500 (setq re (concat "^\\*+ +" org-comment-string "\\>"))
20501 (while (re-search-forward re nil t)
20502 (add-text-properties
20503 (match-beginning 0) (org-end-of-subtree t) pc)))
20504 (set-buffer-modified-p bmp))))))
20506 (defvar org-agenda-skip-function nil
20507 "Function to be called at each match during agenda construction.
20508 If this function returns nil, the current match should not be skipped.
20509 Otherwise, the function must return a position from where the search
20510 should be continued.
20511 This may also be a Lisp form, it will be evaluated.
20512 Never set this variable using `setq' or so, because then it will apply
20513 to all future agenda commands. Instead, bind it with `let' to scope
20514 it dynamically into the agenda-constructing command. A good way to set
20515 it is through options in org-agenda-custom-commands.")
20517 (defun org-agenda-skip ()
20518 "Throw to `:skip' in places that should be skipped.
20519 Also moves point to the end of the skipped region, so that search can
20520 continue from there."
20521 (let ((p (point-at-bol)) to fp)
20522 (and org-agenda-skip-archived-trees
20523 (get-text-property p :org-archived)
20524 (org-end-of-subtree t)
20525 (throw :skip t))
20526 (and (get-text-property p :org-comment)
20527 (org-end-of-subtree t)
20528 (throw :skip t))
20529 (if (equal (char-after p) ?#) (throw :skip t))
20530 (when (and (or (setq fp (functionp org-agenda-skip-function))
20531 (consp org-agenda-skip-function))
20532 (setq to (save-excursion
20533 (save-match-data
20534 (if fp
20535 (funcall org-agenda-skip-function)
20536 (eval org-agenda-skip-function))))))
20537 (goto-char to)
20538 (throw :skip t))))
20540 (defvar org-agenda-markers nil
20541 "List of all currently active markers created by `org-agenda'.")
20542 (defvar org-agenda-last-marker-time (time-to-seconds (current-time))
20543 "Creation time of the last agenda marker.")
20545 (defun org-agenda-new-marker (&optional pos)
20546 "Return a new agenda marker.
20547 Org-mode keeps a list of these markers and resets them when they are
20548 no longer in use."
20549 (let ((m (copy-marker (or pos (point)))))
20550 (setq org-agenda-last-marker-time (time-to-seconds (current-time)))
20551 (push m org-agenda-markers)
20554 (defun org-agenda-reset-markers ()
20555 "Reset markers created by `org-agenda'."
20556 (while org-agenda-markers
20557 (move-marker (pop org-agenda-markers) nil)))
20559 (defun org-get-agenda-file-buffer (file)
20560 "Get a buffer visiting FILE. If the buffer needs to be created, add
20561 it to the list of buffers which might be released later."
20562 (let ((buf (org-find-base-buffer-visiting file)))
20563 (if buf
20564 buf ; just return it
20565 ;; Make a new buffer and remember it
20566 (setq buf (find-file-noselect file))
20567 (if buf (push buf org-agenda-new-buffers))
20568 buf)))
20570 (defun org-release-buffers (blist)
20571 "Release all buffers in list, asking the user for confirmation when needed.
20572 When a buffer is unmodified, it is just killed. When modified, it is saved
20573 \(if the user agrees) and then killed."
20574 (let (buf file)
20575 (while (setq buf (pop blist))
20576 (setq file (buffer-file-name buf))
20577 (when (and (buffer-modified-p buf)
20578 file
20579 (y-or-n-p (format "Save file %s? " file)))
20580 (with-current-buffer buf (save-buffer)))
20581 (kill-buffer buf))))
20583 (defun org-get-category (&optional pos)
20584 "Get the category applying to position POS."
20585 (get-text-property (or pos (point)) 'org-category))
20587 ;;; Agenda timeline
20589 (defvar org-agenda-only-exact-dates nil) ; dynamically scoped
20591 (defun org-timeline (&optional include-all)
20592 "Show a time-sorted view of the entries in the current org file.
20593 Only entries with a time stamp of today or later will be listed. With
20594 \\[universal-argument] prefix, all unfinished TODO items will also be shown,
20595 under the current date.
20596 If the buffer contains an active region, only check the region for
20597 dates."
20598 (interactive "P")
20599 (require 'calendar)
20600 (org-compile-prefix-format 'timeline)
20601 (org-set-sorting-strategy 'timeline)
20602 (let* ((dopast t)
20603 (dotodo include-all)
20604 (doclosed org-agenda-show-log)
20605 (entry buffer-file-name)
20606 (date (calendar-current-date))
20607 (beg (if (org-region-active-p) (region-beginning) (point-min)))
20608 (end (if (org-region-active-p) (region-end) (point-max)))
20609 (day-numbers (org-get-all-dates beg end 'no-ranges
20610 t doclosed ; always include today
20611 org-timeline-show-empty-dates))
20612 (org-deadline-warning-days 0)
20613 (org-agenda-only-exact-dates t)
20614 (today (time-to-days (current-time)))
20615 (past t)
20616 args
20617 s e rtn d emptyp)
20618 (setq org-agenda-redo-command
20619 (list 'progn
20620 (list 'org-switch-to-buffer-other-window (current-buffer))
20621 (list 'org-timeline (list 'quote include-all))))
20622 (if (not dopast)
20623 ;; Remove past dates from the list of dates.
20624 (setq day-numbers (delq nil (mapcar (lambda(x)
20625 (if (>= x today) x nil))
20626 day-numbers))))
20627 (org-prepare-agenda (concat "Timeline "
20628 (file-name-nondirectory buffer-file-name)))
20629 (if doclosed (push :closed args))
20630 (push :timestamp args)
20631 (push :deadline args)
20632 (push :scheduled args)
20633 (push :sexp args)
20634 (if dotodo (push :todo args))
20635 (while (setq d (pop day-numbers))
20636 (if (and (listp d) (eq (car d) :omitted))
20637 (progn
20638 (setq s (point))
20639 (insert (format "\n[... %d empty days omitted]\n\n" (cdr d)))
20640 (put-text-property s (1- (point)) 'face 'org-agenda-structure))
20641 (if (listp d) (setq d (car d) emptyp t) (setq emptyp nil))
20642 (if (and (>= d today)
20643 dopast
20644 past)
20645 (progn
20646 (setq past nil)
20647 (insert (make-string 79 ?-) "\n")))
20648 (setq date (calendar-gregorian-from-absolute d))
20649 (setq s (point))
20650 (setq rtn (and (not emptyp)
20651 (apply 'org-agenda-get-day-entries entry
20652 date args)))
20653 (if (or rtn (equal d today) org-timeline-show-empty-dates)
20654 (progn
20655 (insert
20656 (if (stringp org-agenda-format-date)
20657 (format-time-string org-agenda-format-date
20658 (org-time-from-absolute date))
20659 (funcall org-agenda-format-date date))
20660 "\n")
20661 (put-text-property s (1- (point)) 'face 'org-agenda-structure)
20662 (put-text-property s (1- (point)) 'org-date-line t)
20663 (if (equal d today)
20664 (put-text-property s (1- (point)) 'org-today t))
20665 (and rtn (insert (org-finalize-agenda-entries rtn) "\n"))
20666 (put-text-property s (1- (point)) 'day d)))))
20667 (goto-char (point-min))
20668 (goto-char (or (text-property-any (point-min) (point-max) 'org-today t)
20669 (point-min)))
20670 (add-text-properties (point-min) (point-max) '(org-agenda-type timeline))
20671 (org-finalize-agenda)
20672 (setq buffer-read-only t)))
20674 (defun org-get-all-dates (beg end &optional no-ranges force-today inactive empty pre-re)
20675 "Return a list of all relevant day numbers from BEG to END buffer positions.
20676 If NO-RANGES is non-nil, include only the start and end dates of a range,
20677 not every single day in the range. If FORCE-TODAY is non-nil, make
20678 sure that TODAY is included in the list. If INACTIVE is non-nil, also
20679 inactive time stamps (those in square brackets) are included.
20680 When EMPTY is non-nil, also include days without any entries."
20681 (let ((re (concat
20682 (if pre-re pre-re "")
20683 (if inactive org-ts-regexp-both org-ts-regexp)))
20684 dates dates1 date day day1 day2 ts1 ts2)
20685 (if force-today
20686 (setq dates (list (time-to-days (current-time)))))
20687 (save-excursion
20688 (goto-char beg)
20689 (while (re-search-forward re end t)
20690 (setq day (time-to-days (org-time-string-to-time
20691 (substring (match-string 1) 0 10))))
20692 (or (memq day dates) (push day dates)))
20693 (unless no-ranges
20694 (goto-char beg)
20695 (while (re-search-forward org-tr-regexp end t)
20696 (setq ts1 (substring (match-string 1) 0 10)
20697 ts2 (substring (match-string 2) 0 10)
20698 day1 (time-to-days (org-time-string-to-time ts1))
20699 day2 (time-to-days (org-time-string-to-time ts2)))
20700 (while (< (setq day1 (1+ day1)) day2)
20701 (or (memq day1 dates) (push day1 dates)))))
20702 (setq dates (sort dates '<))
20703 (when empty
20704 (while (setq day (pop dates))
20705 (setq day2 (car dates))
20706 (push day dates1)
20707 (when (and day2 empty)
20708 (if (or (eq empty t)
20709 (and (numberp empty) (<= (- day2 day) empty)))
20710 (while (< (setq day (1+ day)) day2)
20711 (push (list day) dates1))
20712 (push (cons :omitted (- day2 day)) dates1))))
20713 (setq dates (nreverse dates1)))
20714 dates)))
20716 ;;; Agenda Daily/Weekly
20718 (defvar org-agenda-overriding-arguments nil) ; dynamically scoped parameter
20719 (defvar org-agenda-start-day nil) ; dynamically scoped parameter
20720 (defvar org-agenda-last-arguments nil
20721 "The arguments of the previous call to org-agenda")
20722 (defvar org-starting-day nil) ; local variable in the agenda buffer
20723 (defvar org-agenda-span nil) ; local variable in the agenda buffer
20724 (defvar org-include-all-loc nil) ; local variable
20725 (defvar org-agenda-remove-date nil) ; dynamically scoped
20727 ;;;###autoload
20728 (defun org-agenda-list (&optional include-all start-day ndays)
20729 "Produce a daily/weekly view from all files in variable `org-agenda-files'.
20730 The view will be for the current day or week, but from the overview buffer
20731 you will be able to go to other days/weeks.
20733 With one \\[universal-argument] prefix argument INCLUDE-ALL,
20734 all unfinished TODO items will also be shown, before the agenda.
20735 This feature is considered obsolete, please use the TODO list or a block
20736 agenda instead.
20738 With a numeric prefix argument in an interactive call, the agenda will
20739 span INCLUDE-ALL days. Lisp programs should instead specify NDAYS to change
20740 the number of days. NDAYS defaults to `org-agenda-ndays'.
20742 START-DAY defaults to TODAY, or to the most recent match for the weekday
20743 given in `org-agenda-start-on-weekday'."
20744 (interactive "P")
20745 (if (and (integerp include-all) (> include-all 0))
20746 (setq ndays include-all include-all nil))
20747 (setq ndays (or ndays org-agenda-ndays)
20748 start-day (or start-day org-agenda-start-day))
20749 (if org-agenda-overriding-arguments
20750 (setq include-all (car org-agenda-overriding-arguments)
20751 start-day (nth 1 org-agenda-overriding-arguments)
20752 ndays (nth 2 org-agenda-overriding-arguments)))
20753 (if (stringp start-day)
20754 ;; Convert to an absolute day number
20755 (setq start-day (time-to-days (org-read-date nil t start-day))))
20756 (setq org-agenda-last-arguments (list include-all start-day ndays))
20757 (org-compile-prefix-format 'agenda)
20758 (org-set-sorting-strategy 'agenda)
20759 (require 'calendar)
20760 (let* ((org-agenda-start-on-weekday
20761 (if (or (equal ndays 7) (and (null ndays) (equal 7 org-agenda-ndays)))
20762 org-agenda-start-on-weekday nil))
20763 (thefiles (org-agenda-files))
20764 (files thefiles)
20765 (today (time-to-days
20766 (time-subtract (current-time)
20767 (list 0 (* 3600 org-extend-today-until) 0))))
20768 (sd (or start-day today))
20769 (start (if (or (null org-agenda-start-on-weekday)
20770 (< org-agenda-ndays 7))
20772 (let* ((nt (calendar-day-of-week
20773 (calendar-gregorian-from-absolute sd)))
20774 (n1 org-agenda-start-on-weekday)
20775 (d (- nt n1)))
20776 (- sd (+ (if (< d 0) 7 0) d)))))
20777 (day-numbers (list start))
20778 (day-cnt 0)
20779 (inhibit-redisplay (not debug-on-error))
20780 s e rtn rtnall file date d start-pos end-pos todayp nd)
20781 (setq org-agenda-redo-command
20782 (list 'org-agenda-list (list 'quote include-all) start-day ndays))
20783 ;; Make the list of days
20784 (setq ndays (or ndays org-agenda-ndays)
20785 nd ndays)
20786 (while (> ndays 1)
20787 (push (1+ (car day-numbers)) day-numbers)
20788 (setq ndays (1- ndays)))
20789 (setq day-numbers (nreverse day-numbers))
20790 (org-prepare-agenda "Day/Week")
20791 (org-set-local 'org-starting-day (car day-numbers))
20792 (org-set-local 'org-include-all-loc include-all)
20793 (org-set-local 'org-agenda-span
20794 (org-agenda-ndays-to-span nd))
20795 (when (and (or include-all org-agenda-include-all-todo)
20796 (member today day-numbers))
20797 (setq files thefiles
20798 rtnall nil)
20799 (while (setq file (pop files))
20800 (catch 'nextfile
20801 (org-check-agenda-file file)
20802 (setq date (calendar-gregorian-from-absolute today)
20803 rtn (org-agenda-get-day-entries
20804 file date :todo))
20805 (setq rtnall (append rtnall rtn))))
20806 (when rtnall
20807 (insert "ALL CURRENTLY OPEN TODO ITEMS:\n")
20808 (add-text-properties (point-min) (1- (point))
20809 (list 'face 'org-agenda-structure))
20810 (insert (org-finalize-agenda-entries rtnall) "\n")))
20811 (unless org-agenda-compact-blocks
20812 (setq s (point))
20813 (insert (capitalize (symbol-name (org-agenda-ndays-to-span nd)))
20814 "-agenda:\n")
20815 (add-text-properties s (1- (point)) (list 'face 'org-agenda-structure
20816 'org-date-line t)))
20817 (while (setq d (pop day-numbers))
20818 (setq date (calendar-gregorian-from-absolute d)
20819 s (point))
20820 (if (or (setq todayp (= d today))
20821 (and (not start-pos) (= d sd)))
20822 (setq start-pos (point))
20823 (if (and start-pos (not end-pos))
20824 (setq end-pos (point))))
20825 (setq files thefiles
20826 rtnall nil)
20827 (while (setq file (pop files))
20828 (catch 'nextfile
20829 (org-check-agenda-file file)
20830 (if org-agenda-show-log
20831 (setq rtn (org-agenda-get-day-entries
20832 file date
20833 :deadline :scheduled :timestamp :sexp :closed))
20834 (setq rtn (org-agenda-get-day-entries
20835 file date
20836 :deadline :scheduled :sexp :timestamp)))
20837 (setq rtnall (append rtnall rtn))))
20838 (if org-agenda-include-diary
20839 (progn
20840 (require 'diary-lib)
20841 (setq rtn (org-get-entries-from-diary date))
20842 (setq rtnall (append rtnall rtn))))
20843 (if (or rtnall org-agenda-show-all-dates)
20844 (progn
20845 (setq day-cnt (1+ day-cnt))
20846 (insert
20847 (if (stringp org-agenda-format-date)
20848 (format-time-string org-agenda-format-date
20849 (org-time-from-absolute date))
20850 (funcall org-agenda-format-date date))
20851 "\n")
20852 (put-text-property s (1- (point)) 'face 'org-agenda-structure)
20853 (put-text-property s (1- (point)) 'org-date-line t)
20854 (put-text-property s (1- (point)) 'org-day-cnt day-cnt)
20855 (if todayp (put-text-property s (1- (point)) 'org-today t))
20856 (if rtnall (insert
20857 (org-finalize-agenda-entries
20858 (org-agenda-add-time-grid-maybe
20859 rtnall nd todayp))
20860 "\n"))
20861 (put-text-property s (1- (point)) 'day d)
20862 (put-text-property s (1- (point)) 'org-day-cnt day-cnt))))
20863 (goto-char (point-min))
20864 (org-fit-agenda-window)
20865 (unless (and (pos-visible-in-window-p (point-min))
20866 (pos-visible-in-window-p (point-max)))
20867 (goto-char (1- (point-max)))
20868 (recenter -1)
20869 (if (not (pos-visible-in-window-p (or start-pos 1)))
20870 (progn
20871 (goto-char (or start-pos 1))
20872 (recenter 1))))
20873 (goto-char (or start-pos 1))
20874 (add-text-properties (point-min) (point-max) '(org-agenda-type agenda))
20875 (org-finalize-agenda)
20876 (setq buffer-read-only t)
20877 (message "")))
20879 (defun org-agenda-ndays-to-span (n)
20880 (cond ((< n 7) 'day) ((= n 7) 'week) ((< n 32) 'month) (t 'year)))
20882 ;;; Agenda word search
20884 (defvar org-agenda-search-history nil)
20886 ;;;###autoload
20887 (defun org-search-view (&optional arg string)
20888 "Show all entries that contain words or regular expressions.
20889 If the first character of the search string is an asterisks,
20890 search only the headlines.
20892 The search string is broken into \"words\" by splitting at whitespace.
20893 The individual words are then interpreted as a boolean expression with
20894 logical AND. Words prefixed with a minus must not occur in the entry.
20895 Words without a prefix or prefixed with a plus must occur in the entry.
20896 Matching is case-insensitive and the words are enclosed by word delimiters.
20898 Words enclosed by curly braces are interpreted as regular expressions
20899 that must or must not match in the entry.
20901 This command searches the agenda files, and in addition the files listed
20902 in `org-agenda-text-search-extra-files'."
20903 (interactive "P")
20904 (org-compile-prefix-format 'search)
20905 (org-set-sorting-strategy 'search)
20906 (org-prepare-agenda "SEARCH")
20907 (let* ((props (list 'face nil
20908 'done-face 'org-done
20909 'org-not-done-regexp org-not-done-regexp
20910 'org-todo-regexp org-todo-regexp
20911 'mouse-face 'highlight
20912 'keymap org-agenda-keymap
20913 'help-echo (format "mouse-2 or RET jump to location")))
20914 regexp rtn rtnall files file pos
20915 marker priority category tags c neg re
20916 ee txt beg end words regexps+ regexps- hdl-only buffer beg1 str)
20917 (unless (and (not arg)
20918 (stringp string)
20919 (string-match "\\S-" string))
20920 (setq string (read-string "[+-]Word/{Regexp} ...: "
20921 (cond
20922 ((integerp arg) (cons string arg))
20923 (arg string))
20924 'org-agenda-search-history)))
20925 (setq org-agenda-redo-command
20926 (list 'org-search-view 'current-prefix-arg string))
20927 (setq org-agenda-query-string string)
20929 (if (equal (string-to-char string) ?*)
20930 (setq hdl-only t
20931 words (substring string 1))
20932 (setq words string))
20933 (setq words (org-split-string words))
20934 (mapc (lambda (w)
20935 (setq c (string-to-char w))
20936 (if (equal c ?-)
20937 (setq neg t w (substring w 1))
20938 (if (equal c ?+)
20939 (setq neg nil w (substring w 1))
20940 (setq neg nil)))
20941 (if (string-match "\\`{.*}\\'" w)
20942 (setq re (substring w 1 -1))
20943 (setq re (concat "\\<" (regexp-quote (downcase w)) "\\>")))
20944 (if neg (push re regexps-) (push re regexps+)))
20945 words)
20946 (setq regexps+ (sort regexps+ (lambda (a b) (> (length a) (length b)))))
20947 (if (not regexps+)
20948 (setq regexp (concat "^" org-outline-regexp))
20949 (setq regexp (pop regexps+))
20950 (if hdl-only (setq regexp (concat "^" org-outline-regexp ".*?"
20951 regexp))))
20952 (setq files (append (org-agenda-files) org-agenda-text-search-extra-files)
20953 rtnall nil)
20954 (while (setq file (pop files))
20955 (setq ee nil)
20956 (catch 'nextfile
20957 (org-check-agenda-file file)
20958 (setq buffer (if (file-exists-p file)
20959 (org-get-agenda-file-buffer file)
20960 (error "No such file %s" file)))
20961 (if (not buffer)
20962 ;; If file does not exist, make sure an error message is sent
20963 (setq rtn (list (format "ORG-AGENDA-ERROR: No such org-file %s"
20964 file))))
20965 (with-current-buffer buffer
20966 (unless (org-mode-p)
20967 (error "Agenda file %s is not in `org-mode'" file))
20968 (let ((case-fold-search t))
20969 (save-excursion
20970 (save-restriction
20971 (if org-agenda-restrict
20972 (narrow-to-region org-agenda-restrict-begin
20973 org-agenda-restrict-end)
20974 (widen))
20975 (goto-char (point-min))
20976 (unless (or (org-on-heading-p)
20977 (outline-next-heading))
20978 (throw 'nextfile t))
20979 (goto-char (max (point-min) (1- (point))))
20980 (while (re-search-forward regexp nil t)
20981 (org-back-to-heading t)
20982 (skip-chars-forward "* ")
20983 (setq beg (point-at-bol)
20984 beg1 (point)
20985 end (progn (outline-next-heading) (point)))
20986 (catch :skip
20987 (goto-char beg)
20988 (org-agenda-skip)
20989 (setq str (buffer-substring-no-properties
20990 (point-at-bol)
20991 (if hdl-only (point-at-eol) end)))
20992 (mapc (lambda (wr) (when (string-match wr str)
20993 (goto-char (1- end))
20994 (throw :skip t)))
20995 regexps-)
20996 (mapc (lambda (wr) (unless (string-match wr str)
20997 (goto-char (1- end))
20998 (throw :skip t)))
20999 regexps+)
21000 (goto-char beg)
21001 (setq marker (org-agenda-new-marker (point))
21002 category (org-get-category)
21003 tags (org-get-tags-at (point))
21004 txt (org-format-agenda-item
21006 (buffer-substring-no-properties
21007 beg1 (point-at-eol))
21008 category tags))
21009 (org-add-props txt props
21010 'org-marker marker 'org-hd-marker marker
21011 'priority 1000 'org-category category
21012 'type "search")
21013 (push txt ee)
21014 (goto-char (1- end)))))))))
21015 (setq rtn (nreverse ee))
21016 (setq rtnall (append rtnall rtn)))
21017 (if org-agenda-overriding-header
21018 (insert (org-add-props (copy-sequence org-agenda-overriding-header)
21019 nil 'face 'org-agenda-structure) "\n")
21020 (insert "Search words: ")
21021 (add-text-properties (point-min) (1- (point))
21022 (list 'face 'org-agenda-structure))
21023 (setq pos (point))
21024 (insert string "\n")
21025 (add-text-properties pos (1- (point)) (list 'face 'org-warning))
21026 (setq pos (point))
21027 (unless org-agenda-multi
21028 (insert "Press `[', `]' to add/sub word, `{', `}' to add/sub regexp, `C-u r' to edit\n")
21029 (add-text-properties pos (1- (point))
21030 (list 'face 'org-agenda-structure))))
21031 (when rtnall
21032 (insert (org-finalize-agenda-entries rtnall) "\n"))
21033 (goto-char (point-min))
21034 (org-fit-agenda-window)
21035 (add-text-properties (point-min) (point-max) '(org-agenda-type search))
21036 (org-finalize-agenda)
21037 (setq buffer-read-only t)))
21039 ;;; Agenda TODO list
21041 (defvar org-select-this-todo-keyword nil)
21042 (defvar org-last-arg nil)
21044 ;;;###autoload
21045 (defun org-todo-list (arg)
21046 "Show all TODO entries from all agenda file in a single list.
21047 The prefix arg can be used to select a specific TODO keyword and limit
21048 the list to these. When using \\[universal-argument], you will be prompted
21049 for a keyword. A numeric prefix directly selects the Nth keyword in
21050 `org-todo-keywords-1'."
21051 (interactive "P")
21052 (require 'calendar)
21053 (org-compile-prefix-format 'todo)
21054 (org-set-sorting-strategy 'todo)
21055 (org-prepare-agenda "TODO")
21056 (let* ((today (time-to-days (current-time)))
21057 (date (calendar-gregorian-from-absolute today))
21058 (kwds org-todo-keywords-for-agenda)
21059 (completion-ignore-case t)
21060 (org-select-this-todo-keyword
21061 (if (stringp arg) arg
21062 (and arg (integerp arg) (> arg 0)
21063 (nth (1- arg) kwds))))
21064 rtn rtnall files file pos)
21065 (when (equal arg '(4))
21066 (setq org-select-this-todo-keyword
21067 (completing-read "Keyword (or KWD1|K2D2|...): "
21068 (mapcar 'list kwds) nil nil)))
21069 (and (equal 0 arg) (setq org-select-this-todo-keyword nil))
21070 (org-set-local 'org-last-arg arg)
21071 (setq org-agenda-redo-command
21072 '(org-todo-list (or current-prefix-arg org-last-arg)))
21073 (setq files (org-agenda-files)
21074 rtnall nil)
21075 (while (setq file (pop files))
21076 (catch 'nextfile
21077 (org-check-agenda-file file)
21078 (setq rtn (org-agenda-get-day-entries file date :todo))
21079 (setq rtnall (append rtnall rtn))))
21080 (if org-agenda-overriding-header
21081 (insert (org-add-props (copy-sequence org-agenda-overriding-header)
21082 nil 'face 'org-agenda-structure) "\n")
21083 (insert "Global list of TODO items of type: ")
21084 (add-text-properties (point-min) (1- (point))
21085 (list 'face 'org-agenda-structure))
21086 (setq pos (point))
21087 (insert (or org-select-this-todo-keyword "ALL") "\n")
21088 (add-text-properties pos (1- (point)) (list 'face 'org-warning))
21089 (setq pos (point))
21090 (unless org-agenda-multi
21091 (insert "Available with `N r': (0)ALL")
21092 (let ((n 0) s)
21093 (mapc (lambda (x)
21094 (setq s (format "(%d)%s" (setq n (1+ n)) x))
21095 (if (> (+ (current-column) (string-width s) 1) (frame-width))
21096 (insert "\n "))
21097 (insert " " s))
21098 kwds))
21099 (insert "\n"))
21100 (add-text-properties pos (1- (point)) (list 'face 'org-agenda-structure)))
21101 (when rtnall
21102 (insert (org-finalize-agenda-entries rtnall) "\n"))
21103 (goto-char (point-min))
21104 (org-fit-agenda-window)
21105 (add-text-properties (point-min) (point-max) '(org-agenda-type todo))
21106 (org-finalize-agenda)
21107 (setq buffer-read-only t)))
21109 ;;; Agenda tags match
21111 ;;;###autoload
21112 (defun org-tags-view (&optional todo-only match)
21113 "Show all headlines for all `org-agenda-files' matching a TAGS criterion.
21114 The prefix arg TODO-ONLY limits the search to TODO entries."
21115 (interactive "P")
21116 (org-compile-prefix-format 'tags)
21117 (org-set-sorting-strategy 'tags)
21118 (let* ((org-tags-match-list-sublevels
21119 (if todo-only t org-tags-match-list-sublevels))
21120 (completion-ignore-case t)
21121 rtn rtnall files file pos matcher
21122 buffer)
21123 (setq matcher (org-make-tags-matcher match)
21124 match (car matcher) matcher (cdr matcher))
21125 (org-prepare-agenda (concat "TAGS " match))
21126 (setq org-agenda-redo-command
21127 (list 'org-tags-view (list 'quote todo-only)
21128 (list 'if 'current-prefix-arg nil match)))
21129 (setq files (org-agenda-files)
21130 rtnall nil)
21131 (while (setq file (pop files))
21132 (catch 'nextfile
21133 (org-check-agenda-file file)
21134 (setq buffer (if (file-exists-p file)
21135 (org-get-agenda-file-buffer file)
21136 (error "No such file %s" file)))
21137 (if (not buffer)
21138 ;; If file does not exist, merror message to agenda
21139 (setq rtn (list
21140 (format "ORG-AGENDA-ERROR: No such org-file %s" file))
21141 rtnall (append rtnall rtn))
21142 (with-current-buffer buffer
21143 (unless (org-mode-p)
21144 (error "Agenda file %s is not in `org-mode'" file))
21145 (save-excursion
21146 (save-restriction
21147 (if org-agenda-restrict
21148 (narrow-to-region org-agenda-restrict-begin
21149 org-agenda-restrict-end)
21150 (widen))
21151 (setq rtn (org-scan-tags 'agenda matcher todo-only))
21152 (setq rtnall (append rtnall rtn))))))))
21153 (if org-agenda-overriding-header
21154 (insert (org-add-props (copy-sequence org-agenda-overriding-header)
21155 nil 'face 'org-agenda-structure) "\n")
21156 (insert "Headlines with TAGS match: ")
21157 (add-text-properties (point-min) (1- (point))
21158 (list 'face 'org-agenda-structure))
21159 (setq pos (point))
21160 (insert match "\n")
21161 (add-text-properties pos (1- (point)) (list 'face 'org-warning))
21162 (setq pos (point))
21163 (unless org-agenda-multi
21164 (insert "Press `C-u r' to search again with new search string\n"))
21165 (add-text-properties pos (1- (point)) (list 'face 'org-agenda-structure)))
21166 (when rtnall
21167 (insert (org-finalize-agenda-entries rtnall) "\n"))
21168 (goto-char (point-min))
21169 (org-fit-agenda-window)
21170 (add-text-properties (point-min) (point-max) '(org-agenda-type tags))
21171 (org-finalize-agenda)
21172 (setq buffer-read-only t)))
21174 ;;; Agenda Finding stuck projects
21176 (defvar org-agenda-skip-regexp nil
21177 "Regular expression used in skipping subtrees for the agenda.
21178 This is basically a temporary global variable that can be set and then
21179 used by user-defined selections using `org-agenda-skip-function'.")
21181 (defvar org-agenda-overriding-header nil
21182 "When this is set during todo and tags searches, will replace header.")
21184 (defun org-agenda-skip-subtree-when-regexp-matches ()
21185 "Checks if the current subtree contains match for `org-agenda-skip-regexp'.
21186 If yes, it returns the end position of this tree, causing agenda commands
21187 to skip this subtree. This is a function that can be put into
21188 `org-agenda-skip-function' for the duration of a command."
21189 (let ((end (save-excursion (org-end-of-subtree t)))
21190 skip)
21191 (save-excursion
21192 (setq skip (re-search-forward org-agenda-skip-regexp end t)))
21193 (and skip end)))
21195 (defun org-agenda-skip-entry-if (&rest conditions)
21196 "Skip entry if any of CONDITIONS is true.
21197 See `org-agenda-skip-if' for details."
21198 (org-agenda-skip-if nil conditions))
21200 (defun org-agenda-skip-subtree-if (&rest conditions)
21201 "Skip entry if any of CONDITIONS is true.
21202 See `org-agenda-skip-if' for details."
21203 (org-agenda-skip-if t conditions))
21205 (defun org-agenda-skip-if (subtree conditions)
21206 "Checks current entity for CONDITIONS.
21207 If SUBTREE is non-nil, the entire subtree is checked. Otherwise, only
21208 the entry, i.e. the text before the next heading is checked.
21210 CONDITIONS is a list of symbols, boolean OR is used to combine the results
21211 from different tests. Valid conditions are:
21213 scheduled Check if there is a scheduled cookie
21214 notscheduled Check if there is no scheduled cookie
21215 deadline Check if there is a deadline
21216 notdeadline Check if there is no deadline
21217 regexp Check if regexp matches
21218 notregexp Check if regexp does not match.
21220 The regexp is taken from the conditions list, it must come right after
21221 the `regexp' or `notregexp' element.
21223 If any of these conditions is met, this function returns the end point of
21224 the entity, causing the search to continue from there. This is a function
21225 that can be put into `org-agenda-skip-function' for the duration of a command."
21226 (let (beg end m)
21227 (org-back-to-heading t)
21228 (setq beg (point)
21229 end (if subtree
21230 (progn (org-end-of-subtree t) (point))
21231 (progn (outline-next-heading) (1- (point)))))
21232 (goto-char beg)
21233 (and
21235 (and (memq 'scheduled conditions)
21236 (re-search-forward org-scheduled-time-regexp end t))
21237 (and (memq 'notscheduled conditions)
21238 (not (re-search-forward org-scheduled-time-regexp end t)))
21239 (and (memq 'deadline conditions)
21240 (re-search-forward org-deadline-time-regexp end t))
21241 (and (memq 'notdeadline conditions)
21242 (not (re-search-forward org-deadline-time-regexp end t)))
21243 (and (setq m (memq 'regexp conditions))
21244 (stringp (nth 1 m))
21245 (re-search-forward (nth 1 m) end t))
21246 (and (setq m (memq 'notregexp conditions))
21247 (stringp (nth 1 m))
21248 (not (re-search-forward (nth 1 m) end t))))
21249 end)))
21251 ;;;###autoload
21252 (defun org-agenda-list-stuck-projects (&rest ignore)
21253 "Create agenda view for projects that are stuck.
21254 Stuck projects are project that have no next actions. For the definitions
21255 of what a project is and how to check if it stuck, customize the variable
21256 `org-stuck-projects'.
21257 MATCH is being ignored."
21258 (interactive)
21259 (let* ((org-agenda-skip-function 'org-agenda-skip-subtree-when-regexp-matches)
21260 ;; FIXME: we could have used org-agenda-skip-if here.
21261 (org-agenda-overriding-header "List of stuck projects: ")
21262 (matcher (nth 0 org-stuck-projects))
21263 (todo (nth 1 org-stuck-projects))
21264 (todo-wds (if (member "*" todo)
21265 (progn
21266 (org-prepare-agenda-buffers (org-agenda-files))
21267 (org-delete-all
21268 org-done-keywords-for-agenda
21269 (copy-sequence org-todo-keywords-for-agenda)))
21270 todo))
21271 (todo-re (concat "^\\*+[ \t]+\\("
21272 (mapconcat 'identity todo-wds "\\|")
21273 "\\)\\>"))
21274 (tags (nth 2 org-stuck-projects))
21275 (tags-re (if (member "*" tags)
21276 (org-re "^\\*+ .*:[[:alnum:]_@]+:[ \t]*$")
21277 (concat "^\\*+ .*:\\("
21278 (mapconcat 'identity tags "\\|")
21279 (org-re "\\):[[:alnum:]_@:]*[ \t]*$"))))
21280 (gen-re (nth 3 org-stuck-projects))
21281 (re-list
21282 (delq nil
21283 (list
21284 (if todo todo-re)
21285 (if tags tags-re)
21286 (and gen-re (stringp gen-re) (string-match "\\S-" gen-re)
21287 gen-re)))))
21288 (setq org-agenda-skip-regexp
21289 (if re-list
21290 (mapconcat 'identity re-list "\\|")
21291 (error "No information how to identify unstuck projects")))
21292 (org-tags-view nil matcher)
21293 (with-current-buffer org-agenda-buffer-name
21294 (setq org-agenda-redo-command
21295 '(org-agenda-list-stuck-projects
21296 (or current-prefix-arg org-last-arg))))))
21298 ;;; Diary integration
21300 (defvar org-disable-agenda-to-diary nil) ;Dynamically-scoped param.
21302 (defun org-get-entries-from-diary (date)
21303 "Get the (Emacs Calendar) diary entries for DATE."
21304 (let* ((fancy-diary-buffer "*temporary-fancy-diary-buffer*")
21305 (diary-display-hook '(fancy-diary-display))
21306 (pop-up-frames nil)
21307 (list-diary-entries-hook
21308 (cons 'org-diary-default-entry list-diary-entries-hook))
21309 (diary-file-name-prefix-function nil) ; turn this feature off
21310 (diary-modify-entry-list-string-function 'org-modify-diary-entry-string)
21311 entries
21312 (org-disable-agenda-to-diary t))
21313 (save-excursion
21314 (save-window-excursion
21315 (funcall (if (fboundp 'diary-list-entries)
21316 'diary-list-entries 'list-diary-entries)
21317 date 1)))
21318 (if (not (get-buffer fancy-diary-buffer))
21319 (setq entries nil)
21320 (with-current-buffer fancy-diary-buffer
21321 (setq buffer-read-only nil)
21322 (if (zerop (buffer-size))
21323 ;; No entries
21324 (setq entries nil)
21325 ;; Omit the date and other unnecessary stuff
21326 (org-agenda-cleanup-fancy-diary)
21327 ;; Add prefix to each line and extend the text properties
21328 (if (zerop (buffer-size))
21329 (setq entries nil)
21330 (setq entries (buffer-substring (point-min) (- (point-max) 1)))))
21331 (set-buffer-modified-p nil)
21332 (kill-buffer fancy-diary-buffer)))
21333 (when entries
21334 (setq entries (org-split-string entries "\n"))
21335 (setq entries
21336 (mapcar
21337 (lambda (x)
21338 (setq x (org-format-agenda-item "" x "Diary" nil 'time))
21339 ;; Extend the text properties to the beginning of the line
21340 (org-add-props x (text-properties-at (1- (length x)) x)
21341 'type "diary" 'date date))
21342 entries)))))
21344 (defun org-agenda-cleanup-fancy-diary ()
21345 "Remove unwanted stuff in buffer created by `fancy-diary-display'.
21346 This gets rid of the date, the underline under the date, and
21347 the dummy entry installed by `org-mode' to ensure non-empty diary for each
21348 date. It also removes lines that contain only whitespace."
21349 (goto-char (point-min))
21350 (if (looking-at ".*?:[ \t]*")
21351 (progn
21352 (replace-match "")
21353 (re-search-forward "\n=+$" nil t)
21354 (replace-match "")
21355 (while (re-search-backward "^ +\n?" nil t) (replace-match "")))
21356 (re-search-forward "\n=+$" nil t)
21357 (delete-region (point-min) (min (point-max) (1+ (match-end 0)))))
21358 (goto-char (point-min))
21359 (while (re-search-forward "^ +\n" nil t)
21360 (replace-match ""))
21361 (goto-char (point-min))
21362 (if (re-search-forward "^Org-mode dummy\n?" nil t)
21363 (replace-match "")))
21365 ;; Make sure entries from the diary have the right text properties.
21366 (eval-after-load "diary-lib"
21367 '(if (boundp 'diary-modify-entry-list-string-function)
21368 ;; We can rely on the hook, nothing to do
21370 ;; Hook not avaiable, must use advice to make this work
21371 (defadvice add-to-diary-list (before org-mark-diary-entry activate)
21372 "Make the position visible."
21373 (if (and org-disable-agenda-to-diary ;; called from org-agenda
21374 (stringp string)
21375 buffer-file-name)
21376 (setq string (org-modify-diary-entry-string string))))))
21378 (defun org-modify-diary-entry-string (string)
21379 "Add text properties to string, allowing org-mode to act on it."
21380 (org-add-props string nil
21381 'mouse-face 'highlight
21382 'keymap org-agenda-keymap
21383 'help-echo (if buffer-file-name
21384 (format "mouse-2 or RET jump to diary file %s"
21385 (abbreviate-file-name buffer-file-name))
21387 'org-agenda-diary-link t
21388 'org-marker (org-agenda-new-marker (point-at-bol))))
21390 (defun org-diary-default-entry ()
21391 "Add a dummy entry to the diary.
21392 Needed to avoid empty dates which mess up holiday display."
21393 ;; Catch the error if dealing with the new add-to-diary-alist
21394 (when org-disable-agenda-to-diary
21395 (condition-case nil
21396 (add-to-diary-list original-date "Org-mode dummy" "")
21397 (error
21398 (add-to-diary-list original-date "Org-mode dummy" "" nil)))))
21400 ;;;###autoload
21401 (defun org-diary (&rest args)
21402 "Return diary information from org-files.
21403 This function can be used in a \"sexp\" diary entry in the Emacs calendar.
21404 It accesses org files and extracts information from those files to be
21405 listed in the diary. The function accepts arguments specifying what
21406 items should be listed. The following arguments are allowed:
21408 :timestamp List the headlines of items containing a date stamp or
21409 date range matching the selected date. Deadlines will
21410 also be listed, on the expiration day.
21412 :sexp List entries resulting from diary-like sexps.
21414 :deadline List any deadlines past due, or due within
21415 `org-deadline-warning-days'. The listing occurs only
21416 in the diary for *today*, not at any other date. If
21417 an entry is marked DONE, it is no longer listed.
21419 :scheduled List all items which are scheduled for the given date.
21420 The diary for *today* also contains items which were
21421 scheduled earlier and are not yet marked DONE.
21423 :todo List all TODO items from the org-file. This may be a
21424 long list - so this is not turned on by default.
21425 Like deadlines, these entries only show up in the
21426 diary for *today*, not at any other date.
21428 The call in the diary file should look like this:
21430 &%%(org-diary) ~/path/to/some/orgfile.org
21432 Use a separate line for each org file to check. Or, if you omit the file name,
21433 all files listed in `org-agenda-files' will be checked automatically:
21435 &%%(org-diary)
21437 If you don't give any arguments (as in the example above), the default
21438 arguments (:deadline :scheduled :timestamp :sexp) are used.
21439 So the example above may also be written as
21441 &%%(org-diary :deadline :timestamp :sexp :scheduled)
21443 The function expects the lisp variables `entry' and `date' to be provided
21444 by the caller, because this is how the calendar works. Don't use this
21445 function from a program - use `org-agenda-get-day-entries' instead."
21446 (when (> (- (time-to-seconds (current-time))
21447 org-agenda-last-marker-time)
21449 (org-agenda-reset-markers))
21450 (org-compile-prefix-format 'agenda)
21451 (org-set-sorting-strategy 'agenda)
21452 (setq args (or args '(:deadline :scheduled :timestamp :sexp)))
21453 (let* ((files (if (and entry (stringp entry) (string-match "\\S-" entry))
21454 (list entry)
21455 (org-agenda-files t)))
21456 file rtn results)
21457 (org-prepare-agenda-buffers files)
21458 ;; If this is called during org-agenda, don't return any entries to
21459 ;; the calendar. Org Agenda will list these entries itself.
21460 (if org-disable-agenda-to-diary (setq files nil))
21461 (while (setq file (pop files))
21462 (setq rtn (apply 'org-agenda-get-day-entries file date args))
21463 (setq results (append results rtn)))
21464 (if results
21465 (concat (org-finalize-agenda-entries results) "\n"))))
21467 ;;; Agenda entry finders
21469 (defun org-agenda-get-day-entries (file date &rest args)
21470 "Does the work for `org-diary' and `org-agenda'.
21471 FILE is the path to a file to be checked for entries. DATE is date like
21472 the one returned by `calendar-current-date'. ARGS are symbols indicating
21473 which kind of entries should be extracted. For details about these, see
21474 the documentation of `org-diary'."
21475 (setq args (or args '(:deadline :scheduled :timestamp :sexp)))
21476 (let* ((org-startup-folded nil)
21477 (org-startup-align-all-tables nil)
21478 (buffer (if (file-exists-p file)
21479 (org-get-agenda-file-buffer file)
21480 (error "No such file %s" file)))
21481 arg results rtn)
21482 (if (not buffer)
21483 ;; If file does not exist, make sure an error message ends up in diary
21484 (list (format "ORG-AGENDA-ERROR: No such org-file %s" file))
21485 (with-current-buffer buffer
21486 (unless (org-mode-p)
21487 (error "Agenda file %s is not in `org-mode'" file))
21488 (let ((case-fold-search nil))
21489 (save-excursion
21490 (save-restriction
21491 (if org-agenda-restrict
21492 (narrow-to-region org-agenda-restrict-begin
21493 org-agenda-restrict-end)
21494 (widen))
21495 ;; The way we repeatedly append to `results' makes it O(n^2) :-(
21496 (while (setq arg (pop args))
21497 (cond
21498 ((and (eq arg :todo)
21499 (equal date (calendar-current-date)))
21500 (setq rtn (org-agenda-get-todos))
21501 (setq results (append results rtn)))
21502 ((eq arg :timestamp)
21503 (setq rtn (org-agenda-get-blocks))
21504 (setq results (append results rtn))
21505 (setq rtn (org-agenda-get-timestamps))
21506 (setq results (append results rtn)))
21507 ((eq arg :sexp)
21508 (setq rtn (org-agenda-get-sexps))
21509 (setq results (append results rtn)))
21510 ((eq arg :scheduled)
21511 (setq rtn (org-agenda-get-scheduled))
21512 (setq results (append results rtn)))
21513 ((eq arg :closed)
21514 (setq rtn (org-agenda-get-closed))
21515 (setq results (append results rtn)))
21516 ((eq arg :deadline)
21517 (setq rtn (org-agenda-get-deadlines))
21518 (setq results (append results rtn))))))))
21519 results))))
21521 (defun org-entry-is-todo-p ()
21522 (member (org-get-todo-state) org-not-done-keywords))
21524 (defun org-entry-is-done-p ()
21525 (member (org-get-todo-state) org-done-keywords))
21527 (defun org-get-todo-state ()
21528 (save-excursion
21529 (org-back-to-heading t)
21530 (and (looking-at org-todo-line-regexp)
21531 (match-end 2)
21532 (match-string 2))))
21534 (defun org-at-date-range-p (&optional inactive-ok)
21535 "Is the cursor inside a date range?"
21536 (interactive)
21537 (save-excursion
21538 (catch 'exit
21539 (let ((pos (point)))
21540 (skip-chars-backward "^[<\r\n")
21541 (skip-chars-backward "<[")
21542 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
21543 (>= (match-end 0) pos)
21544 (throw 'exit t))
21545 (skip-chars-backward "^<[\r\n")
21546 (skip-chars-backward "<[")
21547 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
21548 (>= (match-end 0) pos)
21549 (throw 'exit t)))
21550 nil)))
21552 (defun org-agenda-get-todos ()
21553 "Return the TODO information for agenda display."
21554 (let* ((props (list 'face nil
21555 'done-face 'org-done
21556 'org-not-done-regexp org-not-done-regexp
21557 'org-todo-regexp org-todo-regexp
21558 'mouse-face 'highlight
21559 'keymap org-agenda-keymap
21560 'help-echo
21561 (format "mouse-2 or RET jump to org file %s"
21562 (abbreviate-file-name buffer-file-name))))
21563 ;; FIXME: get rid of the \n at some point but watch out
21564 (regexp (concat "^\\*+[ \t]+\\("
21565 (if org-select-this-todo-keyword
21566 (if (equal org-select-this-todo-keyword "*")
21567 org-todo-regexp
21568 (concat "\\<\\("
21569 (mapconcat 'identity (org-split-string org-select-this-todo-keyword "|") "\\|")
21570 "\\)\\>"))
21571 org-not-done-regexp)
21572 "[^\n\r]*\\)"))
21573 marker priority category tags
21574 ee txt beg end)
21575 (goto-char (point-min))
21576 (while (re-search-forward regexp nil t)
21577 (catch :skip
21578 (save-match-data
21579 (beginning-of-line)
21580 (setq beg (point) end (progn (outline-next-heading) (point)))
21581 (when (or (and org-agenda-todo-ignore-with-date (goto-char beg)
21582 (re-search-forward org-ts-regexp end t))
21583 (and org-agenda-todo-ignore-scheduled (goto-char beg)
21584 (re-search-forward org-scheduled-time-regexp end t))
21585 (and org-agenda-todo-ignore-deadlines (goto-char beg)
21586 (re-search-forward org-deadline-time-regexp end t)
21587 (org-deadline-close (match-string 1))))
21588 (goto-char (1+ beg))
21589 (or org-agenda-todo-list-sublevels (org-end-of-subtree 'invisible))
21590 (throw :skip nil)))
21591 (goto-char beg)
21592 (org-agenda-skip)
21593 (goto-char (match-beginning 1))
21594 (setq marker (org-agenda-new-marker (match-beginning 0))
21595 category (org-get-category)
21596 tags (org-get-tags-at (point))
21597 txt (org-format-agenda-item "" (match-string 1) category tags)
21598 priority (1+ (org-get-priority txt)))
21599 (org-add-props txt props
21600 'org-marker marker 'org-hd-marker marker
21601 'priority priority 'org-category category
21602 'type "todo")
21603 (push txt ee)
21604 (if org-agenda-todo-list-sublevels
21605 (goto-char (match-end 1))
21606 (org-end-of-subtree 'invisible))))
21607 (nreverse ee)))
21609 (defconst org-agenda-no-heading-message
21610 "No heading for this item in buffer or region.")
21612 (defun org-agenda-get-timestamps ()
21613 "Return the date stamp information for agenda display."
21614 (let* ((props (list 'face nil
21615 'org-not-done-regexp org-not-done-regexp
21616 'org-todo-regexp org-todo-regexp
21617 'mouse-face 'highlight
21618 'keymap org-agenda-keymap
21619 'help-echo
21620 (format "mouse-2 or RET jump to org file %s"
21621 (abbreviate-file-name buffer-file-name))))
21622 (d1 (calendar-absolute-from-gregorian date))
21623 (remove-re
21624 (concat
21625 (regexp-quote
21626 (format-time-string
21627 "<%Y-%m-%d"
21628 (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
21629 ".*?>"))
21630 (regexp
21631 (concat
21632 (regexp-quote
21633 (substring
21634 (format-time-string
21635 (car org-time-stamp-formats)
21636 (apply 'encode-time ; DATE bound by calendar
21637 (list 0 0 0 (nth 1 date) (car date) (nth 2 date))))
21638 0 11))
21639 "\\|\\(<[0-9]+-[0-9]+-[0-9]+[^>\n]+?\\+[0-9]+[dwmy]>\\)"
21640 "\\|\\(<%%\\(([^>\n]+)\\)>\\)"))
21641 marker hdmarker deadlinep scheduledp donep tmp priority category
21642 ee txt timestr tags b0 b3 e3 head)
21643 (goto-char (point-min))
21644 (while (re-search-forward regexp nil t)
21645 (setq b0 (match-beginning 0)
21646 b3 (match-beginning 3) e3 (match-end 3))
21647 (catch :skip
21648 (and (org-at-date-range-p) (throw :skip nil))
21649 (org-agenda-skip)
21650 (if (and (match-end 1)
21651 (not (= d1 (org-time-string-to-absolute (match-string 1) d1))))
21652 (throw :skip nil))
21653 (if (and e3
21654 (not (org-diary-sexp-entry (buffer-substring b3 e3) "" date)))
21655 (throw :skip nil))
21656 (setq marker (org-agenda-new-marker b0)
21657 category (org-get-category b0)
21658 tmp (buffer-substring (max (point-min)
21659 (- b0 org-ds-keyword-length))
21661 timestr (if b3 "" (buffer-substring b0 (point-at-eol)))
21662 deadlinep (string-match org-deadline-regexp tmp)
21663 scheduledp (string-match org-scheduled-regexp tmp)
21664 donep (org-entry-is-done-p))
21665 (if (or scheduledp deadlinep) (throw :skip t))
21666 (if (string-match ">" timestr)
21667 ;; substring should only run to end of time stamp
21668 (setq timestr (substring timestr 0 (match-end 0))))
21669 (save-excursion
21670 (if (re-search-backward "^\\*+ " nil t)
21671 (progn
21672 (goto-char (match-beginning 0))
21673 (setq hdmarker (org-agenda-new-marker)
21674 tags (org-get-tags-at))
21675 (looking-at "\\*+[ \t]+\\([^\r\n]+\\)")
21676 (setq head (match-string 1))
21677 (and org-agenda-skip-timestamp-if-done donep (throw :skip t))
21678 (setq txt (org-format-agenda-item
21679 nil head category tags timestr nil
21680 remove-re)))
21681 (setq txt org-agenda-no-heading-message))
21682 (setq priority (org-get-priority txt))
21683 (org-add-props txt props
21684 'org-marker marker 'org-hd-marker hdmarker)
21685 (org-add-props txt nil 'priority priority
21686 'org-category category 'date date
21687 'type "timestamp")
21688 (push txt ee))
21689 (outline-next-heading)))
21690 (nreverse ee)))
21692 (defun org-agenda-get-sexps ()
21693 "Return the sexp information for agenda display."
21694 (require 'diary-lib)
21695 (let* ((props (list 'face nil
21696 'mouse-face 'highlight
21697 'keymap org-agenda-keymap
21698 'help-echo
21699 (format "mouse-2 or RET jump to org file %s"
21700 (abbreviate-file-name buffer-file-name))))
21701 (regexp "^&?%%(")
21702 marker category ee txt tags entry result beg b sexp sexp-entry)
21703 (goto-char (point-min))
21704 (while (re-search-forward regexp nil t)
21705 (catch :skip
21706 (org-agenda-skip)
21707 (setq beg (match-beginning 0))
21708 (goto-char (1- (match-end 0)))
21709 (setq b (point))
21710 (forward-sexp 1)
21711 (setq sexp (buffer-substring b (point)))
21712 (setq sexp-entry (if (looking-at "[ \t]*\\(\\S-.*\\)")
21713 (org-trim (match-string 1))
21714 ""))
21715 (setq result (org-diary-sexp-entry sexp sexp-entry date))
21716 (when result
21717 (setq marker (org-agenda-new-marker beg)
21718 category (org-get-category beg))
21720 (if (string-match "\\S-" result)
21721 (setq txt result)
21722 (setq txt "SEXP entry returned empty string"))
21724 (setq txt (org-format-agenda-item
21725 "" txt category tags 'time))
21726 (org-add-props txt props 'org-marker marker)
21727 (org-add-props txt nil
21728 'org-category category 'date date
21729 'type "sexp")
21730 (push txt ee))))
21731 (nreverse ee)))
21733 (defun org-agenda-get-closed ()
21734 "Return the logged TODO entries for agenda display."
21735 (let* ((props (list 'mouse-face 'highlight
21736 'org-not-done-regexp org-not-done-regexp
21737 'org-todo-regexp org-todo-regexp
21738 'keymap org-agenda-keymap
21739 'help-echo
21740 (format "mouse-2 or RET jump to org file %s"
21741 (abbreviate-file-name buffer-file-name))))
21742 (regexp (concat
21743 "\\<\\(" org-closed-string "\\|" org-clock-string "\\) *\\["
21744 (regexp-quote
21745 (substring
21746 (format-time-string
21747 (car org-time-stamp-formats)
21748 (apply 'encode-time ; DATE bound by calendar
21749 (list 0 0 0 (nth 1 date) (car date) (nth 2 date))))
21750 1 11))))
21751 marker hdmarker priority category tags closedp
21752 ee txt timestr)
21753 (goto-char (point-min))
21754 (while (re-search-forward regexp nil t)
21755 (catch :skip
21756 (org-agenda-skip)
21757 (setq marker (org-agenda-new-marker (match-beginning 0))
21758 closedp (equal (match-string 1) org-closed-string)
21759 category (org-get-category (match-beginning 0))
21760 timestr (buffer-substring (match-beginning 0) (point-at-eol))
21761 ;; donep (org-entry-is-done-p)
21763 (if (string-match "\\]" timestr)
21764 ;; substring should only run to end of time stamp
21765 (setq timestr (substring timestr 0 (match-end 0))))
21766 (save-excursion
21767 (if (re-search-backward "^\\*+ " nil t)
21768 (progn
21769 (goto-char (match-beginning 0))
21770 (setq hdmarker (org-agenda-new-marker)
21771 tags (org-get-tags-at))
21772 (looking-at "\\*+[ \t]+\\([^\r\n]+\\)")
21773 (setq txt (org-format-agenda-item
21774 (if closedp "Closed: " "Clocked: ")
21775 (match-string 1) category tags timestr)))
21776 (setq txt org-agenda-no-heading-message))
21777 (setq priority 100000)
21778 (org-add-props txt props
21779 'org-marker marker 'org-hd-marker hdmarker 'face 'org-done
21780 'priority priority 'org-category category
21781 'type "closed" 'date date
21782 'undone-face 'org-warning 'done-face 'org-done)
21783 (push txt ee))
21784 (goto-char (point-at-eol))))
21785 (nreverse ee)))
21787 (defun org-agenda-get-deadlines ()
21788 "Return the deadline information for agenda display."
21789 (let* ((props (list 'mouse-face 'highlight
21790 'org-not-done-regexp org-not-done-regexp
21791 'org-todo-regexp org-todo-regexp
21792 'keymap org-agenda-keymap
21793 'help-echo
21794 (format "mouse-2 or RET jump to org file %s"
21795 (abbreviate-file-name buffer-file-name))))
21796 (regexp org-deadline-time-regexp)
21797 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
21798 (d1 (calendar-absolute-from-gregorian date)) ; DATE bound by calendar
21799 d2 diff dfrac wdays pos pos1 category tags
21800 ee txt head face s upcomingp donep timestr)
21801 (goto-char (point-min))
21802 (while (re-search-forward regexp nil t)
21803 (catch :skip
21804 (org-agenda-skip)
21805 (setq s (match-string 1)
21806 pos (1- (match-beginning 1))
21807 d2 (org-time-string-to-absolute (match-string 1) d1 'past)
21808 diff (- d2 d1)
21809 wdays (org-get-wdays s)
21810 dfrac (/ (* 1.0 (- wdays diff)) (max wdays 1))
21811 upcomingp (and todayp (> diff 0)))
21812 ;; When to show a deadline in the calendar:
21813 ;; If the expiration is within wdays warning time.
21814 ;; Past-due deadlines are only shown on the current date
21815 (if (or (and (<= diff wdays)
21816 (and todayp (not org-agenda-only-exact-dates)))
21817 (= diff 0))
21818 (save-excursion
21819 (setq category (org-get-category))
21820 (if (re-search-backward "^\\*+[ \t]+" nil t)
21821 (progn
21822 (goto-char (match-end 0))
21823 (setq pos1 (match-beginning 0))
21824 (setq tags (org-get-tags-at pos1))
21825 (setq head (buffer-substring-no-properties
21826 (point)
21827 (progn (skip-chars-forward "^\r\n")
21828 (point))))
21829 (setq donep (string-match org-looking-at-done-regexp head))
21830 (if (string-match " \\([012]?[0-9]:[0-9][0-9]\\)" s)
21831 (setq timestr
21832 (concat (substring s (match-beginning 1)) " "))
21833 (setq timestr 'time))
21834 (if (and donep
21835 (or org-agenda-skip-deadline-if-done
21836 (not (= diff 0))))
21837 (setq txt nil)
21838 (setq txt (org-format-agenda-item
21839 (if (= diff 0)
21840 (car org-agenda-deadline-leaders)
21841 (format (nth 1 org-agenda-deadline-leaders)
21842 diff))
21843 head category tags timestr))))
21844 (setq txt org-agenda-no-heading-message))
21845 (when txt
21846 (setq face (org-agenda-deadline-face dfrac))
21847 (org-add-props txt props
21848 'org-marker (org-agenda-new-marker pos)
21849 'org-hd-marker (org-agenda-new-marker pos1)
21850 'priority (+ (- diff)
21851 (org-get-priority txt))
21852 'org-category category
21853 'type (if upcomingp "upcoming-deadline" "deadline")
21854 'date (if upcomingp date d2)
21855 'face (if donep 'org-done face)
21856 'undone-face face 'done-face 'org-done)
21857 (push txt ee))))))
21858 (nreverse ee)))
21860 (defun org-agenda-deadline-face (fraction)
21861 "Return the face to displaying a deadline item.
21862 FRACTION is what fraction of the head-warning time has passed."
21863 (let ((faces org-agenda-deadline-faces) f)
21864 (catch 'exit
21865 (while (setq f (pop faces))
21866 (if (>= fraction (car f)) (throw 'exit (cdr f)))))))
21868 (defun org-agenda-get-scheduled ()
21869 "Return the scheduled information for agenda display."
21870 (let* ((props (list 'org-not-done-regexp org-not-done-regexp
21871 'org-todo-regexp org-todo-regexp
21872 'done-face 'org-done
21873 'mouse-face 'highlight
21874 'keymap org-agenda-keymap
21875 'help-echo
21876 (format "mouse-2 or RET jump to org file %s"
21877 (abbreviate-file-name buffer-file-name))))
21878 (regexp org-scheduled-time-regexp)
21879 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
21880 (d1 (calendar-absolute-from-gregorian date)) ; DATE bound by calendar
21881 d2 diff pos pos1 category tags
21882 ee txt head pastschedp donep face timestr s)
21883 (goto-char (point-min))
21884 (while (re-search-forward regexp nil t)
21885 (catch :skip
21886 (org-agenda-skip)
21887 (setq s (match-string 1)
21888 pos (1- (match-beginning 1))
21889 d2 (org-time-string-to-absolute (match-string 1) d1 'past)
21890 ;;; is this right?
21891 ;;; do we need to do this for deadleine too????
21892 ;;; d2 (org-time-string-to-absolute (match-string 1) (if todayp nil d1))
21893 diff (- d2 d1))
21894 (setq pastschedp (and todayp (< diff 0)))
21895 ;; When to show a scheduled item in the calendar:
21896 ;; If it is on or past the date.
21897 (if (or (and (< diff 0)
21898 (and todayp (not org-agenda-only-exact-dates)))
21899 (= diff 0))
21900 (save-excursion
21901 (setq category (org-get-category))
21902 (if (re-search-backward "^\\*+[ \t]+" nil t)
21903 (progn
21904 (goto-char (match-end 0))
21905 (setq pos1 (match-beginning 0))
21906 (setq tags (org-get-tags-at))
21907 (setq head (buffer-substring-no-properties
21908 (point)
21909 (progn (skip-chars-forward "^\r\n") (point))))
21910 (setq donep (string-match org-looking-at-done-regexp head))
21911 (if (string-match " \\([012]?[0-9]:[0-9][0-9]\\)" s)
21912 (setq timestr
21913 (concat (substring s (match-beginning 1)) " "))
21914 (setq timestr 'time))
21915 (if (and donep
21916 (or org-agenda-skip-scheduled-if-done
21917 (not (= diff 0))))
21918 (setq txt nil)
21919 (setq txt (org-format-agenda-item
21920 (if (= diff 0)
21921 (car org-agenda-scheduled-leaders)
21922 (format (nth 1 org-agenda-scheduled-leaders)
21923 (- 1 diff)))
21924 head category tags timestr))))
21925 (setq txt org-agenda-no-heading-message))
21926 (when txt
21927 (setq face (if pastschedp
21928 'org-scheduled-previously
21929 'org-scheduled-today))
21930 (org-add-props txt props
21931 'undone-face face
21932 'face (if donep 'org-done face)
21933 'org-marker (org-agenda-new-marker pos)
21934 'org-hd-marker (org-agenda-new-marker pos1)
21935 'type (if pastschedp "past-scheduled" "scheduled")
21936 'date (if pastschedp d2 date)
21937 'priority (+ 94 (- 5 diff) (org-get-priority txt))
21938 'org-category category)
21939 (push txt ee))))))
21940 (nreverse ee)))
21942 (defun org-agenda-get-blocks ()
21943 "Return the date-range information for agenda display."
21944 (let* ((props (list 'face nil
21945 'org-not-done-regexp org-not-done-regexp
21946 'org-todo-regexp org-todo-regexp
21947 'mouse-face 'highlight
21948 'keymap org-agenda-keymap
21949 'help-echo
21950 (format "mouse-2 or RET jump to org file %s"
21951 (abbreviate-file-name buffer-file-name))))
21952 (regexp org-tr-regexp)
21953 (d0 (calendar-absolute-from-gregorian date))
21954 marker hdmarker ee txt d1 d2 s1 s2 timestr category tags pos
21955 donep head)
21956 (goto-char (point-min))
21957 (while (re-search-forward regexp nil t)
21958 (catch :skip
21959 (org-agenda-skip)
21960 (setq pos (point))
21961 (setq timestr (match-string 0)
21962 s1 (match-string 1)
21963 s2 (match-string 2)
21964 d1 (time-to-days (org-time-string-to-time s1))
21965 d2 (time-to-days (org-time-string-to-time s2)))
21966 (if (and (> (- d0 d1) -1) (> (- d2 d0) -1))
21967 ;; Only allow days between the limits, because the normal
21968 ;; date stamps will catch the limits.
21969 (save-excursion
21970 (setq marker (org-agenda-new-marker (point)))
21971 (setq category (org-get-category))
21972 (if (re-search-backward "^\\*+ " nil t)
21973 (progn
21974 (goto-char (match-beginning 0))
21975 (setq hdmarker (org-agenda-new-marker (point)))
21976 (setq tags (org-get-tags-at))
21977 (looking-at "\\*+[ \t]+\\([^\r\n]+\\)")
21978 (setq head (match-string 1))
21979 (and org-agenda-skip-timestamp-if-done
21980 (org-entry-is-done-p)
21981 (throw :skip t))
21982 (setq txt (org-format-agenda-item
21983 (format (if (= d1 d2) "" "(%d/%d): ")
21984 (1+ (- d0 d1)) (1+ (- d2 d1)))
21985 head category tags
21986 (if (= d0 d1) timestr))))
21987 (setq txt org-agenda-no-heading-message))
21988 (org-add-props txt props
21989 'org-marker marker 'org-hd-marker hdmarker
21990 'type "block" 'date date
21991 'priority (org-get-priority txt) 'org-category category)
21992 (push txt ee)))
21993 (goto-char pos)))
21994 ;; Sort the entries by expiration date.
21995 (nreverse ee)))
21997 ;;; Agenda presentation and sorting
21999 (defconst org-plain-time-of-day-regexp
22000 (concat
22001 "\\(\\<[012]?[0-9]"
22002 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
22003 "\\(--?"
22004 "\\(\\<[012]?[0-9]"
22005 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
22006 "\\)?")
22007 "Regular expression to match a plain time or time range.
22008 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
22009 groups carry important information:
22010 0 the full match
22011 1 the first time, range or not
22012 8 the second time, if it is a range.")
22014 (defconst org-plain-time-extension-regexp
22015 (concat
22016 "\\(\\<[012]?[0-9]"
22017 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
22018 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
22019 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
22020 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
22021 groups carry important information:
22022 0 the full match
22023 7 hours of duration
22024 9 minutes of duration")
22026 (defconst org-stamp-time-of-day-regexp
22027 (concat
22028 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
22029 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
22030 "\\(--?"
22031 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
22032 "Regular expression to match a timestamp time or time range.
22033 After a match, the following groups carry important information:
22034 0 the full match
22035 1 date plus weekday, for backreferencing to make sure both times on same day
22036 2 the first time, range or not
22037 4 the second time, if it is a range.")
22039 (defvar org-prefix-has-time nil
22040 "A flag, set by `org-compile-prefix-format'.
22041 The flag is set if the currently compiled format contains a `%t'.")
22042 (defvar org-prefix-has-tag nil
22043 "A flag, set by `org-compile-prefix-format'.
22044 The flag is set if the currently compiled format contains a `%T'.")
22046 (defun org-format-agenda-item (extra txt &optional category tags dotime
22047 noprefix remove-re)
22048 "Format TXT to be inserted into the agenda buffer.
22049 In particular, it adds the prefix and corresponding text properties. EXTRA
22050 must be a string and replaces the `%s' specifier in the prefix format.
22051 CATEGORY (string, symbol or nil) may be used to overrule the default
22052 category taken from local variable or file name. It will replace the `%c'
22053 specifier in the format. DOTIME, when non-nil, indicates that a
22054 time-of-day should be extracted from TXT for sorting of this entry, and for
22055 the `%t' specifier in the format. When DOTIME is a string, this string is
22056 searched for a time before TXT is. NOPREFIX is a flag and indicates that
22057 only the correctly processes TXT should be returned - this is used by
22058 `org-agenda-change-all-lines'. TAGS can be the tags of the headline.
22059 Any match of REMOVE-RE will be removed from TXT."
22060 (save-match-data
22061 ;; Diary entries sometimes have extra whitespace at the beginning
22062 (if (string-match "^ +" txt) (setq txt (replace-match "" nil nil txt)))
22063 (let* ((category (or category
22064 org-category
22065 (if buffer-file-name
22066 (file-name-sans-extension
22067 (file-name-nondirectory buffer-file-name))
22068 "")))
22069 (tag (if tags (nth (1- (length tags)) tags) ""))
22070 time ; time and tag are needed for the eval of the prefix format
22071 (ts (if dotime (concat (if (stringp dotime) dotime "") txt)))
22072 (time-of-day (and dotime (org-get-time-of-day ts)))
22073 stamp plain s0 s1 s2 rtn srp)
22074 (when (and dotime time-of-day org-prefix-has-time)
22075 ;; Extract starting and ending time and move them to prefix
22076 (when (or (setq stamp (string-match org-stamp-time-of-day-regexp ts))
22077 (setq plain (string-match org-plain-time-of-day-regexp ts)))
22078 (setq s0 (match-string 0 ts)
22079 srp (and stamp (match-end 3))
22080 s1 (match-string (if plain 1 2) ts)
22081 s2 (match-string (if plain 8 (if srp 4 6)) ts))
22083 ;; If the times are in TXT (not in DOTIMES), and the prefix will list
22084 ;; them, we might want to remove them there to avoid duplication.
22085 ;; The user can turn this off with a variable.
22086 (if (and org-agenda-remove-times-when-in-prefix (or stamp plain)
22087 (string-match (concat (regexp-quote s0) " *") txt)
22088 (not (equal ?\] (string-to-char (substring txt (match-end 0)))))
22089 (if (eq org-agenda-remove-times-when-in-prefix 'beg)
22090 (= (match-beginning 0) 0)
22092 (setq txt (replace-match "" nil nil txt))))
22093 ;; Normalize the time(s) to 24 hour
22094 (if s1 (setq s1 (org-get-time-of-day s1 'string t)))
22095 (if s2 (setq s2 (org-get-time-of-day s2 'string t))))
22097 (when (and s1 (not s2) org-agenda-default-appointment-duration
22098 (string-match "\\([0-9]+\\):\\([0-9]+\\)" s1))
22099 (let ((m (+ (string-to-number (match-string 2 s1))
22100 (* 60 (string-to-number (match-string 1 s1)))
22101 org-agenda-default-appointment-duration))
22103 (setq h (/ m 60) m (- m (* h 60)))
22104 (setq s2 (format "%02d:%02d" h m))))
22106 (when (string-match (org-re "\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$")
22107 txt)
22108 ;; Tags are in the string
22109 (if (or (eq org-agenda-remove-tags t)
22110 (and org-agenda-remove-tags
22111 org-prefix-has-tag))
22112 (setq txt (replace-match "" t t txt))
22113 (setq txt (replace-match
22114 (concat (make-string (max (- 50 (length txt)) 1) ?\ )
22115 (match-string 2 txt))
22116 t t txt))))
22118 (when remove-re
22119 (while (string-match remove-re txt)
22120 (setq txt (replace-match "" t t txt))))
22122 ;; Create the final string
22123 (if noprefix
22124 (setq rtn txt)
22125 ;; Prepare the variables needed in the eval of the compiled format
22126 (setq time (cond (s2 (concat s1 "-" s2))
22127 (s1 (concat s1 "......"))
22128 (t ""))
22129 extra (or extra "")
22130 category (if (symbolp category) (symbol-name category) category))
22131 ;; Evaluate the compiled format
22132 (setq rtn (concat (eval org-prefix-format-compiled) txt)))
22134 ;; And finally add the text properties
22135 (org-add-props rtn nil
22136 'org-category (downcase category) 'tags tags
22137 'org-highest-priority org-highest-priority
22138 'org-lowest-priority org-lowest-priority
22139 'prefix-length (- (length rtn) (length txt))
22140 'time-of-day time-of-day
22141 'txt txt
22142 'time time
22143 'extra extra
22144 'dotime dotime))))
22146 (defvar org-agenda-sorting-strategy) ;; because the def is in a let form
22147 (defvar org-agenda-sorting-strategy-selected nil)
22149 (defun org-agenda-add-time-grid-maybe (list ndays todayp)
22150 (catch 'exit
22151 (cond ((not org-agenda-use-time-grid) (throw 'exit list))
22152 ((and todayp (member 'today (car org-agenda-time-grid))))
22153 ((and (= ndays 1) (member 'daily (car org-agenda-time-grid))))
22154 ((member 'weekly (car org-agenda-time-grid)))
22155 (t (throw 'exit list)))
22156 (let* ((have (delq nil (mapcar
22157 (lambda (x) (get-text-property 1 'time-of-day x))
22158 list)))
22159 (string (nth 1 org-agenda-time-grid))
22160 (gridtimes (nth 2 org-agenda-time-grid))
22161 (req (car org-agenda-time-grid))
22162 (remove (member 'remove-match req))
22163 new time)
22164 (if (and (member 'require-timed req) (not have))
22165 ;; don't show empty grid
22166 (throw 'exit list))
22167 (while (setq time (pop gridtimes))
22168 (unless (and remove (member time have))
22169 (setq time (int-to-string time))
22170 (push (org-format-agenda-item
22171 nil string "" nil
22172 (concat (substring time 0 -2) ":" (substring time -2)))
22173 new)
22174 (put-text-property
22175 1 (length (car new)) 'face 'org-time-grid (car new))))
22176 (if (member 'time-up org-agenda-sorting-strategy-selected)
22177 (append new list)
22178 (append list new)))))
22180 (defun org-compile-prefix-format (key)
22181 "Compile the prefix format into a Lisp form that can be evaluated.
22182 The resulting form is returned and stored in the variable
22183 `org-prefix-format-compiled'."
22184 (setq org-prefix-has-time nil org-prefix-has-tag nil)
22185 (let ((s (cond
22186 ((stringp org-agenda-prefix-format)
22187 org-agenda-prefix-format)
22188 ((assq key org-agenda-prefix-format)
22189 (cdr (assq key org-agenda-prefix-format)))
22190 (t " %-12:c%?-12t% s")))
22191 (start 0)
22192 varform vars var e c f opt)
22193 (while (string-match "%\\(\\?\\)?\\([-+]?[0-9.]*\\)\\([ .;,:!?=|/<>]?\\)\\([cts]\\)"
22194 s start)
22195 (setq var (cdr (assoc (match-string 4 s)
22196 '(("c" . category) ("t" . time) ("s" . extra)
22197 ("T" . tag))))
22198 c (or (match-string 3 s) "")
22199 opt (match-beginning 1)
22200 start (1+ (match-beginning 0)))
22201 (if (equal var 'time) (setq org-prefix-has-time t))
22202 (if (equal var 'tag) (setq org-prefix-has-tag t))
22203 (setq f (concat "%" (match-string 2 s) "s"))
22204 (if opt
22205 (setq varform
22206 `(if (equal "" ,var)
22208 (format ,f (if (equal "" ,var) "" (concat ,var ,c)))))
22209 (setq varform `(format ,f (if (equal ,var "") "" (concat ,var ,c)))))
22210 (setq s (replace-match "%s" t nil s))
22211 (push varform vars))
22212 (setq vars (nreverse vars))
22213 (setq org-prefix-format-compiled `(format ,s ,@vars))))
22215 (defun org-set-sorting-strategy (key)
22216 (if (symbolp (car org-agenda-sorting-strategy))
22217 ;; the old format
22218 (setq org-agenda-sorting-strategy-selected org-agenda-sorting-strategy)
22219 (setq org-agenda-sorting-strategy-selected
22220 (or (cdr (assq key org-agenda-sorting-strategy))
22221 (cdr (assq 'agenda org-agenda-sorting-strategy))
22222 '(time-up category-keep priority-down)))))
22224 (defun org-get-time-of-day (s &optional string mod24)
22225 "Check string S for a time of day.
22226 If found, return it as a military time number between 0 and 2400.
22227 If not found, return nil.
22228 The optional STRING argument forces conversion into a 5 character wide string
22229 HH:MM."
22230 (save-match-data
22231 (when
22232 (or (string-match "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)\\([AaPp][Mm]\\)?\\> *" s)
22233 (string-match "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\([AaPp][Mm]\\)\\> *" s))
22234 (let* ((h (string-to-number (match-string 1 s)))
22235 (m (if (match-end 3) (string-to-number (match-string 3 s)) 0))
22236 (ampm (if (match-end 4) (downcase (match-string 4 s))))
22237 (am-p (equal ampm "am"))
22238 (h1 (cond ((not ampm) h)
22239 ((= h 12) (if am-p 0 12))
22240 (t (+ h (if am-p 0 12)))))
22241 (h2 (if (and string mod24 (not (and (= m 0) (= h1 24))))
22242 (mod h1 24) h1))
22243 (t0 (+ (* 100 h2) m))
22244 (t1 (concat (if (>= h1 24) "+" " ")
22245 (if (< t0 100) "0" "")
22246 (if (< t0 10) "0" "")
22247 (int-to-string t0))))
22248 (if string (concat (substring t1 -4 -2) ":" (substring t1 -2)) t0)))))
22250 (defun org-finalize-agenda-entries (list &optional nosort)
22251 "Sort and concatenate the agenda items."
22252 (setq list (mapcar 'org-agenda-highlight-todo list))
22253 (if nosort
22254 list
22255 (mapconcat 'identity (sort list 'org-entries-lessp) "\n")))
22257 (defun org-agenda-highlight-todo (x)
22258 (let (re pl)
22259 (if (eq x 'line)
22260 (save-excursion
22261 (beginning-of-line 1)
22262 (setq re (get-text-property (point) 'org-todo-regexp))
22263 (goto-char (+ (point) (or (get-text-property (point) 'prefix-length) 0)))
22264 (when (looking-at (concat "[ \t]*\\.*" re " +"))
22265 (add-text-properties (match-beginning 0) (match-end 0)
22266 (list 'face (org-get-todo-face 0)))
22267 (let ((s (buffer-substring (match-beginning 1) (match-end 1))))
22268 (delete-region (match-beginning 1) (1- (match-end 0)))
22269 (goto-char (match-beginning 1))
22270 (insert (format org-agenda-todo-keyword-format s)))))
22271 (setq re (concat (get-text-property 0 'org-todo-regexp x))
22272 pl (get-text-property 0 'prefix-length x))
22273 (when (and re
22274 (equal (string-match (concat "\\(\\.*\\)" re "\\( +\\)")
22275 x (or pl 0)) pl))
22276 (add-text-properties
22277 (or (match-end 1) (match-end 0)) (match-end 0)
22278 (list 'face (org-get-todo-face (match-string 2 x)))
22280 (setq x (concat (substring x 0 (match-end 1))
22281 (format org-agenda-todo-keyword-format
22282 (match-string 2 x))
22284 (substring x (match-end 3)))))
22285 x)))
22287 (defsubst org-cmp-priority (a b)
22288 "Compare the priorities of string A and B."
22289 (let ((pa (or (get-text-property 1 'priority a) 0))
22290 (pb (or (get-text-property 1 'priority b) 0)))
22291 (cond ((> pa pb) +1)
22292 ((< pa pb) -1)
22293 (t nil))))
22295 (defsubst org-cmp-category (a b)
22296 "Compare the string values of categories of strings A and B."
22297 (let ((ca (or (get-text-property 1 'org-category a) ""))
22298 (cb (or (get-text-property 1 'org-category b) "")))
22299 (cond ((string-lessp ca cb) -1)
22300 ((string-lessp cb ca) +1)
22301 (t nil))))
22303 (defsubst org-cmp-tag (a b)
22304 "Compare the string values of categories of strings A and B."
22305 (let ((ta (car (last (get-text-property 1 'tags a))))
22306 (tb (car (last (get-text-property 1 'tags b)))))
22307 (cond ((not ta) +1)
22308 ((not tb) -1)
22309 ((string-lessp ta tb) -1)
22310 ((string-lessp tb ta) +1)
22311 (t nil))))
22313 (defsubst org-cmp-time (a b)
22314 "Compare the time-of-day values of strings A and B."
22315 (let* ((def (if org-sort-agenda-notime-is-late 9901 -1))
22316 (ta (or (get-text-property 1 'time-of-day a) def))
22317 (tb (or (get-text-property 1 'time-of-day b) def)))
22318 (cond ((< ta tb) -1)
22319 ((< tb ta) +1)
22320 (t nil))))
22322 (defun org-entries-lessp (a b)
22323 "Predicate for sorting agenda entries."
22324 ;; The following variables will be used when the form is evaluated.
22325 ;; So even though the compiler complains, keep them.
22326 (let* ((time-up (org-cmp-time a b))
22327 (time-down (if time-up (- time-up) nil))
22328 (priority-up (org-cmp-priority a b))
22329 (priority-down (if priority-up (- priority-up) nil))
22330 (category-up (org-cmp-category a b))
22331 (category-down (if category-up (- category-up) nil))
22332 (category-keep (if category-up +1 nil))
22333 (tag-up (org-cmp-tag a b))
22334 (tag-down (if tag-up (- tag-up) nil)))
22335 (cdr (assoc
22336 (eval (cons 'or org-agenda-sorting-strategy-selected))
22337 '((-1 . t) (1 . nil) (nil . nil))))))
22339 ;;; Agenda restriction lock
22341 (defvar org-agenda-restriction-lock-overlay (org-make-overlay 1 1)
22342 "Overlay to mark the headline to which arenda commands are restricted.")
22343 (org-overlay-put org-agenda-restriction-lock-overlay
22344 'face 'org-agenda-restriction-lock)
22345 (org-overlay-put org-agenda-restriction-lock-overlay
22346 'help-echo "Agendas are currently limited to this subtree.")
22347 (org-detach-overlay org-agenda-restriction-lock-overlay)
22348 (defvar org-speedbar-restriction-lock-overlay (org-make-overlay 1 1)
22349 "Overlay marking the agenda restriction line in speedbar.")
22350 (org-overlay-put org-speedbar-restriction-lock-overlay
22351 'face 'org-agenda-restriction-lock)
22352 (org-overlay-put org-speedbar-restriction-lock-overlay
22353 'help-echo "Agendas are currently limited to this item.")
22354 (org-detach-overlay org-speedbar-restriction-lock-overlay)
22356 (defun org-agenda-set-restriction-lock (&optional type)
22357 "Set restriction lock for agenda, to current subtree or file.
22358 Restriction will be the file if TYPE is `file', or if type is the
22359 universal prefix '(4), or if the cursor is before the first headline
22360 in the file. Otherwise, restriction will be to the current subtree."
22361 (interactive "P")
22362 (and (equal type '(4)) (setq type 'file))
22363 (setq type (cond
22364 (type type)
22365 ((org-at-heading-p) 'subtree)
22366 ((condition-case nil (org-back-to-heading t) (error nil))
22367 'subtree)
22368 (t 'file)))
22369 (if (eq type 'subtree)
22370 (progn
22371 (setq org-agenda-restrict t)
22372 (setq org-agenda-overriding-restriction 'subtree)
22373 (put 'org-agenda-files 'org-restrict
22374 (list (buffer-file-name (buffer-base-buffer))))
22375 (org-back-to-heading t)
22376 (org-move-overlay org-agenda-restriction-lock-overlay (point) (point-at-eol))
22377 (move-marker org-agenda-restrict-begin (point))
22378 (move-marker org-agenda-restrict-end
22379 (save-excursion (org-end-of-subtree t)))
22380 (message "Locking agenda restriction to subtree"))
22381 (put 'org-agenda-files 'org-restrict
22382 (list (buffer-file-name (buffer-base-buffer))))
22383 (setq org-agenda-restrict nil)
22384 (setq org-agenda-overriding-restriction 'file)
22385 (move-marker org-agenda-restrict-begin nil)
22386 (move-marker org-agenda-restrict-end nil)
22387 (message "Locking agenda restriction to file"))
22388 (setq current-prefix-arg nil)
22389 (org-agenda-maybe-redo))
22391 (defun org-agenda-remove-restriction-lock (&optional noupdate)
22392 "Remove the agenda restriction lock."
22393 (interactive "P")
22394 (org-detach-overlay org-agenda-restriction-lock-overlay)
22395 (org-detach-overlay org-speedbar-restriction-lock-overlay)
22396 (setq org-agenda-overriding-restriction nil)
22397 (setq org-agenda-restrict nil)
22398 (put 'org-agenda-files 'org-restrict nil)
22399 (move-marker org-agenda-restrict-begin nil)
22400 (move-marker org-agenda-restrict-end nil)
22401 (setq current-prefix-arg nil)
22402 (message "Agenda restriction lock removed")
22403 (or noupdate (org-agenda-maybe-redo)))
22405 (defun org-agenda-maybe-redo ()
22406 "If there is any window showing the agenda view, update it."
22407 (let ((w (get-buffer-window org-agenda-buffer-name t))
22408 (w0 (selected-window)))
22409 (when w
22410 (select-window w)
22411 (org-agenda-redo)
22412 (select-window w0)
22413 (if org-agenda-overriding-restriction
22414 (message "Agenda view shifted to new %s restriction"
22415 org-agenda-overriding-restriction)
22416 (message "Agenda restriction lock removed")))))
22418 ;;; Agenda commands
22420 (defun org-agenda-check-type (error &rest types)
22421 "Check if agenda buffer is of allowed type.
22422 If ERROR is non-nil, throw an error, otherwise just return nil."
22423 (if (memq org-agenda-type types)
22425 (if error
22426 (error "Not allowed in %s-type agenda buffers" org-agenda-type)
22427 nil)))
22429 (defun org-agenda-quit ()
22430 "Exit agenda by removing the window or the buffer."
22431 (interactive)
22432 (let ((buf (current-buffer)))
22433 (if (not (one-window-p)) (delete-window))
22434 (kill-buffer buf)
22435 (org-agenda-reset-markers)
22436 (org-columns-remove-overlays))
22437 ;; Maybe restore the pre-agenda window configuration.
22438 (and org-agenda-restore-windows-after-quit
22439 (not (eq org-agenda-window-setup 'other-frame))
22440 org-pre-agenda-window-conf
22441 (set-window-configuration org-pre-agenda-window-conf)))
22443 (defun org-agenda-exit ()
22444 "Exit agenda by removing the window or the buffer.
22445 Also kill all Org-mode buffers which have been loaded by `org-agenda'.
22446 Org-mode buffers visited directly by the user will not be touched."
22447 (interactive)
22448 (org-release-buffers org-agenda-new-buffers)
22449 (setq org-agenda-new-buffers nil)
22450 (org-agenda-quit))
22452 (defun org-agenda-execute (arg)
22453 "Execute another agenda command, keeping same window.\\<global-map>
22454 So this is just a shortcut for `\\[org-agenda]', available in the agenda."
22455 (interactive "P")
22456 (let ((org-agenda-window-setup 'current-window))
22457 (org-agenda arg)))
22459 (defun org-save-all-org-buffers ()
22460 "Save all Org-mode buffers without user confirmation."
22461 (interactive)
22462 (message "Saving all Org-mode buffers...")
22463 (save-some-buffers t 'org-mode-p)
22464 (message "Saving all Org-mode buffers... done"))
22466 (defun org-agenda-redo ()
22467 "Rebuild Agenda.
22468 When this is the global TODO list, a prefix argument will be interpreted."
22469 (interactive)
22470 (let* ((org-agenda-keep-modes t)
22471 (line (org-current-line))
22472 (window-line (- line (org-current-line (window-start))))
22473 (lprops (get 'org-agenda-redo-command 'org-lprops)))
22474 (message "Rebuilding agenda buffer...")
22475 (org-let lprops '(eval org-agenda-redo-command))
22476 (setq org-agenda-undo-list nil
22477 org-agenda-pending-undo-list nil)
22478 (message "Rebuilding agenda buffer...done")
22479 (goto-line line)
22480 (recenter window-line)))
22482 (defun org-agenda-manipulate-query-add ()
22483 "Manipulate the query by adding a search term with positive selection.
22484 Positive selection means, the term must be matched for selection of an entry."
22485 (interactive)
22486 (org-agenda-manipulate-query ?\[))
22487 (defun org-agenda-manipulate-query-subtract ()
22488 "Manipulate the query by adding a search term with negative selection.
22489 Negative selection means, term must not be matched for selection of an entry."
22490 (interactive)
22491 (org-agenda-manipulate-query ?\]))
22492 (defun org-agenda-manipulate-query-add-re ()
22493 "Manipulate the query by adding a search regexp with positive selection.
22494 Positive selection means, the regexp must match for selection of an entry."
22495 (interactive)
22496 (org-agenda-manipulate-query ?\{))
22497 (defun org-agenda-manipulate-query-subtract-re ()
22498 "Manipulate the query by adding a search regexp with negative selection.
22499 Negative selection means, regexp must not match for selection of an entry."
22500 (interactive)
22501 (org-agenda-manipulate-query ?\}))
22502 (defun org-agenda-manipulate-query (char)
22503 (cond
22504 ((eq org-agenda-type 'search)
22505 (org-add-to-string
22506 'org-agenda-query-string
22507 (cdr (assoc char '((?\[ . " +") (?\] . " -")
22508 (?\{ . " +{}") (?\} . " -{}")))))
22509 (setq org-agenda-redo-command
22510 (list 'org-search-view
22511 (+ (length org-agenda-query-string)
22512 (if (member char '(?\{ ?\})) 0 1))
22513 org-agenda-query-string))
22514 (set-register org-agenda-query-register org-agenda-query-string)
22515 (org-agenda-redo))
22516 (t (error "Canot manipulate query for %s-type agenda buffers"
22517 org-agenda-type))))
22519 (defun org-add-to-string (var string)
22520 (set var (concat (symbol-value var) string)))
22522 (defun org-agenda-goto-date (date)
22523 "Jump to DATE in agenda."
22524 (interactive (list (org-read-date)))
22525 (org-agenda-list nil date))
22527 (defun org-agenda-goto-today ()
22528 "Go to today."
22529 (interactive)
22530 (org-agenda-check-type t 'timeline 'agenda)
22531 (let ((tdpos (text-property-any (point-min) (point-max) 'org-today t)))
22532 (cond
22533 (tdpos (goto-char tdpos))
22534 ((eq org-agenda-type 'agenda)
22535 (let* ((sd (time-to-days
22536 (time-subtract (current-time)
22537 (list 0 (* 3600 org-extend-today-until) 0))))
22538 (comp (org-agenda-compute-time-span sd org-agenda-span))
22539 (org-agenda-overriding-arguments org-agenda-last-arguments))
22540 (setf (nth 1 org-agenda-overriding-arguments) (car comp))
22541 (setf (nth 2 org-agenda-overriding-arguments) (cdr comp))
22542 (org-agenda-redo)
22543 (org-agenda-find-same-or-today-or-agenda)))
22544 (t (error "Cannot find today")))))
22546 (defun org-agenda-find-same-or-today-or-agenda (&optional cnt)
22547 (goto-char
22548 (or (and cnt (text-property-any (point-min) (point-max) 'org-day-cnt cnt))
22549 (text-property-any (point-min) (point-max) 'org-today t)
22550 (text-property-any (point-min) (point-max) 'org-agenda-type 'agenda)
22551 (point-min))))
22553 (defun org-agenda-later (arg)
22554 "Go forward in time by thee current span.
22555 With prefix ARG, go forward that many times the current span."
22556 (interactive "p")
22557 (org-agenda-check-type t 'agenda)
22558 (let* ((span org-agenda-span)
22559 (sd org-starting-day)
22560 (greg (calendar-gregorian-from-absolute sd))
22561 (cnt (get-text-property (point) 'org-day-cnt))
22562 greg2 nd)
22563 (cond
22564 ((eq span 'day)
22565 (setq sd (+ arg sd) nd 1))
22566 ((eq span 'week)
22567 (setq sd (+ (* 7 arg) sd) nd 7))
22568 ((eq span 'month)
22569 (setq greg2 (list (+ (car greg) arg) (nth 1 greg) (nth 2 greg))
22570 sd (calendar-absolute-from-gregorian greg2))
22571 (setcar greg2 (1+ (car greg2)))
22572 (setq nd (- (calendar-absolute-from-gregorian greg2) sd)))
22573 ((eq span 'year)
22574 (setq greg2 (list (car greg) (nth 1 greg) (+ arg (nth 2 greg)))
22575 sd (calendar-absolute-from-gregorian greg2))
22576 (setcar (nthcdr 2 greg2) (1+ (nth 2 greg2)))
22577 (setq nd (- (calendar-absolute-from-gregorian greg2) sd))))
22578 (let ((org-agenda-overriding-arguments
22579 (list (car org-agenda-last-arguments) sd nd t)))
22580 (org-agenda-redo)
22581 (org-agenda-find-same-or-today-or-agenda cnt))))
22583 (defun org-agenda-earlier (arg)
22584 "Go backward in time by the current span.
22585 With prefix ARG, go backward that many times the current span."
22586 (interactive "p")
22587 (org-agenda-later (- arg)))
22589 (defun org-agenda-day-view ()
22590 "Switch to daily view for agenda."
22591 (interactive)
22592 (setq org-agenda-ndays 1)
22593 (org-agenda-change-time-span 'day))
22594 (defun org-agenda-week-view ()
22595 "Switch to daily view for agenda."
22596 (interactive)
22597 (setq org-agenda-ndays 7)
22598 (org-agenda-change-time-span 'week))
22599 (defun org-agenda-month-view ()
22600 "Switch to daily view for agenda."
22601 (interactive)
22602 (org-agenda-change-time-span 'month))
22603 (defun org-agenda-year-view ()
22604 "Switch to daily view for agenda."
22605 (interactive)
22606 (if (y-or-n-p "Are you sure you want to compute the agenda for an entire year? ")
22607 (org-agenda-change-time-span 'year)
22608 (error "Abort")))
22610 (defun org-agenda-change-time-span (span)
22611 "Change the agenda view to SPAN.
22612 SPAN may be `day', `week', `month', `year'."
22613 (org-agenda-check-type t 'agenda)
22614 (if (equal org-agenda-span span)
22615 (error "Viewing span is already \"%s\"" span))
22616 (let* ((sd (or (get-text-property (point) 'day)
22617 org-starting-day))
22618 (computed (org-agenda-compute-time-span sd span))
22619 (org-agenda-overriding-arguments
22620 (list (car org-agenda-last-arguments)
22621 (car computed) (cdr computed) t)))
22622 (org-agenda-redo)
22623 (org-agenda-find-same-or-today-or-agenda))
22624 (org-agenda-set-mode-name)
22625 (message "Switched to %s view" span))
22627 (defun org-agenda-compute-time-span (sd span)
22628 "Compute starting date and number of days for agenda.
22629 SPAN may be `day', `week', `month', `year'. The return value
22630 is a cons cell with the starting date and the number of days,
22631 so that the date SD will be in that range."
22632 (let* ((greg (calendar-gregorian-from-absolute sd))
22634 (cond
22635 ((eq span 'day)
22636 (setq nd 1))
22637 ((eq span 'week)
22638 (let* ((nt (calendar-day-of-week
22639 (calendar-gregorian-from-absolute sd)))
22640 (d (if org-agenda-start-on-weekday
22641 (- nt org-agenda-start-on-weekday)
22642 0)))
22643 (setq sd (- sd (+ (if (< d 0) 7 0) d)))
22644 (setq nd 7)))
22645 ((eq span 'month)
22646 (setq sd (calendar-absolute-from-gregorian
22647 (list (car greg) 1 (nth 2 greg)))
22648 nd (- (calendar-absolute-from-gregorian
22649 (list (1+ (car greg)) 1 (nth 2 greg)))
22650 sd)))
22651 ((eq span 'year)
22652 (setq sd (calendar-absolute-from-gregorian
22653 (list 1 1 (nth 2 greg)))
22654 nd (- (calendar-absolute-from-gregorian
22655 (list 1 1 (1+ (nth 2 greg))))
22656 sd))))
22657 (cons sd nd)))
22659 ;; FIXME: does not work if user makes date format that starts with a blank
22660 (defun org-agenda-next-date-line (&optional arg)
22661 "Jump to the next line indicating a date in agenda buffer."
22662 (interactive "p")
22663 (org-agenda-check-type t 'agenda 'timeline)
22664 (beginning-of-line 1)
22665 (if (looking-at "^\\S-") (forward-char 1))
22666 (if (not (re-search-forward "^\\S-" nil t arg))
22667 (progn
22668 (backward-char 1)
22669 (error "No next date after this line in this buffer")))
22670 (goto-char (match-beginning 0)))
22672 (defun org-agenda-previous-date-line (&optional arg)
22673 "Jump to the previous line indicating a date in agenda buffer."
22674 (interactive "p")
22675 (org-agenda-check-type t 'agenda 'timeline)
22676 (beginning-of-line 1)
22677 (if (not (re-search-backward "^\\S-" nil t arg))
22678 (error "No previous date before this line in this buffer")))
22680 ;; Initialize the highlight
22681 (defvar org-hl (org-make-overlay 1 1))
22682 (org-overlay-put org-hl 'face 'highlight)
22684 (defun org-highlight (begin end &optional buffer)
22685 "Highlight a region with overlay."
22686 (funcall (if (featurep 'xemacs) 'set-extent-endpoints 'move-overlay)
22687 org-hl begin end (or buffer (current-buffer))))
22689 (defun org-unhighlight ()
22690 "Detach overlay INDEX."
22691 (funcall (if (featurep 'xemacs) 'detach-extent 'delete-overlay) org-hl))
22693 ;; FIXME this is currently not used.
22694 (defun org-highlight-until-next-command (beg end &optional buffer)
22695 (org-highlight beg end buffer)
22696 (add-hook 'pre-command-hook 'org-unhighlight-once))
22697 (defun org-unhighlight-once ()
22698 (remove-hook 'pre-command-hook 'org-unhighlight-once)
22699 (org-unhighlight))
22701 (defun org-agenda-follow-mode ()
22702 "Toggle follow mode in an agenda buffer."
22703 (interactive)
22704 (setq org-agenda-follow-mode (not org-agenda-follow-mode))
22705 (org-agenda-set-mode-name)
22706 (message "Follow mode is %s"
22707 (if org-agenda-follow-mode "on" "off")))
22709 (defun org-agenda-log-mode ()
22710 "Toggle log mode in an agenda buffer."
22711 (interactive)
22712 (org-agenda-check-type t 'agenda 'timeline)
22713 (setq org-agenda-show-log (not org-agenda-show-log))
22714 (org-agenda-set-mode-name)
22715 (org-agenda-redo)
22716 (message "Log mode is %s"
22717 (if org-agenda-show-log "on" "off")))
22719 (defun org-agenda-toggle-diary ()
22720 "Toggle diary inclusion in an agenda buffer."
22721 (interactive)
22722 (org-agenda-check-type t 'agenda)
22723 (setq org-agenda-include-diary (not org-agenda-include-diary))
22724 (org-agenda-redo)
22725 (org-agenda-set-mode-name)
22726 (message "Diary inclusion turned %s"
22727 (if org-agenda-include-diary "on" "off")))
22729 (defun org-agenda-toggle-time-grid ()
22730 "Toggle time grid in an agenda buffer."
22731 (interactive)
22732 (org-agenda-check-type t 'agenda)
22733 (setq org-agenda-use-time-grid (not org-agenda-use-time-grid))
22734 (org-agenda-redo)
22735 (org-agenda-set-mode-name)
22736 (message "Time-grid turned %s"
22737 (if org-agenda-use-time-grid "on" "off")))
22739 (defun org-agenda-set-mode-name ()
22740 "Set the mode name to indicate all the small mode settings."
22741 (setq mode-name
22742 (concat "Org-Agenda"
22743 (if (equal org-agenda-ndays 1) " Day" "")
22744 (if (equal org-agenda-ndays 7) " Week" "")
22745 (if org-agenda-follow-mode " Follow" "")
22746 (if org-agenda-include-diary " Diary" "")
22747 (if org-agenda-use-time-grid " Grid" "")
22748 (if org-agenda-show-log " Log" "")))
22749 (force-mode-line-update))
22751 (defun org-agenda-post-command-hook ()
22752 (and (eolp) (not (bolp)) (backward-char 1))
22753 (setq org-agenda-type (get-text-property (point) 'org-agenda-type))
22754 (if (and org-agenda-follow-mode
22755 (get-text-property (point) 'org-marker))
22756 (org-agenda-show)))
22758 (defun org-agenda-show-priority ()
22759 "Show the priority of the current item.
22760 This priority is composed of the main priority given with the [#A] cookies,
22761 and by additional input from the age of a schedules or deadline entry."
22762 (interactive)
22763 (let* ((pri (get-text-property (point-at-bol) 'priority)))
22764 (message "Priority is %d" (if pri pri -1000))))
22766 (defun org-agenda-show-tags ()
22767 "Show the tags applicable to the current item."
22768 (interactive)
22769 (let* ((tags (get-text-property (point-at-bol) 'tags)))
22770 (if tags
22771 (message "Tags are :%s:"
22772 (org-no-properties (mapconcat 'identity tags ":")))
22773 (message "No tags associated with this line"))))
22775 (defun org-agenda-goto (&optional highlight)
22776 "Go to the Org-mode file which contains the item at point."
22777 (interactive)
22778 (let* ((marker (or (get-text-property (point) 'org-marker)
22779 (org-agenda-error)))
22780 (buffer (marker-buffer marker))
22781 (pos (marker-position marker)))
22782 (switch-to-buffer-other-window buffer)
22783 (widen)
22784 (goto-char pos)
22785 (when (org-mode-p)
22786 (org-show-context 'agenda)
22787 (save-excursion
22788 (and (outline-next-heading)
22789 (org-flag-heading nil)))) ; show the next heading
22790 (recenter (/ (window-height) 2))
22791 (run-hooks 'org-agenda-after-show-hook)
22792 (and highlight (org-highlight (point-at-bol) (point-at-eol)))))
22794 (defvar org-agenda-after-show-hook nil
22795 "Normal hook run after an item has been shown from the agenda.
22796 Point is in the buffer where the item originated.")
22798 (defun org-agenda-kill ()
22799 "Kill the entry or subtree belonging to the current agenda entry."
22800 (interactive)
22801 (or (eq major-mode 'org-agenda-mode) (error "Not in agenda"))
22802 (let* ((marker (or (get-text-property (point) 'org-marker)
22803 (org-agenda-error)))
22804 (buffer (marker-buffer marker))
22805 (pos (marker-position marker))
22806 (type (get-text-property (point) 'type))
22807 dbeg dend (n 0) conf)
22808 (org-with-remote-undo buffer
22809 (with-current-buffer buffer
22810 (save-excursion
22811 (goto-char pos)
22812 (if (and (org-mode-p) (not (member type '("sexp"))))
22813 (setq dbeg (progn (org-back-to-heading t) (point))
22814 dend (org-end-of-subtree t t))
22815 (setq dbeg (point-at-bol)
22816 dend (min (point-max) (1+ (point-at-eol)))))
22817 (goto-char dbeg)
22818 (while (re-search-forward "^[ \t]*\\S-" dend t) (setq n (1+ n)))))
22819 (setq conf (or (eq t org-agenda-confirm-kill)
22820 (and (numberp org-agenda-confirm-kill)
22821 (> n org-agenda-confirm-kill))))
22822 (and conf
22823 (not (y-or-n-p
22824 (format "Delete entry with %d lines in buffer \"%s\"? "
22825 n (buffer-name buffer))))
22826 (error "Abort"))
22827 (org-remove-subtree-entries-from-agenda buffer dbeg dend)
22828 (with-current-buffer buffer (delete-region dbeg dend))
22829 (message "Agenda item and source killed"))))
22831 (defun org-agenda-archive ()
22832 "Kill the entry or subtree belonging to the current agenda entry."
22833 (interactive)
22834 (or (eq major-mode 'org-agenda-mode) (error "Not in agenda"))
22835 (let* ((marker (or (get-text-property (point) 'org-marker)
22836 (org-agenda-error)))
22837 (buffer (marker-buffer marker))
22838 (pos (marker-position marker)))
22839 (org-with-remote-undo buffer
22840 (with-current-buffer buffer
22841 (if (org-mode-p)
22842 (save-excursion
22843 (goto-char pos)
22844 (org-remove-subtree-entries-from-agenda)
22845 (org-back-to-heading t)
22846 (org-archive-subtree))
22847 (error "Archiving works only in Org-mode files"))))))
22849 (defun org-remove-subtree-entries-from-agenda (&optional buf beg end)
22850 "Remove all lines in the agenda that correspond to a given subtree.
22851 The subtree is the one in buffer BUF, starting at BEG and ending at END.
22852 If this information is not given, the function uses the tree at point."
22853 (let ((buf (or buf (current-buffer))) m p)
22854 (save-excursion
22855 (unless (and beg end)
22856 (org-back-to-heading t)
22857 (setq beg (point))
22858 (org-end-of-subtree t)
22859 (setq end (point)))
22860 (set-buffer (get-buffer org-agenda-buffer-name))
22861 (save-excursion
22862 (goto-char (point-max))
22863 (beginning-of-line 1)
22864 (while (not (bobp))
22865 (when (and (setq m (get-text-property (point) 'org-marker))
22866 (equal buf (marker-buffer m))
22867 (setq p (marker-position m))
22868 (>= p beg)
22869 (<= p end))
22870 (let ((inhibit-read-only t))
22871 (delete-region (point-at-bol) (1+ (point-at-eol)))))
22872 (beginning-of-line 0))))))
22874 (defun org-agenda-open-link ()
22875 "Follow the link in the current line, if any."
22876 (interactive)
22877 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local)
22878 (save-excursion
22879 (save-restriction
22880 (narrow-to-region (point-at-bol) (point-at-eol))
22881 (org-open-at-point))))
22883 (defun org-agenda-copy-local-variable (var)
22884 "Get a variable from a referenced buffer and install it here."
22885 (let ((m (get-text-property (point) 'org-marker)))
22886 (when (and m (buffer-live-p (marker-buffer m)))
22887 (org-set-local var (with-current-buffer (marker-buffer m)
22888 (symbol-value var))))))
22890 (defun org-agenda-switch-to (&optional delete-other-windows)
22891 "Go to the Org-mode file which contains the item at point."
22892 (interactive)
22893 (let* ((marker (or (get-text-property (point) 'org-marker)
22894 (org-agenda-error)))
22895 (buffer (marker-buffer marker))
22896 (pos (marker-position marker)))
22897 (switch-to-buffer buffer)
22898 (and delete-other-windows (delete-other-windows))
22899 (widen)
22900 (goto-char pos)
22901 (when (org-mode-p)
22902 (org-show-context 'agenda)
22903 (save-excursion
22904 (and (outline-next-heading)
22905 (org-flag-heading nil)))))) ; show the next heading
22907 (defun org-agenda-goto-mouse (ev)
22908 "Go to the Org-mode file which contains the item at the mouse click."
22909 (interactive "e")
22910 (mouse-set-point ev)
22911 (org-agenda-goto))
22913 (defun org-agenda-show ()
22914 "Display the Org-mode file which contains the item at point."
22915 (interactive)
22916 (let ((win (selected-window)))
22917 (org-agenda-goto t)
22918 (select-window win)))
22920 (defun org-agenda-recenter (arg)
22921 "Display the Org-mode file which contains the item at point and recenter."
22922 (interactive "P")
22923 (let ((win (selected-window)))
22924 (org-agenda-goto t)
22925 (recenter arg)
22926 (select-window win)))
22928 (defun org-agenda-show-mouse (ev)
22929 "Display the Org-mode file which contains the item at the mouse click."
22930 (interactive "e")
22931 (mouse-set-point ev)
22932 (org-agenda-show))
22934 (defun org-agenda-check-no-diary ()
22935 "Check if the entry is a diary link and abort if yes."
22936 (if (get-text-property (point) 'org-agenda-diary-link)
22937 (org-agenda-error)))
22939 (defun org-agenda-error ()
22940 (error "Command not allowed in this line"))
22942 (defun org-agenda-tree-to-indirect-buffer ()
22943 "Show the subtree corresponding to the current entry in an indirect buffer.
22944 This calls the command `org-tree-to-indirect-buffer' from the original
22945 Org-mode buffer.
22946 With numerical prefix arg ARG, go up to this level and then take that tree.
22947 With a C-u prefix, make a separate frame for this tree (i.e. don't use the
22948 dedicated frame)."
22949 (interactive)
22950 (org-agenda-check-no-diary)
22951 (let* ((marker (or (get-text-property (point) 'org-marker)
22952 (org-agenda-error)))
22953 (buffer (marker-buffer marker))
22954 (pos (marker-position marker)))
22955 (with-current-buffer buffer
22956 (save-excursion
22957 (goto-char pos)
22958 (call-interactively 'org-tree-to-indirect-buffer)))))
22960 (defvar org-last-heading-marker (make-marker)
22961 "Marker pointing to the headline that last changed its TODO state
22962 by a remote command from the agenda.")
22964 (defun org-agenda-todo-nextset ()
22965 "Switch TODO entry to next sequence."
22966 (interactive)
22967 (org-agenda-todo 'nextset))
22969 (defun org-agenda-todo-previousset ()
22970 "Switch TODO entry to previous sequence."
22971 (interactive)
22972 (org-agenda-todo 'previousset))
22974 (defun org-agenda-todo (&optional arg)
22975 "Cycle TODO state of line at point, also in Org-mode file.
22976 This changes the line at point, all other lines in the agenda referring to
22977 the same tree node, and the headline of the tree node in the Org-mode file."
22978 (interactive "P")
22979 (org-agenda-check-no-diary)
22980 (let* ((col (current-column))
22981 (marker (or (get-text-property (point) 'org-marker)
22982 (org-agenda-error)))
22983 (buffer (marker-buffer marker))
22984 (pos (marker-position marker))
22985 (hdmarker (get-text-property (point) 'org-hd-marker))
22986 (inhibit-read-only t)
22987 newhead)
22988 (org-with-remote-undo buffer
22989 (with-current-buffer buffer
22990 (widen)
22991 (goto-char pos)
22992 (org-show-context 'agenda)
22993 (save-excursion
22994 (and (outline-next-heading)
22995 (org-flag-heading nil))) ; show the next heading
22996 (org-todo arg)
22997 (and (bolp) (forward-char 1))
22998 (setq newhead (org-get-heading))
22999 (save-excursion
23000 (org-back-to-heading)
23001 (move-marker org-last-heading-marker (point))))
23002 (beginning-of-line 1)
23003 (save-excursion
23004 (org-agenda-change-all-lines newhead hdmarker 'fixface))
23005 (move-to-column col))))
23007 (defun org-agenda-change-all-lines (newhead hdmarker &optional fixface)
23008 "Change all lines in the agenda buffer which match HDMARKER.
23009 The new content of the line will be NEWHEAD (as modified by
23010 `org-format-agenda-item'). HDMARKER is checked with
23011 `equal' against all `org-hd-marker' text properties in the file.
23012 If FIXFACE is non-nil, the face of each item is modified acording to
23013 the new TODO state."
23014 (let* ((inhibit-read-only t)
23015 props m pl undone-face done-face finish new dotime cat tags)
23016 (save-excursion
23017 (goto-char (point-max))
23018 (beginning-of-line 1)
23019 (while (not finish)
23020 (setq finish (bobp))
23021 (when (and (setq m (get-text-property (point) 'org-hd-marker))
23022 (equal m hdmarker))
23023 (setq props (text-properties-at (point))
23024 dotime (get-text-property (point) 'dotime)
23025 cat (get-text-property (point) 'org-category)
23026 tags (get-text-property (point) 'tags)
23027 new (org-format-agenda-item "x" newhead cat tags dotime 'noprefix)
23028 pl (get-text-property (point) 'prefix-length)
23029 undone-face (get-text-property (point) 'undone-face)
23030 done-face (get-text-property (point) 'done-face))
23031 (move-to-column pl)
23032 (cond
23033 ((equal new "")
23034 (beginning-of-line 1)
23035 (and (looking-at ".*\n?") (replace-match "")))
23036 ((looking-at ".*")
23037 (replace-match new t t)
23038 (beginning-of-line 1)
23039 (add-text-properties (point-at-bol) (point-at-eol) props)
23040 (when fixface
23041 (add-text-properties
23042 (point-at-bol) (point-at-eol)
23043 (list 'face
23044 (if org-last-todo-state-is-todo
23045 undone-face done-face))))
23046 (org-agenda-highlight-todo 'line)
23047 (beginning-of-line 1))
23048 (t (error "Line update did not work"))))
23049 (beginning-of-line 0)))
23050 (org-finalize-agenda)))
23052 (defun org-agenda-align-tags (&optional line)
23053 "Align all tags in agenda items to `org-agenda-tags-column'."
23054 (let ((inhibit-read-only t) l c)
23055 (save-excursion
23056 (goto-char (if line (point-at-bol) (point-min)))
23057 (while (re-search-forward (org-re "\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$")
23058 (if line (point-at-eol) nil) t)
23059 (add-text-properties
23060 (match-beginning 2) (match-end 2)
23061 (list 'face (list 'org-tag (get-text-property
23062 (match-beginning 2) 'face))))
23063 (setq l (- (match-end 2) (match-beginning 2))
23064 c (if (< org-agenda-tags-column 0)
23065 (- (abs org-agenda-tags-column) l)
23066 org-agenda-tags-column))
23067 (delete-region (match-beginning 1) (match-end 1))
23068 (goto-char (match-beginning 1))
23069 (insert (org-add-props
23070 (make-string (max 1 (- c (current-column))) ?\ )
23071 (text-properties-at (point))))))))
23073 (defun org-agenda-priority-up ()
23074 "Increase the priority of line at point, also in Org-mode file."
23075 (interactive)
23076 (org-agenda-priority 'up))
23078 (defun org-agenda-priority-down ()
23079 "Decrease the priority of line at point, also in Org-mode file."
23080 (interactive)
23081 (org-agenda-priority 'down))
23083 (defun org-agenda-priority (&optional force-direction)
23084 "Set the priority of line at point, also in Org-mode file.
23085 This changes the line at point, all other lines in the agenda referring to
23086 the same tree node, and the headline of the tree node in the Org-mode file."
23087 (interactive)
23088 (org-agenda-check-no-diary)
23089 (let* ((marker (or (get-text-property (point) 'org-marker)
23090 (org-agenda-error)))
23091 (hdmarker (get-text-property (point) 'org-hd-marker))
23092 (buffer (marker-buffer hdmarker))
23093 (pos (marker-position hdmarker))
23094 (inhibit-read-only t)
23095 newhead)
23096 (org-with-remote-undo buffer
23097 (with-current-buffer buffer
23098 (widen)
23099 (goto-char pos)
23100 (org-show-context 'agenda)
23101 (save-excursion
23102 (and (outline-next-heading)
23103 (org-flag-heading nil))) ; show the next heading
23104 (funcall 'org-priority force-direction)
23105 (end-of-line 1)
23106 (setq newhead (org-get-heading)))
23107 (org-agenda-change-all-lines newhead hdmarker)
23108 (beginning-of-line 1))))
23110 (defun org-get-tags-at (&optional pos)
23111 "Get a list of all headline tags applicable at POS.
23112 POS defaults to point. If tags are inherited, the list contains
23113 the targets in the same sequence as the headlines appear, i.e.
23114 the tags of the current headline come last."
23115 (interactive)
23116 (let (tags lastpos)
23117 (save-excursion
23118 (save-restriction
23119 (widen)
23120 (goto-char (or pos (point)))
23121 (save-match-data
23122 (org-back-to-heading t)
23123 (condition-case nil
23124 (while (not (equal lastpos (point)))
23125 (setq lastpos (point))
23126 (if (looking-at (org-re "[^\r\n]+?:\\([[:alnum:]_@:]+\\):[ \t]*$"))
23127 (setq tags (append (org-split-string
23128 (org-match-string-no-properties 1) ":")
23129 tags)))
23130 (or org-use-tag-inheritance (error ""))
23131 (org-up-heading-all 1))
23132 (error nil))))
23133 tags)))
23135 ;; FIXME: should fix the tags property of the agenda line.
23136 (defun org-agenda-set-tags ()
23137 "Set tags for the current headline."
23138 (interactive)
23139 (org-agenda-check-no-diary)
23140 (if (and (org-region-active-p) (interactive-p))
23141 (call-interactively 'org-change-tag-in-region)
23142 (org-agenda-show) ;;; FIXME This is a stupid hack and should not be needed
23143 (let* ((hdmarker (or (get-text-property (point) 'org-hd-marker)
23144 (org-agenda-error)))
23145 (buffer (marker-buffer hdmarker))
23146 (pos (marker-position hdmarker))
23147 (inhibit-read-only t)
23148 newhead)
23149 (org-with-remote-undo buffer
23150 (with-current-buffer buffer
23151 (widen)
23152 (goto-char pos)
23153 (save-excursion
23154 (org-show-context 'agenda))
23155 (save-excursion
23156 (and (outline-next-heading)
23157 (org-flag-heading nil))) ; show the next heading
23158 (goto-char pos)
23159 (call-interactively 'org-set-tags)
23160 (end-of-line 1)
23161 (setq newhead (org-get-heading)))
23162 (org-agenda-change-all-lines newhead hdmarker)
23163 (beginning-of-line 1)))))
23165 (defun org-agenda-toggle-archive-tag ()
23166 "Toggle the archive tag for the current entry."
23167 (interactive)
23168 (org-agenda-check-no-diary)
23169 (org-agenda-show) ;;; FIXME This is a stupid hack and should not be needed
23170 (let* ((hdmarker (or (get-text-property (point) 'org-hd-marker)
23171 (org-agenda-error)))
23172 (buffer (marker-buffer hdmarker))
23173 (pos (marker-position hdmarker))
23174 (inhibit-read-only t)
23175 newhead)
23176 (org-with-remote-undo buffer
23177 (with-current-buffer buffer
23178 (widen)
23179 (goto-char pos)
23180 (org-show-context 'agenda)
23181 (save-excursion
23182 (and (outline-next-heading)
23183 (org-flag-heading nil))) ; show the next heading
23184 (call-interactively 'org-toggle-archive-tag)
23185 (end-of-line 1)
23186 (setq newhead (org-get-heading)))
23187 (org-agenda-change-all-lines newhead hdmarker)
23188 (beginning-of-line 1))))
23190 (defun org-agenda-date-later (arg &optional what)
23191 "Change the date of this item to one day later."
23192 (interactive "p")
23193 (org-agenda-check-type t 'agenda 'timeline)
23194 (org-agenda-check-no-diary)
23195 (let* ((marker (or (get-text-property (point) 'org-marker)
23196 (org-agenda-error)))
23197 (buffer (marker-buffer marker))
23198 (pos (marker-position marker)))
23199 (org-with-remote-undo buffer
23200 (with-current-buffer buffer
23201 (widen)
23202 (goto-char pos)
23203 (if (not (org-at-timestamp-p))
23204 (error "Cannot find time stamp"))
23205 (org-timestamp-change arg (or what 'day)))
23206 (org-agenda-show-new-time marker org-last-changed-timestamp))
23207 (message "Time stamp changed to %s" org-last-changed-timestamp)))
23209 (defun org-agenda-date-earlier (arg &optional what)
23210 "Change the date of this item to one day earlier."
23211 (interactive "p")
23212 (org-agenda-date-later (- arg) what))
23214 (defun org-agenda-show-new-time (marker stamp &optional prefix)
23215 "Show new date stamp via text properties."
23216 ;; We use text properties to make this undoable
23217 (let ((inhibit-read-only t))
23218 (setq stamp (concat " " prefix " => " stamp))
23219 (save-excursion
23220 (goto-char (point-max))
23221 (while (not (bobp))
23222 (when (equal marker (get-text-property (point) 'org-marker))
23223 (move-to-column (- (window-width) (length stamp)) t)
23224 (if (featurep 'xemacs)
23225 ;; Use `duplicable' property to trigger undo recording
23226 (let ((ex (make-extent nil nil))
23227 (gl (make-glyph stamp)))
23228 (set-glyph-face gl 'secondary-selection)
23229 (set-extent-properties
23230 ex (list 'invisible t 'end-glyph gl 'duplicable t))
23231 (insert-extent ex (1- (point)) (point-at-eol)))
23232 (add-text-properties
23233 (1- (point)) (point-at-eol)
23234 (list 'display (org-add-props stamp nil
23235 'face 'secondary-selection))))
23236 (beginning-of-line 1))
23237 (beginning-of-line 0)))))
23239 (defun org-agenda-date-prompt (arg)
23240 "Change the date of this item. Date is prompted for, with default today.
23241 The prefix ARG is passed to the `org-time-stamp' command and can therefore
23242 be used to request time specification in the time stamp."
23243 (interactive "P")
23244 (org-agenda-check-type t 'agenda 'timeline)
23245 (org-agenda-check-no-diary)
23246 (let* ((marker (or (get-text-property (point) 'org-marker)
23247 (org-agenda-error)))
23248 (buffer (marker-buffer marker))
23249 (pos (marker-position marker)))
23250 (org-with-remote-undo buffer
23251 (with-current-buffer buffer
23252 (widen)
23253 (goto-char pos)
23254 (if (not (org-at-timestamp-p))
23255 (error "Cannot find time stamp"))
23256 (org-time-stamp arg)
23257 (message "Time stamp changed to %s" org-last-changed-timestamp)))))
23259 (defun org-agenda-schedule (arg)
23260 "Schedule the item at point."
23261 (interactive "P")
23262 (org-agenda-check-type t 'agenda 'timeline 'todo 'tags)
23263 (org-agenda-check-no-diary)
23264 (let* ((marker (or (get-text-property (point) 'org-marker)
23265 (org-agenda-error)))
23266 (buffer (marker-buffer marker))
23267 (pos (marker-position marker))
23268 (org-insert-labeled-timestamps-at-point nil)
23270 (message "%s" (marker-insertion-type marker)) (sit-for 3)
23271 (set-marker-insertion-type marker t)
23272 (org-with-remote-undo buffer
23273 (with-current-buffer buffer
23274 (widen)
23275 (goto-char pos)
23276 (setq ts (org-schedule arg)))
23277 (org-agenda-show-new-time marker ts "S"))
23278 (message "Item scheduled for %s" ts)))
23280 (defun org-agenda-deadline (arg)
23281 "Schedule the item at point."
23282 (interactive "P")
23283 (org-agenda-check-type t 'agenda 'timeline 'todo 'tags)
23284 (org-agenda-check-no-diary)
23285 (let* ((marker (or (get-text-property (point) 'org-marker)
23286 (org-agenda-error)))
23287 (buffer (marker-buffer marker))
23288 (pos (marker-position marker))
23289 (org-insert-labeled-timestamps-at-point nil)
23291 (org-with-remote-undo buffer
23292 (with-current-buffer buffer
23293 (widen)
23294 (goto-char pos)
23295 (setq ts (org-deadline arg)))
23296 (org-agenda-show-new-time marker ts "S"))
23297 (message "Deadline for this item set to %s" ts)))
23299 (defun org-get-heading (&optional no-tags)
23300 "Return the heading of the current entry, without the stars."
23301 (save-excursion
23302 (org-back-to-heading t)
23303 (if (looking-at
23304 (if no-tags
23305 (org-re "\\*+[ \t]+\\([^\n\r]*?\\)\\([ \t]+:[[:alnum:]:_@]+:[ \t]*\\)?$")
23306 "\\*+[ \t]+\\([^\r\n]*\\)"))
23307 (match-string 1) "")))
23309 (defun org-agenda-clock-in (&optional arg)
23310 "Start the clock on the currently selected item."
23311 (interactive "P")
23312 (org-agenda-check-no-diary)
23313 (let* ((marker (or (get-text-property (point) 'org-marker)
23314 (org-agenda-error)))
23315 (pos (marker-position marker)))
23316 (org-with-remote-undo (marker-buffer marker)
23317 (with-current-buffer (marker-buffer marker)
23318 (widen)
23319 (goto-char pos)
23320 (org-clock-in)))))
23322 (defun org-agenda-clock-out (&optional arg)
23323 "Stop the currently running clock."
23324 (interactive "P")
23325 (unless (marker-buffer org-clock-marker)
23326 (error "No running clock"))
23327 (org-with-remote-undo (marker-buffer org-clock-marker)
23328 (org-clock-out)))
23330 (defun org-agenda-clock-cancel (&optional arg)
23331 "Cancel the currently running clock."
23332 (interactive "P")
23333 (unless (marker-buffer org-clock-marker)
23334 (error "No running clock"))
23335 (org-with-remote-undo (marker-buffer org-clock-marker)
23336 (org-clock-cancel)))
23338 (defun org-agenda-diary-entry ()
23339 "Make a diary entry, like the `i' command from the calendar.
23340 All the standard commands work: block, weekly etc."
23341 (interactive)
23342 (org-agenda-check-type t 'agenda 'timeline)
23343 (require 'diary-lib)
23344 (let* ((char (progn
23345 (message "Diary entry: [d]ay [w]eekly [m]onthly [y]early [a]nniversary [b]lock [c]yclic")
23346 (read-char-exclusive)))
23347 (cmd (cdr (assoc char
23348 '((?d . insert-diary-entry)
23349 (?w . insert-weekly-diary-entry)
23350 (?m . insert-monthly-diary-entry)
23351 (?y . insert-yearly-diary-entry)
23352 (?a . insert-anniversary-diary-entry)
23353 (?b . insert-block-diary-entry)
23354 (?c . insert-cyclic-diary-entry)))))
23355 (oldf (symbol-function 'calendar-cursor-to-date))
23356 ; (buf (get-file-buffer (substitute-in-file-name diary-file)))
23357 (point (point))
23358 (mark (or (mark t) (point))))
23359 (unless cmd
23360 (error "No command associated with <%c>" char))
23361 (unless (and (get-text-property point 'day)
23362 (or (not (equal ?b char))
23363 (get-text-property mark 'day)))
23364 (error "Don't know which date to use for diary entry"))
23365 ;; We implement this by hacking the `calendar-cursor-to-date' function
23366 ;; and the `calendar-mark-ring' variable. Saves a lot of code.
23367 (let ((calendar-mark-ring
23368 (list (calendar-gregorian-from-absolute
23369 (or (get-text-property mark 'day)
23370 (get-text-property point 'day))))))
23371 (unwind-protect
23372 (progn
23373 (fset 'calendar-cursor-to-date
23374 (lambda (&optional error)
23375 (calendar-gregorian-from-absolute
23376 (get-text-property point 'day))))
23377 (call-interactively cmd))
23378 (fset 'calendar-cursor-to-date oldf)))))
23381 (defun org-agenda-execute-calendar-command (cmd)
23382 "Execute a calendar command from the agenda, with the date associated to
23383 the cursor position."
23384 (org-agenda-check-type t 'agenda 'timeline)
23385 (require 'diary-lib)
23386 (unless (get-text-property (point) 'day)
23387 (error "Don't know which date to use for calendar command"))
23388 (let* ((oldf (symbol-function 'calendar-cursor-to-date))
23389 (point (point))
23390 (date (calendar-gregorian-from-absolute
23391 (get-text-property point 'day)))
23392 ;; the following 3 vars are needed in the calendar
23393 (displayed-day (extract-calendar-day date))
23394 (displayed-month (extract-calendar-month date))
23395 (displayed-year (extract-calendar-year date)))
23396 (unwind-protect
23397 (progn
23398 (fset 'calendar-cursor-to-date
23399 (lambda (&optional error)
23400 (calendar-gregorian-from-absolute
23401 (get-text-property point 'day))))
23402 (call-interactively cmd))
23403 (fset 'calendar-cursor-to-date oldf))))
23405 (defun org-agenda-phases-of-moon ()
23406 "Display the phases of the moon for the 3 months around the cursor date."
23407 (interactive)
23408 (org-agenda-execute-calendar-command 'calendar-phases-of-moon))
23410 (defun org-agenda-holidays ()
23411 "Display the holidays for the 3 months around the cursor date."
23412 (interactive)
23413 (org-agenda-execute-calendar-command 'list-calendar-holidays))
23415 (defun org-agenda-sunrise-sunset (arg)
23416 "Display sunrise and sunset for the cursor date.
23417 Latitude and longitude can be specified with the variables
23418 `calendar-latitude' and `calendar-longitude'. When called with prefix
23419 argument, latitude and longitude will be prompted for."
23420 (interactive "P")
23421 (let ((calendar-longitude (if arg nil calendar-longitude))
23422 (calendar-latitude (if arg nil calendar-latitude))
23423 (calendar-location-name
23424 (if arg "the given coordinates" calendar-location-name)))
23425 (org-agenda-execute-calendar-command 'calendar-sunrise-sunset)))
23427 (defun org-agenda-goto-calendar ()
23428 "Open the Emacs calendar with the date at the cursor."
23429 (interactive)
23430 (org-agenda-check-type t 'agenda 'timeline)
23431 (let* ((day (or (get-text-property (point) 'day)
23432 (error "Don't know which date to open in calendar")))
23433 (date (calendar-gregorian-from-absolute day))
23434 (calendar-move-hook nil)
23435 (view-calendar-holidays-initially nil)
23436 (view-diary-entries-initially nil))
23437 (calendar)
23438 (calendar-goto-date date)))
23440 (defun org-calendar-goto-agenda ()
23441 "Compute the Org-mode agenda for the calendar date displayed at the cursor.
23442 This is a command that has to be installed in `calendar-mode-map'."
23443 (interactive)
23444 (org-agenda-list nil (calendar-absolute-from-gregorian
23445 (calendar-cursor-to-date))
23446 nil))
23448 (defun org-agenda-convert-date ()
23449 (interactive)
23450 (org-agenda-check-type t 'agenda 'timeline)
23451 (let ((day (get-text-property (point) 'day))
23452 date s)
23453 (unless day
23454 (error "Don't know which date to convert"))
23455 (setq date (calendar-gregorian-from-absolute day))
23456 (setq s (concat
23457 "Gregorian: " (calendar-date-string date) "\n"
23458 "ISO: " (calendar-iso-date-string date) "\n"
23459 "Day of Yr: " (calendar-day-of-year-string date) "\n"
23460 "Julian: " (calendar-julian-date-string date) "\n"
23461 "Astron. JD: " (calendar-astro-date-string date)
23462 " (Julian date number at noon UTC)\n"
23463 "Hebrew: " (calendar-hebrew-date-string date) " (until sunset)\n"
23464 "Islamic: " (calendar-islamic-date-string date) " (until sunset)\n"
23465 "French: " (calendar-french-date-string date) "\n"
23466 "Baha'i: " (calendar-bahai-date-string date) " (until sunset)\n"
23467 "Mayan: " (calendar-mayan-date-string date) "\n"
23468 "Coptic: " (calendar-coptic-date-string date) "\n"
23469 "Ethiopic: " (calendar-ethiopic-date-string date) "\n"
23470 "Persian: " (calendar-persian-date-string date) "\n"
23471 "Chinese: " (calendar-chinese-date-string date) "\n"))
23472 (with-output-to-temp-buffer "*Dates*"
23473 (princ s))
23474 (if (fboundp 'fit-window-to-buffer)
23475 (fit-window-to-buffer (get-buffer-window "*Dates*")))))
23478 ;;;; Embedded LaTeX
23480 (defvar org-cdlatex-mode-map (make-sparse-keymap)
23481 "Keymap for the minor `org-cdlatex-mode'.")
23483 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
23484 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
23485 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
23486 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
23487 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
23489 (defvar org-cdlatex-texmathp-advice-is-done nil
23490 "Flag remembering if we have applied the advice to texmathp already.")
23492 (define-minor-mode org-cdlatex-mode
23493 "Toggle the minor `org-cdlatex-mode'.
23494 This mode supports entering LaTeX environment and math in LaTeX fragments
23495 in Org-mode.
23496 \\{org-cdlatex-mode-map}"
23497 nil " OCDL" nil
23498 (when org-cdlatex-mode (require 'cdlatex))
23499 (unless org-cdlatex-texmathp-advice-is-done
23500 (setq org-cdlatex-texmathp-advice-is-done t)
23501 (defadvice texmathp (around org-math-always-on activate)
23502 "Always return t in org-mode buffers.
23503 This is because we want to insert math symbols without dollars even outside
23504 the LaTeX math segments. If Orgmode thinks that point is actually inside
23505 en embedded LaTeX fragement, let texmathp do its job.
23506 \\[org-cdlatex-mode-map]"
23507 (interactive)
23508 (let (p)
23509 (cond
23510 ((not (org-mode-p)) ad-do-it)
23511 ((eq this-command 'cdlatex-math-symbol)
23512 (setq ad-return-value t
23513 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
23515 (let ((p (org-inside-LaTeX-fragment-p)))
23516 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
23517 (setq ad-return-value t
23518 texmathp-why '("Org-mode embedded math" . 0))
23519 (if p ad-do-it)))))))))
23521 (defun turn-on-org-cdlatex ()
23522 "Unconditionally turn on `org-cdlatex-mode'."
23523 (org-cdlatex-mode 1))
23525 (defun org-inside-LaTeX-fragment-p ()
23526 "Test if point is inside a LaTeX fragment.
23527 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
23528 sequence appearing also before point.
23529 Even though the matchers for math are configurable, this function assumes
23530 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
23531 delimiters are skipped when they have been removed by customization.
23532 The return value is nil, or a cons cell with the delimiter and
23533 and the position of this delimiter.
23535 This function does a reasonably good job, but can locally be fooled by
23536 for example currency specifications. For example it will assume being in
23537 inline math after \"$22.34\". The LaTeX fragment formatter will only format
23538 fragments that are properly closed, but during editing, we have to live
23539 with the uncertainty caused by missing closing delimiters. This function
23540 looks only before point, not after."
23541 (catch 'exit
23542 (let ((pos (point))
23543 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
23544 (lim (progn
23545 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
23546 (point)))
23547 dd-on str (start 0) m re)
23548 (goto-char pos)
23549 (when dodollar
23550 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
23551 re (nth 1 (assoc "$" org-latex-regexps)))
23552 (while (string-match re str start)
23553 (cond
23554 ((= (match-end 0) (length str))
23555 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
23556 ((= (match-end 0) (- (length str) 5))
23557 (throw 'exit nil))
23558 (t (setq start (match-end 0))))))
23559 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
23560 (goto-char pos)
23561 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
23562 (and (match-beginning 2) (throw 'exit nil))
23563 ;; count $$
23564 (while (re-search-backward "\\$\\$" lim t)
23565 (setq dd-on (not dd-on)))
23566 (goto-char pos)
23567 (if dd-on (cons "$$" m))))))
23570 (defun org-try-cdlatex-tab ()
23571 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
23572 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
23573 - inside a LaTeX fragment, or
23574 - after the first word in a line, where an abbreviation expansion could
23575 insert a LaTeX environment."
23576 (when org-cdlatex-mode
23577 (cond
23578 ((save-excursion
23579 (skip-chars-backward "a-zA-Z0-9*")
23580 (skip-chars-backward " \t")
23581 (bolp))
23582 (cdlatex-tab) t)
23583 ((org-inside-LaTeX-fragment-p)
23584 (cdlatex-tab) t)
23585 (t nil))))
23587 (defun org-cdlatex-underscore-caret (&optional arg)
23588 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
23589 Revert to the normal definition outside of these fragments."
23590 (interactive "P")
23591 (if (org-inside-LaTeX-fragment-p)
23592 (call-interactively 'cdlatex-sub-superscript)
23593 (let (org-cdlatex-mode)
23594 (call-interactively (key-binding (vector last-input-event))))))
23596 (defun org-cdlatex-math-modify (&optional arg)
23597 "Execute `cdlatex-math-modify' in LaTeX fragments.
23598 Revert to the normal definition outside of these fragments."
23599 (interactive "P")
23600 (if (org-inside-LaTeX-fragment-p)
23601 (call-interactively 'cdlatex-math-modify)
23602 (let (org-cdlatex-mode)
23603 (call-interactively (key-binding (vector last-input-event))))))
23605 (defvar org-latex-fragment-image-overlays nil
23606 "List of overlays carrying the images of latex fragments.")
23607 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
23609 (defun org-remove-latex-fragment-image-overlays ()
23610 "Remove all overlays with LaTeX fragment images in current buffer."
23611 (mapc 'org-delete-overlay org-latex-fragment-image-overlays)
23612 (setq org-latex-fragment-image-overlays nil))
23614 (defun org-preview-latex-fragment (&optional subtree)
23615 "Preview the LaTeX fragment at point, or all locally or globally.
23616 If the cursor is in a LaTeX fragment, create the image and overlay
23617 it over the source code. If there is no fragment at point, display
23618 all fragments in the current text, from one headline to the next. With
23619 prefix SUBTREE, display all fragments in the current subtree. With a
23620 double prefix `C-u C-u', or when the cursor is before the first headline,
23621 display all fragments in the buffer.
23622 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
23623 (interactive "P")
23624 (org-remove-latex-fragment-image-overlays)
23625 (save-excursion
23626 (save-restriction
23627 (let (beg end at msg)
23628 (cond
23629 ((or (equal subtree '(16))
23630 (not (save-excursion
23631 (re-search-backward (concat "^" outline-regexp) nil t))))
23632 (setq beg (point-min) end (point-max)
23633 msg "Creating images for buffer...%s"))
23634 ((equal subtree '(4))
23635 (org-back-to-heading)
23636 (setq beg (point) end (org-end-of-subtree t)
23637 msg "Creating images for subtree...%s"))
23639 (if (setq at (org-inside-LaTeX-fragment-p))
23640 (goto-char (max (point-min) (- (cdr at) 2)))
23641 (org-back-to-heading))
23642 (setq beg (point) end (progn (outline-next-heading) (point))
23643 msg (if at "Creating image...%s"
23644 "Creating images for entry...%s"))))
23645 (message msg "")
23646 (narrow-to-region beg end)
23647 (goto-char beg)
23648 (org-format-latex
23649 (concat "ltxpng/" (file-name-sans-extension
23650 (file-name-nondirectory
23651 buffer-file-name)))
23652 default-directory 'overlays msg at 'forbuffer)
23653 (message msg "done. Use `C-c C-c' to remove images.")))))
23655 (defvar org-latex-regexps
23656 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
23657 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
23658 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
23659 ("$" "\\([^$]\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([ .,?;:'\")\000]\\|$\\)" 2 nil)
23660 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
23661 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 t)
23662 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 t))
23663 "Regular expressions for matching embedded LaTeX.")
23665 (defun org-format-latex (prefix &optional dir overlays msg at forbuffer)
23666 "Replace LaTeX fragments with links to an image, and produce images."
23667 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
23668 (let* ((prefixnodir (file-name-nondirectory prefix))
23669 (absprefix (expand-file-name prefix dir))
23670 (todir (file-name-directory absprefix))
23671 (opt org-format-latex-options)
23672 (matchers (plist-get opt :matchers))
23673 (re-list org-latex-regexps)
23674 (cnt 0) txt link beg end re e checkdir
23675 m n block linkfile movefile ov)
23676 ;; Check if there are old images files with this prefix, and remove them
23677 (when (file-directory-p todir)
23678 (mapc 'delete-file
23679 (directory-files
23680 todir 'full
23681 (concat (regexp-quote prefixnodir) "_[0-9]+\\.png$"))))
23682 ;; Check the different regular expressions
23683 (while (setq e (pop re-list))
23684 (setq m (car e) re (nth 1 e) n (nth 2 e)
23685 block (if (nth 3 e) "\n\n" ""))
23686 (when (member m matchers)
23687 (goto-char (point-min))
23688 (while (re-search-forward re nil t)
23689 (when (or (not at) (equal (cdr at) (match-beginning n)))
23690 (setq txt (match-string n)
23691 beg (match-beginning n) end (match-end n)
23692 cnt (1+ cnt)
23693 linkfile (format "%s_%04d.png" prefix cnt)
23694 movefile (format "%s_%04d.png" absprefix cnt)
23695 link (concat block "[[file:" linkfile "]]" block))
23696 (if msg (message msg cnt))
23697 (goto-char beg)
23698 (unless checkdir ; make sure the directory exists
23699 (setq checkdir t)
23700 (or (file-directory-p todir) (make-directory todir)))
23701 (org-create-formula-image
23702 txt movefile opt forbuffer)
23703 (if overlays
23704 (progn
23705 (setq ov (org-make-overlay beg end))
23706 (if (featurep 'xemacs)
23707 (progn
23708 (org-overlay-put ov 'invisible t)
23709 (org-overlay-put
23710 ov 'end-glyph
23711 (make-glyph (vector 'png :file movefile))))
23712 (org-overlay-put
23713 ov 'display
23714 (list 'image :type 'png :file movefile :ascent 'center)))
23715 (push ov org-latex-fragment-image-overlays)
23716 (goto-char end))
23717 (delete-region beg end)
23718 (insert link))))))))
23720 ;; This function borrows from Ganesh Swami's latex2png.el
23721 (defun org-create-formula-image (string tofile options buffer)
23722 (let* ((tmpdir (if (featurep 'xemacs)
23723 (temp-directory)
23724 temporary-file-directory))
23725 (texfilebase (make-temp-name
23726 (expand-file-name "orgtex" tmpdir)))
23727 (texfile (concat texfilebase ".tex"))
23728 (dvifile (concat texfilebase ".dvi"))
23729 (pngfile (concat texfilebase ".png"))
23730 (fnh (face-attribute 'default :height nil))
23731 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
23732 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
23733 (fg (or (plist-get options (if buffer :foreground :html-foreground))
23734 "Black"))
23735 (bg (or (plist-get options (if buffer :background :html-background))
23736 "Transparent")))
23737 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
23738 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
23739 (with-temp-file texfile
23740 (insert org-format-latex-header
23741 "\n\\begin{document}\n" string "\n\\end{document}\n"))
23742 (let ((dir default-directory))
23743 (condition-case nil
23744 (progn
23745 (cd tmpdir)
23746 (call-process "latex" nil nil nil texfile))
23747 (error nil))
23748 (cd dir))
23749 (if (not (file-exists-p dvifile))
23750 (progn (message "Failed to create dvi file from %s" texfile) nil)
23751 (call-process "dvipng" nil nil nil
23752 "-E" "-fg" fg "-bg" bg
23753 "-D" dpi
23754 ;;"-x" scale "-y" scale
23755 "-T" "tight"
23756 "-o" pngfile
23757 dvifile)
23758 (if (not (file-exists-p pngfile))
23759 (progn (message "Failed to create png file from %s" texfile) nil)
23760 ;; Use the requested file name and clean up
23761 (copy-file pngfile tofile 'replace)
23762 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
23763 (delete-file (concat texfilebase e)))
23764 pngfile))))
23766 (defun org-dvipng-color (attr)
23767 "Return an rgb color specification for dvipng."
23768 (apply 'format "rgb %s %s %s"
23769 (mapcar 'org-normalize-color
23770 (color-values (face-attribute 'default attr nil)))))
23772 (defun org-normalize-color (value)
23773 "Return string to be used as color value for an RGB component."
23774 (format "%g" (/ value 65535.0)))
23776 ;;;; Exporting
23778 ;;; Variables, constants, and parameter plists
23780 (defconst org-level-max 20)
23782 (defvar org-export-html-preamble nil
23783 "Preamble, to be inserted just after <body>. Set by publishing functions.")
23784 (defvar org-export-html-postamble nil
23785 "Preamble, to be inserted just before </body>. Set by publishing functions.")
23786 (defvar org-export-html-auto-preamble t
23787 "Should default preamble be inserted? Set by publishing functions.")
23788 (defvar org-export-html-auto-postamble t
23789 "Should default postamble be inserted? Set by publishing functions.")
23790 (defvar org-current-export-file nil) ; dynamically scoped parameter
23791 (defvar org-current-export-dir nil) ; dynamically scoped parameter
23794 (defconst org-export-plist-vars
23795 '((:language . org-export-default-language)
23796 (:customtime . org-display-custom-times)
23797 (:headline-levels . org-export-headline-levels)
23798 (:section-numbers . org-export-with-section-numbers)
23799 (:table-of-contents . org-export-with-toc)
23800 (:preserve-breaks . org-export-preserve-breaks)
23801 (:archived-trees . org-export-with-archived-trees)
23802 (:emphasize . org-export-with-emphasize)
23803 (:sub-superscript . org-export-with-sub-superscripts)
23804 (:special-strings . org-export-with-special-strings)
23805 (:footnotes . org-export-with-footnotes)
23806 (:drawers . org-export-with-drawers)
23807 (:tags . org-export-with-tags)
23808 (:TeX-macros . org-export-with-TeX-macros)
23809 (:LaTeX-fragments . org-export-with-LaTeX-fragments)
23810 (:skip-before-1st-heading . org-export-skip-text-before-1st-heading)
23811 (:fixed-width . org-export-with-fixed-width)
23812 (:timestamps . org-export-with-timestamps)
23813 (:author-info . org-export-author-info)
23814 (:time-stamp-file . org-export-time-stamp-file)
23815 (:tables . org-export-with-tables)
23816 (:table-auto-headline . org-export-highlight-first-table-line)
23817 (:style . org-export-html-style)
23818 (:agenda-style . org-agenda-export-html-style)
23819 (:convert-org-links . org-export-html-link-org-files-as-html)
23820 (:inline-images . org-export-html-inline-images)
23821 (:html-extension . org-export-html-extension)
23822 (:html-table-tag . org-export-html-table-tag)
23823 (:expand-quoted-html . org-export-html-expand)
23824 (:timestamp . org-export-html-with-timestamp)
23825 (:publishing-directory . org-export-publishing-directory)
23826 (:preamble . org-export-html-preamble)
23827 (:postamble . org-export-html-postamble)
23828 (:auto-preamble . org-export-html-auto-preamble)
23829 (:auto-postamble . org-export-html-auto-postamble)
23830 (:author . user-full-name)
23831 (:email . user-mail-address)))
23833 (defun org-default-export-plist ()
23834 "Return the property list with default settings for the export variables."
23835 (let ((l org-export-plist-vars) rtn e)
23836 (while (setq e (pop l))
23837 (setq rtn (cons (car e) (cons (symbol-value (cdr e)) rtn))))
23838 rtn))
23840 (defun org-infile-export-plist ()
23841 "Return the property list with file-local settings for export."
23842 (save-excursion
23843 (save-restriction
23844 (widen)
23845 (goto-char 0)
23846 (let ((re (org-make-options-regexp
23847 '("TITLE" "AUTHOR" "DATE" "EMAIL" "TEXT" "OPTIONS" "LANGUAGE")))
23848 p key val text options)
23849 (while (re-search-forward re nil t)
23850 (setq key (org-match-string-no-properties 1)
23851 val (org-match-string-no-properties 2))
23852 (cond
23853 ((string-equal key "TITLE") (setq p (plist-put p :title val)))
23854 ((string-equal key "AUTHOR")(setq p (plist-put p :author val)))
23855 ((string-equal key "EMAIL") (setq p (plist-put p :email val)))
23856 ((string-equal key "DATE") (setq p (plist-put p :date val)))
23857 ((string-equal key "LANGUAGE") (setq p (plist-put p :language val)))
23858 ((string-equal key "TEXT")
23859 (setq text (if text (concat text "\n" val) val)))
23860 ((string-equal key "OPTIONS") (setq options val))))
23861 (setq p (plist-put p :text text))
23862 (when options
23863 (let ((op '(("H" . :headline-levels)
23864 ("num" . :section-numbers)
23865 ("toc" . :table-of-contents)
23866 ("\\n" . :preserve-breaks)
23867 ("@" . :expand-quoted-html)
23868 (":" . :fixed-width)
23869 ("|" . :tables)
23870 ("^" . :sub-superscript)
23871 ("-" . :special-strings)
23872 ("f" . :footnotes)
23873 ("d" . :drawers)
23874 ("tags" . :tags)
23875 ("*" . :emphasize)
23876 ("TeX" . :TeX-macros)
23877 ("LaTeX" . :LaTeX-fragments)
23878 ("skip" . :skip-before-1st-heading)
23879 ("author" . :author-info)
23880 ("timestamp" . :time-stamp-file)))
23882 (while (setq o (pop op))
23883 (if (string-match (concat (regexp-quote (car o))
23884 ":\\([^ \t\n\r;,.]*\\)")
23885 options)
23886 (setq p (plist-put p (cdr o)
23887 (car (read-from-string
23888 (match-string 1 options)))))))))
23889 p))))
23891 (defun org-export-directory (type plist)
23892 (let* ((val (plist-get plist :publishing-directory))
23893 (dir (if (listp val)
23894 (or (cdr (assoc type val)) ".")
23895 val)))
23896 dir))
23898 (defun org-skip-comments (lines)
23899 "Skip lines starting with \"#\" and subtrees starting with COMMENT."
23900 (let ((re1 (concat "^\\(\\*+\\)[ \t]+" org-comment-string))
23901 (re2 "^\\(\\*+\\)[ \t\n\r]")
23902 (case-fold-search nil)
23903 rtn line level)
23904 (while (setq line (pop lines))
23905 (cond
23906 ((and (string-match re1 line)
23907 (setq level (- (match-end 1) (match-beginning 1))))
23908 ;; Beginning of a COMMENT subtree. Skip it.
23909 (while (and (setq line (pop lines))
23910 (or (not (string-match re2 line))
23911 (> (- (match-end 1) (match-beginning 1)) level))))
23912 (setq lines (cons line lines)))
23913 ((string-match "^#" line)
23914 ;; an ordinary comment line
23916 ((and org-export-table-remove-special-lines
23917 (string-match "^[ \t]*|" line)
23918 (or (string-match "^[ \t]*| *[!_^] *|" line)
23919 (and (string-match "| *<[0-9]+> *|" line)
23920 (not (string-match "| *[^ <|]" line)))))
23921 ;; a special table line that should be removed
23923 (t (setq rtn (cons line rtn)))))
23924 (nreverse rtn)))
23926 (defun org-export (&optional arg)
23927 (interactive)
23928 (let ((help "[t] insert the export option template
23929 \[v] limit export to visible part of outline tree
23931 \[a] export as ASCII
23933 \[h] export as HTML
23934 \[H] export as HTML to temporary buffer
23935 \[R] export region as HTML
23936 \[b] export as HTML and browse immediately
23937 \[x] export as XOXO
23939 \[l] export as LaTeX
23940 \[L] export as LaTeX to temporary buffer
23942 \[i] export current file as iCalendar file
23943 \[I] export all agenda files as iCalendar files
23944 \[c] export agenda files into combined iCalendar file
23946 \[F] publish current file
23947 \[P] publish current project
23948 \[X] publish... (project will be prompted for)
23949 \[A] publish all projects")
23950 (cmds
23951 '((?t . org-insert-export-options-template)
23952 (?v . org-export-visible)
23953 (?a . org-export-as-ascii)
23954 (?h . org-export-as-html)
23955 (?b . org-export-as-html-and-open)
23956 (?H . org-export-as-html-to-buffer)
23957 (?R . org-export-region-as-html)
23958 (?x . org-export-as-xoxo)
23959 (?l . org-export-as-latex)
23960 (?L . org-export-as-latex-to-buffer)
23961 (?i . org-export-icalendar-this-file)
23962 (?I . org-export-icalendar-all-agenda-files)
23963 (?c . org-export-icalendar-combine-agenda-files)
23964 (?F . org-publish-current-file)
23965 (?P . org-publish-current-project)
23966 (?X . org-publish)
23967 (?A . org-publish-all)))
23968 r1 r2 ass)
23969 (save-window-excursion
23970 (delete-other-windows)
23971 (with-output-to-temp-buffer "*Org Export/Publishing Help*"
23972 (princ help))
23973 (message "Select command: ")
23974 (setq r1 (read-char-exclusive)))
23975 (setq r2 (if (< r1 27) (+ r1 96) r1))
23976 (if (setq ass (assq r2 cmds))
23977 (call-interactively (cdr ass))
23978 (error "No command associated with key %c" r1))))
23980 (defconst org-html-entities
23981 '(("nbsp")
23982 ("iexcl")
23983 ("cent")
23984 ("pound")
23985 ("curren")
23986 ("yen")
23987 ("brvbar")
23988 ("vert" . "&#124;")
23989 ("sect")
23990 ("uml")
23991 ("copy")
23992 ("ordf")
23993 ("laquo")
23994 ("not")
23995 ("shy")
23996 ("reg")
23997 ("macr")
23998 ("deg")
23999 ("plusmn")
24000 ("sup2")
24001 ("sup3")
24002 ("acute")
24003 ("micro")
24004 ("para")
24005 ("middot")
24006 ("odot"."o")
24007 ("star"."*")
24008 ("cedil")
24009 ("sup1")
24010 ("ordm")
24011 ("raquo")
24012 ("frac14")
24013 ("frac12")
24014 ("frac34")
24015 ("iquest")
24016 ("Agrave")
24017 ("Aacute")
24018 ("Acirc")
24019 ("Atilde")
24020 ("Auml")
24021 ("Aring") ("AA"."&Aring;")
24022 ("AElig")
24023 ("Ccedil")
24024 ("Egrave")
24025 ("Eacute")
24026 ("Ecirc")
24027 ("Euml")
24028 ("Igrave")
24029 ("Iacute")
24030 ("Icirc")
24031 ("Iuml")
24032 ("ETH")
24033 ("Ntilde")
24034 ("Ograve")
24035 ("Oacute")
24036 ("Ocirc")
24037 ("Otilde")
24038 ("Ouml")
24039 ("times")
24040 ("Oslash")
24041 ("Ugrave")
24042 ("Uacute")
24043 ("Ucirc")
24044 ("Uuml")
24045 ("Yacute")
24046 ("THORN")
24047 ("szlig")
24048 ("agrave")
24049 ("aacute")
24050 ("acirc")
24051 ("atilde")
24052 ("auml")
24053 ("aring")
24054 ("aelig")
24055 ("ccedil")
24056 ("egrave")
24057 ("eacute")
24058 ("ecirc")
24059 ("euml")
24060 ("igrave")
24061 ("iacute")
24062 ("icirc")
24063 ("iuml")
24064 ("eth")
24065 ("ntilde")
24066 ("ograve")
24067 ("oacute")
24068 ("ocirc")
24069 ("otilde")
24070 ("ouml")
24071 ("divide")
24072 ("oslash")
24073 ("ugrave")
24074 ("uacute")
24075 ("ucirc")
24076 ("uuml")
24077 ("yacute")
24078 ("thorn")
24079 ("yuml")
24080 ("fnof")
24081 ("Alpha")
24082 ("Beta")
24083 ("Gamma")
24084 ("Delta")
24085 ("Epsilon")
24086 ("Zeta")
24087 ("Eta")
24088 ("Theta")
24089 ("Iota")
24090 ("Kappa")
24091 ("Lambda")
24092 ("Mu")
24093 ("Nu")
24094 ("Xi")
24095 ("Omicron")
24096 ("Pi")
24097 ("Rho")
24098 ("Sigma")
24099 ("Tau")
24100 ("Upsilon")
24101 ("Phi")
24102 ("Chi")
24103 ("Psi")
24104 ("Omega")
24105 ("alpha")
24106 ("beta")
24107 ("gamma")
24108 ("delta")
24109 ("epsilon")
24110 ("varepsilon"."&epsilon;")
24111 ("zeta")
24112 ("eta")
24113 ("theta")
24114 ("iota")
24115 ("kappa")
24116 ("lambda")
24117 ("mu")
24118 ("nu")
24119 ("xi")
24120 ("omicron")
24121 ("pi")
24122 ("rho")
24123 ("sigmaf") ("varsigma"."&sigmaf;")
24124 ("sigma")
24125 ("tau")
24126 ("upsilon")
24127 ("phi")
24128 ("chi")
24129 ("psi")
24130 ("omega")
24131 ("thetasym") ("vartheta"."&thetasym;")
24132 ("upsih")
24133 ("piv")
24134 ("bull") ("bullet"."&bull;")
24135 ("hellip") ("dots"."&hellip;")
24136 ("prime")
24137 ("Prime")
24138 ("oline")
24139 ("frasl")
24140 ("weierp")
24141 ("image")
24142 ("real")
24143 ("trade")
24144 ("alefsym")
24145 ("larr") ("leftarrow"."&larr;") ("gets"."&larr;")
24146 ("uarr") ("uparrow"."&uarr;")
24147 ("rarr") ("to"."&rarr;") ("rightarrow"."&rarr;")
24148 ("darr")("downarrow"."&darr;")
24149 ("harr") ("leftrightarrow"."&harr;")
24150 ("crarr") ("hookleftarrow"."&crarr;") ; has round hook, not quite CR
24151 ("lArr") ("Leftarrow"."&lArr;")
24152 ("uArr") ("Uparrow"."&uArr;")
24153 ("rArr") ("Rightarrow"."&rArr;")
24154 ("dArr") ("Downarrow"."&dArr;")
24155 ("hArr") ("Leftrightarrow"."&hArr;")
24156 ("forall")
24157 ("part") ("partial"."&part;")
24158 ("exist") ("exists"."&exist;")
24159 ("empty") ("emptyset"."&empty;")
24160 ("nabla")
24161 ("isin") ("in"."&isin;")
24162 ("notin")
24163 ("ni")
24164 ("prod")
24165 ("sum")
24166 ("minus")
24167 ("lowast") ("ast"."&lowast;")
24168 ("radic")
24169 ("prop") ("proptp"."&prop;")
24170 ("infin") ("infty"."&infin;")
24171 ("ang") ("angle"."&ang;")
24172 ("and") ("wedge"."&and;")
24173 ("or") ("vee"."&or;")
24174 ("cap")
24175 ("cup")
24176 ("int")
24177 ("there4")
24178 ("sim")
24179 ("cong") ("simeq"."&cong;")
24180 ("asymp")("approx"."&asymp;")
24181 ("ne") ("neq"."&ne;")
24182 ("equiv")
24183 ("le")
24184 ("ge")
24185 ("sub") ("subset"."&sub;")
24186 ("sup") ("supset"."&sup;")
24187 ("nsub")
24188 ("sube")
24189 ("supe")
24190 ("oplus")
24191 ("otimes")
24192 ("perp")
24193 ("sdot") ("cdot"."&sdot;")
24194 ("lceil")
24195 ("rceil")
24196 ("lfloor")
24197 ("rfloor")
24198 ("lang")
24199 ("rang")
24200 ("loz") ("Diamond"."&loz;")
24201 ("spades") ("spadesuit"."&spades;")
24202 ("clubs") ("clubsuit"."&clubs;")
24203 ("hearts") ("diamondsuit"."&hearts;")
24204 ("diams") ("diamondsuit"."&diams;")
24205 ("smile"."&#9786;") ("blacksmile"."&#9787;") ("sad"."&#9785;")
24206 ("quot")
24207 ("amp")
24208 ("lt")
24209 ("gt")
24210 ("OElig")
24211 ("oelig")
24212 ("Scaron")
24213 ("scaron")
24214 ("Yuml")
24215 ("circ")
24216 ("tilde")
24217 ("ensp")
24218 ("emsp")
24219 ("thinsp")
24220 ("zwnj")
24221 ("zwj")
24222 ("lrm")
24223 ("rlm")
24224 ("ndash")
24225 ("mdash")
24226 ("lsquo")
24227 ("rsquo")
24228 ("sbquo")
24229 ("ldquo")
24230 ("rdquo")
24231 ("bdquo")
24232 ("dagger")
24233 ("Dagger")
24234 ("permil")
24235 ("lsaquo")
24236 ("rsaquo")
24237 ("euro")
24239 ("arccos"."arccos")
24240 ("arcsin"."arcsin")
24241 ("arctan"."arctan")
24242 ("arg"."arg")
24243 ("cos"."cos")
24244 ("cosh"."cosh")
24245 ("cot"."cot")
24246 ("coth"."coth")
24247 ("csc"."csc")
24248 ("deg"."deg")
24249 ("det"."det")
24250 ("dim"."dim")
24251 ("exp"."exp")
24252 ("gcd"."gcd")
24253 ("hom"."hom")
24254 ("inf"."inf")
24255 ("ker"."ker")
24256 ("lg"."lg")
24257 ("lim"."lim")
24258 ("liminf"."liminf")
24259 ("limsup"."limsup")
24260 ("ln"."ln")
24261 ("log"."log")
24262 ("max"."max")
24263 ("min"."min")
24264 ("Pr"."Pr")
24265 ("sec"."sec")
24266 ("sin"."sin")
24267 ("sinh"."sinh")
24268 ("sup"."sup")
24269 ("tan"."tan")
24270 ("tanh"."tanh")
24272 "Entities for TeX->HTML translation.
24273 Entries can be like (\"ent\"), in which case \"\\ent\" will be translated to
24274 \"&ent;\". An entry can also be a dotted pair like (\"ent\".\"&other;\").
24275 In that case, \"\\ent\" will be translated to \"&other;\".
24276 The list contains HTML entities for Latin-1, Greek and other symbols.
24277 It is supplemented by a number of commonly used TeX macros with appropriate
24278 translations. There is currently no way for users to extend this.")
24280 ;;; General functions for all backends
24282 (defun org-cleaned-string-for-export (string &rest parameters)
24283 "Cleanup a buffer STRING so that links can be created safely."
24284 (interactive)
24285 (let* ((re-radio (and org-target-link-regexp
24286 (concat "\\([^<]\\)\\(" org-target-link-regexp "\\)")))
24287 (re-plain-link (concat "\\([^[<]\\)" org-plain-link-re))
24288 (re-angle-link (concat "\\([^[]\\)" org-angle-link-re))
24289 (re-archive (concat ":" org-archive-tag ":"))
24290 (re-quote (concat "^\\*+[ \t]+" org-quote-string "\\>"))
24291 (re-commented (concat "^\\*+[ \t]+" org-comment-string "\\>"))
24292 (htmlp (plist-get parameters :for-html))
24293 (asciip (plist-get parameters :for-ascii))
24294 (latexp (plist-get parameters :for-LaTeX))
24295 (commentsp (plist-get parameters :comments))
24296 (archived-trees (plist-get parameters :archived-trees))
24297 (inhibit-read-only t)
24298 (drawers org-drawers)
24299 (exp-drawers (plist-get parameters :drawers))
24300 (outline-regexp "\\*+ ")
24301 a b xx
24302 rtn p)
24303 (with-current-buffer (get-buffer-create " org-mode-tmp")
24304 (erase-buffer)
24305 (insert string)
24306 ;; Remove license-to-kill stuff
24307 (while (setq p (text-property-any (point-min) (point-max)
24308 :org-license-to-kill t))
24309 (delete-region p (next-single-property-change p :org-license-to-kill)))
24311 (let ((org-inhibit-startup t)) (org-mode))
24312 (untabify (point-min) (point-max))
24314 ;; Get rid of drawers
24315 (unless (eq t exp-drawers)
24316 (goto-char (point-min))
24317 (let ((re (concat "^[ \t]*:\\("
24318 (mapconcat
24319 'identity
24320 (org-delete-all exp-drawers
24321 (copy-sequence drawers))
24322 "\\|")
24323 "\\):[ \t]*\n\\([^@]*?\n\\)?[ \t]*:END:[ \t]*\n")))
24324 (while (re-search-forward re nil t)
24325 (replace-match ""))))
24327 ;; Get the correct stuff before the first headline
24328 (when (plist-get parameters :skip-before-1st-heading)
24329 (goto-char (point-min))
24330 (when (re-search-forward "^\\*+[ \t]" nil t)
24331 (delete-region (point-min) (match-beginning 0))
24332 (goto-char (point-min))
24333 (insert "\n")))
24334 (when (plist-get parameters :add-text)
24335 (goto-char (point-min))
24336 (insert (plist-get parameters :add-text) "\n"))
24338 ;; Get rid of archived trees
24339 (when (not (eq archived-trees t))
24340 (goto-char (point-min))
24341 (while (re-search-forward re-archive nil t)
24342 (if (not (org-on-heading-p t))
24343 (org-end-of-subtree t)
24344 (beginning-of-line 1)
24345 (setq a (if archived-trees
24346 (1+ (point-at-eol)) (point))
24347 b (org-end-of-subtree t))
24348 (if (> b a) (delete-region a b)))))
24350 ;; Find targets in comments and move them out of comments,
24351 ;; but mark them as targets that should be invisible
24352 (goto-char (point-min))
24353 (while (re-search-forward "^#.*?\\(<<<?[^>\r\n]+>>>?\\).*" nil t)
24354 (replace-match "\\1(INVISIBLE)"))
24356 ;; Protect backend specific stuff, throw away the others.
24357 (let ((formatters
24358 `((,htmlp "HTML" "BEGIN_HTML" "END_HTML")
24359 (,asciip "ASCII" "BEGIN_ASCII" "END_ASCII")
24360 (,latexp "LaTeX" "BEGIN_LaTeX" "END_LaTeX")))
24361 fmt)
24362 (goto-char (point-min))
24363 (while (re-search-forward "^#\\+BEGIN_EXAMPLE[ \t]*\n" nil t)
24364 (goto-char (match-end 0))
24365 (while (not (looking-at "#\\+END_EXAMPLE"))
24366 (insert ": ")
24367 (beginning-of-line 2)))
24368 (goto-char (point-min))
24369 (while (re-search-forward "^[ \t]*:.*\\(\n[ \t]*:.*\\)*" nil t)
24370 (add-text-properties (match-beginning 0) (match-end 0)
24371 '(org-protected t)))
24372 (while formatters
24373 (setq fmt (pop formatters))
24374 (when (car fmt)
24375 (goto-char (point-min))
24376 (while (re-search-forward (concat "^#\\+" (cadr fmt)
24377 ":[ \t]*\\(.*\\)") nil t)
24378 (replace-match "\\1" t)
24379 (add-text-properties
24380 (point-at-bol) (min (1+ (point-at-eol)) (point-max))
24381 '(org-protected t))))
24382 (goto-char (point-min))
24383 (while (re-search-forward
24384 (concat "^#\\+"
24385 (caddr fmt) "\\>.*\\(\\(\n.*\\)*?\n\\)#\\+"
24386 (cadddr fmt) "\\>.*\n?") nil t)
24387 (if (car fmt)
24388 (add-text-properties (match-beginning 1) (1+ (match-end 1))
24389 '(org-protected t))
24390 (delete-region (match-beginning 0) (match-end 0))))))
24392 ;; Protect quoted subtrees
24393 (goto-char (point-min))
24394 (while (re-search-forward re-quote nil t)
24395 (goto-char (match-beginning 0))
24396 (end-of-line 1)
24397 (add-text-properties (point) (org-end-of-subtree t)
24398 '(org-protected t)))
24400 ;; Protect verbatim elements
24401 (goto-char (point-min))
24402 (while (re-search-forward org-verbatim-re nil t)
24403 (add-text-properties (match-beginning 4) (match-end 4)
24404 '(org-protected t))
24405 (goto-char (1+ (match-end 4))))
24407 ;; Remove subtrees that are commented
24408 (goto-char (point-min))
24409 (while (re-search-forward re-commented nil t)
24410 (goto-char (match-beginning 0))
24411 (delete-region (point) (org-end-of-subtree t)))
24413 ;; Remove special table lines
24414 (when org-export-table-remove-special-lines
24415 (goto-char (point-min))
24416 (while (re-search-forward "^[ \t]*|" nil t)
24417 (beginning-of-line 1)
24418 (if (or (looking-at "[ \t]*| *[!_^] *|")
24419 (and (looking-at ".*?| *<[0-9]+> *|")
24420 (not (looking-at ".*?| *[^ <|]"))))
24421 (delete-region (max (point-min) (1- (point-at-bol)))
24422 (point-at-eol))
24423 (end-of-line 1))))
24425 ;; Specific LaTeX stuff
24426 (when latexp
24427 (require 'org-export-latex nil)
24428 (org-export-latex-cleaned-string))
24430 (when asciip
24431 (org-export-ascii-clean-string))
24433 ;; Specific HTML stuff
24434 (when htmlp
24435 ;; Convert LaTeX fragments to images
24436 (when (plist-get parameters :LaTeX-fragments)
24437 (org-format-latex
24438 (concat "ltxpng/" (file-name-sans-extension
24439 (file-name-nondirectory
24440 org-current-export-file)))
24441 org-current-export-dir nil "Creating LaTeX image %s"))
24442 (message "Exporting..."))
24444 ;; Remove or replace comments
24445 (goto-char (point-min))
24446 (while (re-search-forward "^#\\(.*\n?\\)" nil t)
24447 (if commentsp
24448 (progn (add-text-properties
24449 (match-beginning 0) (match-end 0) '(org-protected t))
24450 (replace-match (format commentsp (match-string 1)) t t))
24451 (replace-match "")))
24453 ;; Find matches for radio targets and turn them into internal links
24454 (goto-char (point-min))
24455 (when re-radio
24456 (while (re-search-forward re-radio nil t)
24457 (org-if-unprotected
24458 (replace-match "\\1[[\\2]]"))))
24460 ;; Find all links that contain a newline and put them into a single line
24461 (goto-char (point-min))
24462 (while (re-search-forward "\\(\\(\\[\\|\\]\\)\\[[^]]*?\\)[ \t]*\n[ \t]*\\([^]]*\\]\\(\\[\\|\\]\\)\\)" nil t)
24463 (org-if-unprotected
24464 (replace-match "\\1 \\3")
24465 (goto-char (match-beginning 0))))
24468 ;; Normalize links: Convert angle and plain links into bracket links
24469 ;; Expand link abbreviations
24470 (goto-char (point-min))
24471 (while (re-search-forward re-plain-link nil t)
24472 (goto-char (1- (match-end 0)))
24473 (org-if-unprotected
24474 (let* ((s (concat (match-string 1) "[[" (match-string 2)
24475 ":" (match-string 3) "]]")))
24476 ;; added 'org-link face to links
24477 (put-text-property 0 (length s) 'face 'org-link s)
24478 (replace-match s t t))))
24479 (goto-char (point-min))
24480 (while (re-search-forward re-angle-link nil t)
24481 (goto-char (1- (match-end 0)))
24482 (org-if-unprotected
24483 (let* ((s (concat (match-string 1) "[[" (match-string 2)
24484 ":" (match-string 3) "]]")))
24485 (put-text-property 0 (length s) 'face 'org-link s)
24486 (replace-match s t t))))
24487 (goto-char (point-min))
24488 (while (re-search-forward org-bracket-link-regexp nil t)
24489 (org-if-unprotected
24490 (let* ((s (concat "[[" (setq xx (save-match-data
24491 (org-link-expand-abbrev (match-string 1))))
24493 (if (match-end 3)
24494 (match-string 2)
24495 (concat "[" xx "]"))
24496 "]")))
24497 (put-text-property 0 (length s) 'face 'org-link s)
24498 (replace-match s t t))))
24500 ;; Find multiline emphasis and put them into single line
24501 (when (plist-get parameters :emph-multiline)
24502 (goto-char (point-min))
24503 (while (re-search-forward org-emph-re nil t)
24504 (if (not (= (char-after (match-beginning 3))
24505 (char-after (match-beginning 4))))
24506 (org-if-unprotected
24507 (subst-char-in-region (match-beginning 0) (match-end 0)
24508 ?\n ?\ t)
24509 (goto-char (1- (match-end 0))))
24510 (goto-char (1+ (match-beginning 0))))))
24512 (setq rtn (buffer-string)))
24513 (kill-buffer " org-mode-tmp")
24514 rtn))
24516 (defun org-export-grab-title-from-buffer ()
24517 "Get a title for the current document, from looking at the buffer."
24518 (let ((inhibit-read-only t))
24519 (save-excursion
24520 (goto-char (point-min))
24521 (let ((end (save-excursion (outline-next-heading) (point))))
24522 (when (re-search-forward "^[ \t]*[^|# \t\r\n].*\n" end t)
24523 ;; Mark the line so that it will not be exported as normal text.
24524 (org-unmodified
24525 (add-text-properties (match-beginning 0) (match-end 0)
24526 (list :org-license-to-kill t)))
24527 ;; Return the title string
24528 (org-trim (match-string 0)))))))
24530 (defun org-export-get-title-from-subtree ()
24531 "Return subtree title and exclude it from export."
24532 (let (title (m (mark)))
24533 (save-excursion
24534 (goto-char (region-beginning))
24535 (when (and (org-at-heading-p)
24536 (>= (org-end-of-subtree t t) (region-end)))
24537 ;; This is a subtree, we take the title from the first heading
24538 (goto-char (region-beginning))
24539 (looking-at org-todo-line-regexp)
24540 (setq title (match-string 3))
24541 (org-unmodified
24542 (add-text-properties (point) (1+ (point-at-eol))
24543 (list :org-license-to-kill t)))))
24544 title))
24546 (defun org-solidify-link-text (s &optional alist)
24547 "Take link text and make a safe target out of it."
24548 (save-match-data
24549 (let* ((rtn
24550 (mapconcat
24551 'identity
24552 (org-split-string s "[ \t\r\n]+") "--"))
24553 (a (assoc rtn alist)))
24554 (or (cdr a) rtn))))
24556 (defun org-get-min-level (lines)
24557 "Get the minimum level in LINES."
24558 (let ((re "^\\(\\*+\\) ") l min)
24559 (catch 'exit
24560 (while (setq l (pop lines))
24561 (if (string-match re l)
24562 (throw 'exit (org-tr-level (length (match-string 1 l))))))
24563 1)))
24565 ;; Variable holding the vector with section numbers
24566 (defvar org-section-numbers (make-vector org-level-max 0))
24568 (defun org-init-section-numbers ()
24569 "Initialize the vector for the section numbers."
24570 (let* ((level -1)
24571 (numbers (nreverse (org-split-string "" "\\.")))
24572 (depth (1- (length org-section-numbers)))
24573 (i depth) number-string)
24574 (while (>= i 0)
24575 (if (> i level)
24576 (aset org-section-numbers i 0)
24577 (setq number-string (or (car numbers) "0"))
24578 (if (string-match "\\`[A-Z]\\'" number-string)
24579 (aset org-section-numbers i
24580 (- (string-to-char number-string) ?A -1))
24581 (aset org-section-numbers i (string-to-number number-string)))
24582 (pop numbers))
24583 (setq i (1- i)))))
24585 (defun org-section-number (&optional level)
24586 "Return a string with the current section number.
24587 When LEVEL is non-nil, increase section numbers on that level."
24588 (let* ((depth (1- (length org-section-numbers))) idx n (string ""))
24589 (when level
24590 (when (> level -1)
24591 (aset org-section-numbers
24592 level (1+ (aref org-section-numbers level))))
24593 (setq idx (1+ level))
24594 (while (<= idx depth)
24595 (if (not (= idx 1))
24596 (aset org-section-numbers idx 0))
24597 (setq idx (1+ idx))))
24598 (setq idx 0)
24599 (while (<= idx depth)
24600 (setq n (aref org-section-numbers idx))
24601 (setq string (concat string (if (not (string= string "")) "." "")
24602 (int-to-string n)))
24603 (setq idx (1+ idx)))
24604 (save-match-data
24605 (if (string-match "\\`\\([@0]\\.\\)+" string)
24606 (setq string (replace-match "" t nil string)))
24607 (if (string-match "\\(\\.0\\)+\\'" string)
24608 (setq string (replace-match "" t nil string))))
24609 string))
24611 ;;; ASCII export
24613 (defvar org-last-level nil) ; dynamically scoped variable
24614 (defvar org-min-level nil) ; dynamically scoped variable
24615 (defvar org-levels-open nil) ; dynamically scoped parameter
24616 (defvar org-ascii-current-indentation nil) ; For communication
24618 (defun org-export-as-ascii (arg)
24619 "Export the outline as a pretty ASCII file.
24620 If there is an active region, export only the region.
24621 The prefix ARG specifies how many levels of the outline should become
24622 underlined headlines. The default is 3."
24623 (interactive "P")
24624 (setq-default org-todo-line-regexp org-todo-line-regexp)
24625 (let* ((opt-plist (org-combine-plists (org-default-export-plist)
24626 (org-infile-export-plist)))
24627 (region-p (org-region-active-p))
24628 (subtree-p
24629 (when region-p
24630 (save-excursion
24631 (goto-char (region-beginning))
24632 (and (org-at-heading-p)
24633 (>= (org-end-of-subtree t t) (region-end))))))
24634 (custom-times org-display-custom-times)
24635 (org-ascii-current-indentation '(0 . 0))
24636 (level 0) line txt
24637 (umax nil)
24638 (umax-toc nil)
24639 (case-fold-search nil)
24640 (filename (concat (file-name-as-directory
24641 (org-export-directory :ascii opt-plist))
24642 (file-name-sans-extension
24643 (or (and subtree-p
24644 (org-entry-get (region-beginning)
24645 "EXPORT_FILE_NAME" t))
24646 (file-name-nondirectory buffer-file-name)))
24647 ".txt"))
24648 (filename (if (equal (file-truename filename)
24649 (file-truename buffer-file-name))
24650 (concat filename ".txt")
24651 filename))
24652 (buffer (find-file-noselect filename))
24653 (org-levels-open (make-vector org-level-max nil))
24654 (odd org-odd-levels-only)
24655 (date (plist-get opt-plist :date))
24656 (author (plist-get opt-plist :author))
24657 (title (or (and subtree-p (org-export-get-title-from-subtree))
24658 (plist-get opt-plist :title)
24659 (and (not
24660 (plist-get opt-plist :skip-before-1st-heading))
24661 (org-export-grab-title-from-buffer))
24662 (file-name-sans-extension
24663 (file-name-nondirectory buffer-file-name))))
24664 (email (plist-get opt-plist :email))
24665 (language (plist-get opt-plist :language))
24666 (quote-re0 (concat "^[ \t]*" org-quote-string "\\>"))
24667 ; (quote-re (concat "^\\(\\*+\\)\\([ \t]*" org-quote-string "\\>\\)"))
24668 (todo nil)
24669 (lang-words nil)
24670 (region
24671 (buffer-substring
24672 (if (org-region-active-p) (region-beginning) (point-min))
24673 (if (org-region-active-p) (region-end) (point-max))))
24674 (lines (org-split-string
24675 (org-cleaned-string-for-export
24676 region
24677 :for-ascii t
24678 :skip-before-1st-heading
24679 (plist-get opt-plist :skip-before-1st-heading)
24680 :drawers (plist-get opt-plist :drawers)
24681 :verbatim-multiline t
24682 :archived-trees
24683 (plist-get opt-plist :archived-trees)
24684 :add-text (plist-get opt-plist :text))
24685 "\n"))
24686 thetoc have-headings first-heading-pos
24687 table-open table-buffer)
24689 (let ((inhibit-read-only t))
24690 (org-unmodified
24691 (remove-text-properties (point-min) (point-max)
24692 '(:org-license-to-kill t))))
24694 (setq org-min-level (org-get-min-level lines))
24695 (setq org-last-level org-min-level)
24696 (org-init-section-numbers)
24698 (find-file-noselect filename)
24700 (setq lang-words (or (assoc language org-export-language-setup)
24701 (assoc "en" org-export-language-setup)))
24702 (switch-to-buffer-other-window buffer)
24703 (erase-buffer)
24704 (fundamental-mode)
24705 ;; create local variables for all options, to make sure all called
24706 ;; functions get the correct information
24707 (mapc (lambda (x)
24708 (set (make-local-variable (cdr x))
24709 (plist-get opt-plist (car x))))
24710 org-export-plist-vars)
24711 (org-set-local 'org-odd-levels-only odd)
24712 (setq umax (if arg (prefix-numeric-value arg)
24713 org-export-headline-levels))
24714 (setq umax-toc (if (integerp org-export-with-toc)
24715 (min org-export-with-toc umax)
24716 umax))
24718 ;; File header
24719 (if title (org-insert-centered title ?=))
24720 (insert "\n")
24721 (if (and (or author email)
24722 org-export-author-info)
24723 (insert (concat (nth 1 lang-words) ": " (or author "")
24724 (if email (concat " <" email ">") "")
24725 "\n")))
24727 (cond
24728 ((and date (string-match "%" date))
24729 (setq date (format-time-string date (current-time))))
24730 (date)
24731 (t (setq date (format-time-string "%Y/%m/%d %X" (current-time)))))
24733 (if (and date org-export-time-stamp-file)
24734 (insert (concat (nth 2 lang-words) ": " date"\n")))
24736 (insert "\n\n")
24738 (if org-export-with-toc
24739 (progn
24740 (push (concat (nth 3 lang-words) "\n") thetoc)
24741 (push (concat (make-string (length (nth 3 lang-words)) ?=) "\n") thetoc)
24742 (mapc '(lambda (line)
24743 (if (string-match org-todo-line-regexp
24744 line)
24745 ;; This is a headline
24746 (progn
24747 (setq have-headings t)
24748 (setq level (- (match-end 1) (match-beginning 1))
24749 level (org-tr-level level)
24750 txt (match-string 3 line)
24751 todo
24752 (or (and org-export-mark-todo-in-toc
24753 (match-beginning 2)
24754 (not (member (match-string 2 line)
24755 org-done-keywords)))
24756 ; TODO, not DONE
24757 (and org-export-mark-todo-in-toc
24758 (= level umax-toc)
24759 (org-search-todo-below
24760 line lines level))))
24761 (setq txt (org-html-expand-for-ascii txt))
24763 (while (string-match org-bracket-link-regexp txt)
24764 (setq txt
24765 (replace-match
24766 (match-string (if (match-end 2) 3 1) txt)
24767 t t txt)))
24769 (if (and (memq org-export-with-tags '(not-in-toc nil))
24770 (string-match
24771 (org-re "[ \t]+:[[:alnum:]_@:]+:[ \t]*$")
24772 txt))
24773 (setq txt (replace-match "" t t txt)))
24774 (if (string-match quote-re0 txt)
24775 (setq txt (replace-match "" t t txt)))
24777 (if org-export-with-section-numbers
24778 (setq txt (concat (org-section-number level)
24779 " " txt)))
24780 (if (<= level umax-toc)
24781 (progn
24782 (push
24783 (concat
24784 (make-string
24785 (* (max 0 (- level org-min-level)) 4) ?\ )
24786 (format (if todo "%s (*)\n" "%s\n") txt))
24787 thetoc)
24788 (setq org-last-level level))
24789 ))))
24790 lines)
24791 (setq thetoc (if have-headings (nreverse thetoc) nil))))
24793 (org-init-section-numbers)
24794 (while (setq line (pop lines))
24795 ;; Remove the quoted HTML tags.
24796 (setq line (org-html-expand-for-ascii line))
24797 ;; Remove targets
24798 (while (string-match "<<<?[^<>]*>>>?[ \t]*\n?" line)
24799 (setq line (replace-match "" t t line)))
24800 ;; Replace internal links
24801 (while (string-match org-bracket-link-regexp line)
24802 (setq line (replace-match
24803 (if (match-end 3) "[\\3]" "[\\1]")
24804 t nil line)))
24805 (when custom-times
24806 (setq line (org-translate-time line)))
24807 (cond
24808 ((string-match "^\\(\\*+\\)[ \t]+\\(.*\\)" line)
24809 ;; a Headline
24810 (setq first-heading-pos (or first-heading-pos (point)))
24811 (setq level (org-tr-level (- (match-end 1) (match-beginning 1)))
24812 txt (match-string 2 line))
24813 (org-ascii-level-start level txt umax lines))
24815 ((and org-export-with-tables
24816 (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)" line))
24817 (if (not table-open)
24818 ;; New table starts
24819 (setq table-open t table-buffer nil))
24820 ;; Accumulate lines
24821 (setq table-buffer (cons line table-buffer))
24822 (when (or (not lines)
24823 (not (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)"
24824 (car lines))))
24825 (setq table-open nil
24826 table-buffer (nreverse table-buffer))
24827 (insert (mapconcat
24828 (lambda (x)
24829 (org-fix-indentation x org-ascii-current-indentation))
24830 (org-format-table-ascii table-buffer)
24831 "\n") "\n")))
24833 (setq line (org-fix-indentation line org-ascii-current-indentation))
24834 (if (and org-export-with-fixed-width
24835 (string-match "^\\([ \t]*\\)\\(:\\)" line))
24836 (setq line (replace-match "\\1" nil nil line)))
24837 (insert line "\n"))))
24839 (normal-mode)
24841 ;; insert the table of contents
24842 (when thetoc
24843 (goto-char (point-min))
24844 (if (re-search-forward "^[ \t]*\\[TABLE-OF-CONTENTS\\][ \t]*$" nil t)
24845 (progn
24846 (goto-char (match-beginning 0))
24847 (replace-match ""))
24848 (goto-char first-heading-pos))
24849 (mapc 'insert thetoc)
24850 (or (looking-at "[ \t]*\n[ \t]*\n")
24851 (insert "\n\n")))
24853 ;; Convert whitespace place holders
24854 (goto-char (point-min))
24855 (let (beg end)
24856 (while (setq beg (next-single-property-change (point) 'org-whitespace))
24857 (setq end (next-single-property-change beg 'org-whitespace))
24858 (goto-char beg)
24859 (delete-region beg end)
24860 (insert (make-string (- end beg) ?\ ))))
24862 (save-buffer)
24863 ;; remove display and invisible chars
24864 (let (beg end)
24865 (goto-char (point-min))
24866 (while (setq beg (next-single-property-change (point) 'display))
24867 (setq end (next-single-property-change beg 'display))
24868 (delete-region beg end)
24869 (goto-char beg)
24870 (insert "=>"))
24871 (goto-char (point-min))
24872 (while (setq beg (next-single-property-change (point) 'org-cwidth))
24873 (setq end (next-single-property-change beg 'org-cwidth))
24874 (delete-region beg end)
24875 (goto-char beg)))
24876 (goto-char (point-min))))
24878 (defun org-export-ascii-clean-string ()
24879 "Do extra work for ASCII export"
24880 (goto-char (point-min))
24881 (while (re-search-forward org-verbatim-re nil t)
24882 (goto-char (match-end 2))
24883 (backward-delete-char 1) (insert "'")
24884 (goto-char (match-beginning 2))
24885 (delete-char 1) (insert "`")
24886 (goto-char (match-end 2))))
24888 (defun org-search-todo-below (line lines level)
24889 "Search the subtree below LINE for any TODO entries."
24890 (let ((rest (cdr (memq line lines)))
24891 (re org-todo-line-regexp)
24892 line lv todo)
24893 (catch 'exit
24894 (while (setq line (pop rest))
24895 (if (string-match re line)
24896 (progn
24897 (setq lv (- (match-end 1) (match-beginning 1))
24898 todo (and (match-beginning 2)
24899 (not (member (match-string 2 line)
24900 org-done-keywords))))
24901 ; TODO, not DONE
24902 (if (<= lv level) (throw 'exit nil))
24903 (if todo (throw 'exit t))))))))
24905 (defun org-html-expand-for-ascii (line)
24906 "Handle quoted HTML for ASCII export."
24907 (if org-export-html-expand
24908 (while (string-match "@<[^<>\n]*>" line)
24909 ;; We just remove the tags for now.
24910 (setq line (replace-match "" nil nil line))))
24911 line)
24913 (defun org-insert-centered (s &optional underline)
24914 "Insert the string S centered and underline it with character UNDERLINE."
24915 (let ((ind (max (/ (- 80 (string-width s)) 2) 0)))
24916 (insert (make-string ind ?\ ) s "\n")
24917 (if underline
24918 (insert (make-string ind ?\ )
24919 (make-string (string-width s) underline)
24920 "\n"))))
24922 (defun org-ascii-level-start (level title umax &optional lines)
24923 "Insert a new level in ASCII export."
24924 (let (char (n (- level umax 1)) (ind 0))
24925 (if (> level umax)
24926 (progn
24927 (insert (make-string (* 2 n) ?\ )
24928 (char-to-string (nth (% n (length org-export-ascii-bullets))
24929 org-export-ascii-bullets))
24930 " " title "\n")
24931 ;; find the indentation of the next non-empty line
24932 (catch 'stop
24933 (while lines
24934 (if (string-match "^\\* " (car lines)) (throw 'stop nil))
24935 (if (string-match "^\\([ \t]*\\)\\S-" (car lines))
24936 (throw 'stop (setq ind (org-get-indentation (car lines)))))
24937 (pop lines)))
24938 (setq org-ascii-current-indentation (cons (* 2 (1+ n)) ind)))
24939 (if (or (not (equal (char-before) ?\n))
24940 (not (equal (char-before (1- (point))) ?\n)))
24941 (insert "\n"))
24942 (setq char (nth (- umax level) (reverse org-export-ascii-underline)))
24943 (unless org-export-with-tags
24944 (if (string-match (org-re "[ \t]+\\(:[[:alnum:]_@:]+:\\)[ \t]*$") title)
24945 (setq title (replace-match "" t t title))))
24946 (if org-export-with-section-numbers
24947 (setq title (concat (org-section-number level) " " title)))
24948 (insert title "\n" (make-string (string-width title) char) "\n")
24949 (setq org-ascii-current-indentation '(0 . 0)))))
24951 (defun org-export-visible (type arg)
24952 "Create a copy of the visible part of the current buffer, and export it.
24953 The copy is created in a temporary buffer and removed after use.
24954 TYPE is the final key (as a string) that also select the export command in
24955 the `C-c C-e' export dispatcher.
24956 As a special case, if the you type SPC at the prompt, the temporary
24957 org-mode file will not be removed but presented to you so that you can
24958 continue to use it. The prefix arg ARG is passed through to the exporting
24959 command."
24960 (interactive
24961 (list (progn
24962 (message "Export visible: [a]SCII [h]tml [b]rowse HTML [H/R]uffer with HTML [x]OXO [ ]keep buffer")
24963 (read-char-exclusive))
24964 current-prefix-arg))
24965 (if (not (member type '(?a ?\C-a ?b ?\C-b ?h ?x ?\ )))
24966 (error "Invalid export key"))
24967 (let* ((binding (cdr (assoc type
24968 '((?a . org-export-as-ascii)
24969 (?\C-a . org-export-as-ascii)
24970 (?b . org-export-as-html-and-open)
24971 (?\C-b . org-export-as-html-and-open)
24972 (?h . org-export-as-html)
24973 (?H . org-export-as-html-to-buffer)
24974 (?R . org-export-region-as-html)
24975 (?x . org-export-as-xoxo)))))
24976 (keepp (equal type ?\ ))
24977 (file buffer-file-name)
24978 (buffer (get-buffer-create "*Org Export Visible*"))
24979 s e)
24980 ;; Need to hack the drawers here.
24981 (save-excursion
24982 (goto-char (point-min))
24983 (while (re-search-forward org-drawer-regexp nil t)
24984 (goto-char (match-beginning 1))
24985 (or (org-invisible-p) (org-flag-drawer nil))))
24986 (with-current-buffer buffer (erase-buffer))
24987 (save-excursion
24988 (setq s (goto-char (point-min)))
24989 (while (not (= (point) (point-max)))
24990 (goto-char (org-find-invisible))
24991 (append-to-buffer buffer s (point))
24992 (setq s (goto-char (org-find-visible))))
24993 (org-cycle-hide-drawers 'all)
24994 (goto-char (point-min))
24995 (unless keepp
24996 ;; Copy all comment lines to the end, to make sure #+ settings are
24997 ;; still available for the second export step. Kind of a hack, but
24998 ;; does do the trick.
24999 (if (looking-at "#[^\r\n]*")
25000 (append-to-buffer buffer (match-beginning 0) (1+ (match-end 0))))
25001 (while (re-search-forward "[\n\r]#[^\n\r]*" nil t)
25002 (append-to-buffer buffer (1+ (match-beginning 0))
25003 (min (point-max) (1+ (match-end 0))))))
25004 (set-buffer buffer)
25005 (let ((buffer-file-name file)
25006 (org-inhibit-startup t))
25007 (org-mode)
25008 (show-all)
25009 (unless keepp (funcall binding arg))))
25010 (if (not keepp)
25011 (kill-buffer buffer)
25012 (switch-to-buffer-other-window buffer)
25013 (goto-char (point-min)))))
25015 (defun org-find-visible ()
25016 (let ((s (point)))
25017 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
25018 (get-char-property s 'invisible)))
25020 (defun org-find-invisible ()
25021 (let ((s (point)))
25022 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
25023 (not (get-char-property s 'invisible))))
25026 ;;; HTML export
25028 (defun org-get-current-options ()
25029 "Return a string with current options as keyword options.
25030 Does include HTML export options as well as TODO and CATEGORY stuff."
25031 (format
25032 "#+TITLE: %s
25033 #+AUTHOR: %s
25034 #+EMAIL: %s
25035 #+LANGUAGE: %s
25036 #+TEXT: Some descriptive text to be emitted. Several lines OK.
25037 #+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
25038 #+CATEGORY: %s
25039 #+SEQ_TODO: %s
25040 #+TYP_TODO: %s
25041 #+PRIORITIES: %c %c %c
25042 #+DRAWERS: %s
25043 #+STARTUP: %s %s %s %s %s
25044 #+TAGS: %s
25045 #+ARCHIVE: %s
25046 #+LINK: %s
25048 (buffer-name) (user-full-name) user-mail-address org-export-default-language
25049 org-export-headline-levels
25050 org-export-with-section-numbers
25051 org-export-with-toc
25052 org-export-preserve-breaks
25053 org-export-html-expand
25054 org-export-with-fixed-width
25055 org-export-with-tables
25056 org-export-with-sub-superscripts
25057 org-export-with-special-strings
25058 org-export-with-footnotes
25059 org-export-with-emphasize
25060 org-export-with-TeX-macros
25061 org-export-with-LaTeX-fragments
25062 org-export-skip-text-before-1st-heading
25063 org-export-with-drawers
25064 org-export-with-tags
25065 (file-name-nondirectory buffer-file-name)
25066 "TODO FEEDBACK VERIFY DONE"
25067 "Me Jason Marie DONE"
25068 org-highest-priority org-lowest-priority org-default-priority
25069 (mapconcat 'identity org-drawers " ")
25070 (cdr (assoc org-startup-folded
25071 '((nil . "showall") (t . "overview") (content . "content"))))
25072 (if org-odd-levels-only "odd" "oddeven")
25073 (if org-hide-leading-stars "hidestars" "showstars")
25074 (if org-startup-align-all-tables "align" "noalign")
25075 (cond ((eq org-log-done t) "logdone")
25076 ((equal org-log-done 'note) "lognotedone")
25077 ((not org-log-done) "nologdone"))
25078 (or (mapconcat (lambda (x)
25079 (cond
25080 ((equal '(:startgroup) x) "{")
25081 ((equal '(:endgroup) x) "}")
25082 ((cdr x) (format "%s(%c)" (car x) (cdr x)))
25083 (t (car x))))
25084 (or org-tag-alist (org-get-buffer-tags)) " ") "")
25085 org-archive-location
25086 "org file:~/org/%s.org"
25089 (defun org-insert-export-options-template ()
25090 "Insert into the buffer a template with information for exporting."
25091 (interactive)
25092 (if (not (bolp)) (newline))
25093 (let ((s (org-get-current-options)))
25094 (and (string-match "#\\+CATEGORY" s)
25095 (setq s (substring s 0 (match-beginning 0))))
25096 (insert s)))
25098 (defun org-toggle-fixed-width-section (arg)
25099 "Toggle the fixed-width export.
25100 If there is no active region, the QUOTE keyword at the current headline is
25101 inserted or removed. When present, it causes the text between this headline
25102 and the next to be exported as fixed-width text, and unmodified.
25103 If there is an active region, this command adds or removes a colon as the
25104 first character of this line. If the first character of a line is a colon,
25105 this line is also exported in fixed-width font."
25106 (interactive "P")
25107 (let* ((cc 0)
25108 (regionp (org-region-active-p))
25109 (beg (if regionp (region-beginning) (point)))
25110 (end (if regionp (region-end)))
25111 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
25112 (case-fold-search nil)
25113 (re "[ \t]*\\(:\\)")
25114 off)
25115 (if regionp
25116 (save-excursion
25117 (goto-char beg)
25118 (setq cc (current-column))
25119 (beginning-of-line 1)
25120 (setq off (looking-at re))
25121 (while (> nlines 0)
25122 (setq nlines (1- nlines))
25123 (beginning-of-line 1)
25124 (cond
25125 (arg
25126 (move-to-column cc t)
25127 (insert ":\n")
25128 (forward-line -1))
25129 ((and off (looking-at re))
25130 (replace-match "" t t nil 1))
25131 ((not off) (move-to-column cc t) (insert ":")))
25132 (forward-line 1)))
25133 (save-excursion
25134 (org-back-to-heading)
25135 (if (looking-at (concat outline-regexp
25136 "\\( *\\<" org-quote-string "\\>[ \t]*\\)"))
25137 (replace-match "" t t nil 1)
25138 (if (looking-at outline-regexp)
25139 (progn
25140 (goto-char (match-end 0))
25141 (insert org-quote-string " "))))))))
25143 (defun org-export-as-html-and-open (arg)
25144 "Export the outline as HTML and immediately open it with a browser.
25145 If there is an active region, export only the region.
25146 The prefix ARG specifies how many levels of the outline should become
25147 headlines. The default is 3. Lower levels will become bulleted lists."
25148 (interactive "P")
25149 (org-export-as-html arg 'hidden)
25150 (org-open-file buffer-file-name))
25152 (defun org-export-as-html-batch ()
25153 "Call `org-export-as-html', may be used in batch processing as
25154 emacs --batch
25155 --load=$HOME/lib/emacs/org.el
25156 --eval \"(setq org-export-headline-levels 2)\"
25157 --visit=MyFile --funcall org-export-as-html-batch"
25158 (org-export-as-html org-export-headline-levels 'hidden))
25160 (defun org-export-as-html-to-buffer (arg)
25161 "Call `org-exort-as-html` with output to a temporary buffer.
25162 No file is created. The prefix ARG is passed through to `org-export-as-html'."
25163 (interactive "P")
25164 (org-export-as-html arg nil nil "*Org HTML Export*")
25165 (switch-to-buffer-other-window "*Org HTML Export*"))
25167 (defun org-replace-region-by-html (beg end)
25168 "Assume the current region has org-mode syntax, and convert it to HTML.
25169 This can be used in any buffer. For example, you could write an
25170 itemized list in org-mode syntax in an HTML buffer and then use this
25171 command to convert it."
25172 (interactive "r")
25173 (let (reg html buf pop-up-frames)
25174 (save-window-excursion
25175 (if (org-mode-p)
25176 (setq html (org-export-region-as-html
25177 beg end t 'string))
25178 (setq reg (buffer-substring beg end)
25179 buf (get-buffer-create "*Org tmp*"))
25180 (with-current-buffer buf
25181 (erase-buffer)
25182 (insert reg)
25183 (org-mode)
25184 (setq html (org-export-region-as-html
25185 (point-min) (point-max) t 'string)))
25186 (kill-buffer buf)))
25187 (delete-region beg end)
25188 (insert html)))
25190 (defun org-export-region-as-html (beg end &optional body-only buffer)
25191 "Convert region from BEG to END in org-mode buffer to HTML.
25192 If prefix arg BODY-ONLY is set, omit file header, footer, and table of
25193 contents, and only produce the region of converted text, useful for
25194 cut-and-paste operations.
25195 If BUFFER is a buffer or a string, use/create that buffer as a target
25196 of the converted HTML. If BUFFER is the symbol `string', return the
25197 produced HTML as a string and leave not buffer behind. For example,
25198 a Lisp program could call this function in the following way:
25200 (setq html (org-export-region-as-html beg end t 'string))
25202 When called interactively, the output buffer is selected, and shown
25203 in a window. A non-interactive call will only retunr the buffer."
25204 (interactive "r\nP")
25205 (when (interactive-p)
25206 (setq buffer "*Org HTML Export*"))
25207 (let ((transient-mark-mode t) (zmacs-regions t)
25208 rtn)
25209 (goto-char end)
25210 (set-mark (point)) ;; to activate the region
25211 (goto-char beg)
25212 (setq rtn (org-export-as-html
25213 nil nil nil
25214 buffer body-only))
25215 (if (fboundp 'deactivate-mark) (deactivate-mark))
25216 (if (and (interactive-p) (bufferp rtn))
25217 (switch-to-buffer-other-window rtn)
25218 rtn)))
25220 (defvar html-table-tag nil) ; dynamically scoped into this.
25221 (defun org-export-as-html (arg &optional hidden ext-plist
25222 to-buffer body-only)
25223 "Export the outline as a pretty HTML file.
25224 If there is an active region, export only the region. The prefix
25225 ARG specifies how many levels of the outline should become
25226 headlines. The default is 3. Lower levels will become bulleted
25227 lists. When HIDDEN is non-nil, don't display the HTML buffer.
25228 EXT-PLIST is a property list with external parameters overriding
25229 org-mode's default settings, but still inferior to file-local
25230 settings. When TO-BUFFER is non-nil, create a buffer with that
25231 name and export to that buffer. If TO-BUFFER is the symbol `string',
25232 don't leave any buffer behind but just return the resulting HTML as
25233 a string. When BODY-ONLY is set, don't produce the file header and footer,
25234 simply return the content of <body>...</body>, without even
25235 the body tags themselves."
25236 (interactive "P")
25238 ;; Make sure we have a file name when we need it.
25239 (when (and (not (or to-buffer body-only))
25240 (not buffer-file-name))
25241 (if (buffer-base-buffer)
25242 (org-set-local 'buffer-file-name
25243 (with-current-buffer (buffer-base-buffer)
25244 buffer-file-name))
25245 (error "Need a file name to be able to export.")))
25247 (message "Exporting...")
25248 (setq-default org-todo-line-regexp org-todo-line-regexp)
25249 (setq-default org-deadline-line-regexp org-deadline-line-regexp)
25250 (setq-default org-done-keywords org-done-keywords)
25251 (setq-default org-maybe-keyword-time-regexp org-maybe-keyword-time-regexp)
25252 (let* ((opt-plist (org-combine-plists (org-default-export-plist)
25253 ext-plist
25254 (org-infile-export-plist)))
25256 (style (plist-get opt-plist :style))
25257 (html-extension (plist-get opt-plist :html-extension))
25258 (link-validate (plist-get opt-plist :link-validation-function))
25259 valid thetoc have-headings first-heading-pos
25260 (odd org-odd-levels-only)
25261 (region-p (org-region-active-p))
25262 (subtree-p
25263 (when region-p
25264 (save-excursion
25265 (goto-char (region-beginning))
25266 (and (org-at-heading-p)
25267 (>= (org-end-of-subtree t t) (region-end))))))
25268 ;; The following two are dynamically scoped into other
25269 ;; routines below.
25270 (org-current-export-dir (org-export-directory :html opt-plist))
25271 (org-current-export-file buffer-file-name)
25272 (level 0) (line "") (origline "") txt todo
25273 (umax nil)
25274 (umax-toc nil)
25275 (filename (if to-buffer nil
25276 (expand-file-name
25277 (concat
25278 (file-name-sans-extension
25279 (or (and subtree-p
25280 (org-entry-get (region-beginning)
25281 "EXPORT_FILE_NAME" t))
25282 (file-name-nondirectory buffer-file-name)))
25283 "." html-extension)
25284 (file-name-as-directory
25285 (org-export-directory :html opt-plist)))))
25286 (current-dir (if buffer-file-name
25287 (file-name-directory buffer-file-name)
25288 default-directory))
25289 (buffer (if to-buffer
25290 (cond
25291 ((eq to-buffer 'string) (get-buffer-create "*Org HTML Export*"))
25292 (t (get-buffer-create to-buffer)))
25293 (find-file-noselect filename)))
25294 (org-levels-open (make-vector org-level-max nil))
25295 (date (plist-get opt-plist :date))
25296 (author (plist-get opt-plist :author))
25297 (title (or (and subtree-p (org-export-get-title-from-subtree))
25298 (plist-get opt-plist :title)
25299 (and (not
25300 (plist-get opt-plist :skip-before-1st-heading))
25301 (org-export-grab-title-from-buffer))
25302 (and buffer-file-name
25303 (file-name-sans-extension
25304 (file-name-nondirectory buffer-file-name)))
25305 "UNTITLED"))
25306 (html-table-tag (plist-get opt-plist :html-table-tag))
25307 (quote-re0 (concat "^[ \t]*" org-quote-string "\\>"))
25308 (quote-re (concat "^\\(\\*+\\)\\([ \t]+" org-quote-string "\\>\\)"))
25309 (inquote nil)
25310 (infixed nil)
25311 (in-local-list nil)
25312 (local-list-num nil)
25313 (local-list-indent nil)
25314 (llt org-plain-list-ordered-item-terminator)
25315 (email (plist-get opt-plist :email))
25316 (language (plist-get opt-plist :language))
25317 (lang-words nil)
25318 (target-alist nil) tg
25319 (head-count 0) cnt
25320 (start 0)
25321 (coding-system (and (boundp 'buffer-file-coding-system)
25322 buffer-file-coding-system))
25323 (coding-system-for-write (or org-export-html-coding-system
25324 coding-system))
25325 (save-buffer-coding-system (or org-export-html-coding-system
25326 coding-system))
25327 (charset (and coding-system-for-write
25328 (fboundp 'coding-system-get)
25329 (coding-system-get coding-system-for-write
25330 'mime-charset)))
25331 (region
25332 (buffer-substring
25333 (if region-p (region-beginning) (point-min))
25334 (if region-p (region-end) (point-max))))
25335 (lines
25336 (org-split-string
25337 (org-cleaned-string-for-export
25338 region
25339 :emph-multiline t
25340 :for-html t
25341 :skip-before-1st-heading
25342 (plist-get opt-plist :skip-before-1st-heading)
25343 :drawers (plist-get opt-plist :drawers)
25344 :archived-trees
25345 (plist-get opt-plist :archived-trees)
25346 :add-text
25347 (plist-get opt-plist :text)
25348 :LaTeX-fragments
25349 (plist-get opt-plist :LaTeX-fragments))
25350 "[\r\n]"))
25351 table-open type
25352 table-buffer table-orig-buffer
25353 ind start-is-num starter didclose
25354 rpl path desc descp desc1 desc2 link
25357 (let ((inhibit-read-only t))
25358 (org-unmodified
25359 (remove-text-properties (point-min) (point-max)
25360 '(:org-license-to-kill t))))
25362 (message "Exporting...")
25364 (setq org-min-level (org-get-min-level lines))
25365 (setq org-last-level org-min-level)
25366 (org-init-section-numbers)
25368 (cond
25369 ((and date (string-match "%" date))
25370 (setq date (format-time-string date (current-time))))
25371 (date)
25372 (t (setq date (format-time-string "%Y/%m/%d %X" (current-time)))))
25374 ;; Get the language-dependent settings
25375 (setq lang-words (or (assoc language org-export-language-setup)
25376 (assoc "en" org-export-language-setup)))
25378 ;; Switch to the output buffer
25379 (set-buffer buffer)
25380 (let ((inhibit-read-only t)) (erase-buffer))
25381 (fundamental-mode)
25383 (and (fboundp 'set-buffer-file-coding-system)
25384 (set-buffer-file-coding-system coding-system-for-write))
25386 (let ((case-fold-search nil)
25387 (org-odd-levels-only odd))
25388 ;; create local variables for all options, to make sure all called
25389 ;; functions get the correct information
25390 (mapc (lambda (x)
25391 (set (make-local-variable (cdr x))
25392 (plist-get opt-plist (car x))))
25393 org-export-plist-vars)
25394 (setq umax (if arg (prefix-numeric-value arg)
25395 org-export-headline-levels))
25396 (setq umax-toc (if (integerp org-export-with-toc)
25397 (min org-export-with-toc umax)
25398 umax))
25399 (unless body-only
25400 ;; File header
25401 (insert (format
25402 "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"
25403 \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">
25404 <html xmlns=\"http://www.w3.org/1999/xhtml\"
25405 lang=\"%s\" xml:lang=\"%s\">
25406 <head>
25407 <title>%s</title>
25408 <meta http-equiv=\"Content-Type\" content=\"text/html;charset=%s\"/>
25409 <meta name=\"generator\" content=\"Org-mode\"/>
25410 <meta name=\"generated\" content=\"%s\"/>
25411 <meta name=\"author\" content=\"%s\"/>
25413 </head><body>
25415 language language (org-html-expand title)
25416 (or charset "iso-8859-1") date author style))
25418 (insert (or (plist-get opt-plist :preamble) ""))
25420 (when (plist-get opt-plist :auto-preamble)
25421 (if title (insert (format org-export-html-title-format
25422 (org-html-expand title))))))
25424 (if (and org-export-with-toc (not body-only))
25425 (progn
25426 (push (format "<h%d>%s</h%d>\n"
25427 org-export-html-toplevel-hlevel
25428 (nth 3 lang-words)
25429 org-export-html-toplevel-hlevel)
25430 thetoc)
25431 (push "<ul>\n<li>" thetoc)
25432 (setq lines
25433 (mapcar '(lambda (line)
25434 (if (string-match org-todo-line-regexp line)
25435 ;; This is a headline
25436 (progn
25437 (setq have-headings t)
25438 (setq level (- (match-end 1) (match-beginning 1))
25439 level (org-tr-level level)
25440 txt (save-match-data
25441 (org-html-expand
25442 (org-export-cleanup-toc-line
25443 (match-string 3 line))))
25444 todo
25445 (or (and org-export-mark-todo-in-toc
25446 (match-beginning 2)
25447 (not (member (match-string 2 line)
25448 org-done-keywords)))
25449 ; TODO, not DONE
25450 (and org-export-mark-todo-in-toc
25451 (= level umax-toc)
25452 (org-search-todo-below
25453 line lines level))))
25454 (if (string-match
25455 (org-re "[ \t]+:\\([[:alnum:]_@:]+\\):[ \t]*$") txt)
25456 (setq txt (replace-match "&nbsp;&nbsp;&nbsp;<span class=\"tag\"> \\1</span>" t nil txt)))
25457 (if (string-match quote-re0 txt)
25458 (setq txt (replace-match "" t t txt)))
25459 (if org-export-with-section-numbers
25460 (setq txt (concat (org-section-number level)
25461 " " txt)))
25462 (if (<= level (max umax umax-toc))
25463 (setq head-count (+ head-count 1)))
25464 (if (<= level umax-toc)
25465 (progn
25466 (if (> level org-last-level)
25467 (progn
25468 (setq cnt (- level org-last-level))
25469 (while (>= (setq cnt (1- cnt)) 0)
25470 (push "\n<ul>\n<li>" thetoc))
25471 (push "\n" thetoc)))
25472 (if (< level org-last-level)
25473 (progn
25474 (setq cnt (- org-last-level level))
25475 (while (>= (setq cnt (1- cnt)) 0)
25476 (push "</li>\n</ul>" thetoc))
25477 (push "\n" thetoc)))
25478 ;; Check for targets
25479 (while (string-match org-target-regexp line)
25480 (setq tg (match-string 1 line)
25481 line (replace-match
25482 (concat "@<span class=\"target\">" tg "@</span> ")
25483 t t line))
25484 (push (cons (org-solidify-link-text tg)
25485 (format "sec-%d" head-count))
25486 target-alist))
25487 (while (string-match "&lt;\\(&lt;\\)+\\|&gt;\\(&gt;\\)+" txt)
25488 (setq txt (replace-match "" t t txt)))
25489 (push
25490 (format
25491 (if todo
25492 "</li>\n<li><a href=\"#sec-%d\"><span class=\"todo\">%s</span></a>"
25493 "</li>\n<li><a href=\"#sec-%d\">%s</a>")
25494 head-count txt) thetoc)
25496 (setq org-last-level level))
25498 line)
25499 lines))
25500 (while (> org-last-level (1- org-min-level))
25501 (setq org-last-level (1- org-last-level))
25502 (push "</li>\n</ul>\n" thetoc))
25503 (setq thetoc (if have-headings (nreverse thetoc) nil))))
25505 (setq head-count 0)
25506 (org-init-section-numbers)
25508 (while (setq line (pop lines) origline line)
25509 (catch 'nextline
25511 ;; end of quote section?
25512 (when (and inquote (string-match "^\\*+ " line))
25513 (insert "</pre>\n")
25514 (setq inquote nil))
25515 ;; inside a quote section?
25516 (when inquote
25517 (insert (org-html-protect line) "\n")
25518 (throw 'nextline nil))
25520 ;; verbatim lines
25521 (when (and org-export-with-fixed-width
25522 (string-match "^[ \t]*:\\(.*\\)" line))
25523 (when (not infixed)
25524 (setq infixed t)
25525 (insert "<pre>\n"))
25526 (insert (org-html-protect (match-string 1 line)) "\n")
25527 (when (and lines
25528 (not (string-match "^[ \t]*\\(:.*\\)"
25529 (car lines))))
25530 (setq infixed nil)
25531 (insert "</pre>\n"))
25532 (throw 'nextline nil))
25534 ;; Protected HTML
25535 (when (get-text-property 0 'org-protected line)
25536 (let (par)
25537 (when (re-search-backward
25538 "\\(<p>\\)\\([ \t\r\n]*\\)\\=" (- (point) 100) t)
25539 (setq par (match-string 1))
25540 (replace-match "\\2\n"))
25541 (insert line "\n")
25542 (while (and lines
25543 (or (= (length (car lines)) 0)
25544 (get-text-property 0 'org-protected (car lines))))
25545 (insert (pop lines) "\n"))
25546 (and par (insert "<p>\n")))
25547 (throw 'nextline nil))
25549 ;; Horizontal line
25550 (when (string-match "^[ \t]*-\\{5,\\}[ \t]*$" line)
25551 (insert "\n<hr/>\n")
25552 (throw 'nextline nil))
25554 ;; make targets to anchors
25555 (while (string-match "<<<?\\([^<>]*\\)>>>?\\((INVISIBLE)\\)?[ \t]*\n?" line)
25556 (cond
25557 ((match-end 2)
25558 (setq line (replace-match
25559 (concat "@<a name=\""
25560 (org-solidify-link-text (match-string 1 line))
25561 "\">\\nbsp@</a>")
25562 t t line)))
25563 ((and org-export-with-toc (equal (string-to-char line) ?*))
25564 (setq line (replace-match
25565 (concat "@<span class=\"target\">" (match-string 1 line) "@</span> ")
25566 ; (concat "@<i>" (match-string 1 line) "@</i> ")
25567 t t line)))
25569 (setq line (replace-match
25570 (concat "@<a name=\""
25571 (org-solidify-link-text (match-string 1 line))
25572 "\" class=\"target\">" (match-string 1 line) "@</a> ")
25573 t t line)))))
25575 (setq line (org-html-handle-time-stamps line))
25577 ;; replace "&" by "&amp;", "<" and ">" by "&lt;" and "&gt;"
25578 ;; handle @<..> HTML tags (replace "@&gt;..&lt;" by "<..>")
25579 ;; Also handle sub_superscripts and checkboxes
25580 (or (string-match org-table-hline-regexp line)
25581 (setq line (org-html-expand line)))
25583 ;; Format the links
25584 (setq start 0)
25585 (while (string-match org-bracket-link-analytic-regexp line start)
25586 (setq start (match-beginning 0))
25587 (setq type (if (match-end 2) (match-string 2 line) "internal"))
25588 (setq path (match-string 3 line))
25589 (setq desc1 (if (match-end 5) (match-string 5 line))
25590 desc2 (if (match-end 2) (concat type ":" path) path)
25591 descp (and desc1 (not (equal desc1 desc2)))
25592 desc (or desc1 desc2))
25593 ;; Make an image out of the description if that is so wanted
25594 (when (and descp (org-file-image-p desc))
25595 (save-match-data
25596 (if (string-match "^file:" desc)
25597 (setq desc (substring desc (match-end 0)))))
25598 (setq desc (concat "<img src=\"" desc "\"/>")))
25599 ;; FIXME: do we need to unescape here somewhere?
25600 (cond
25601 ((equal type "internal")
25602 (setq rpl
25603 (concat
25604 "<a href=\"#"
25605 (org-solidify-link-text
25606 (save-match-data (org-link-unescape path)) target-alist)
25607 "\">" desc "</a>")))
25608 ((member type '("http" "https"))
25609 ;; standard URL, just check if we need to inline an image
25610 (if (and (or (eq t org-export-html-inline-images)
25611 (and org-export-html-inline-images (not descp)))
25612 (org-file-image-p path))
25613 (setq rpl (concat "<img src=\"" type ":" path "\"/>"))
25614 (setq link (concat type ":" path))
25615 (setq rpl (concat "<a href=\"" link "\">" desc "</a>"))))
25616 ((member type '("ftp" "mailto" "news"))
25617 ;; standard URL
25618 (setq link (concat type ":" path))
25619 (setq rpl (concat "<a href=\"" link "\">" desc "</a>")))
25620 ((string= type "file")
25621 ;; FILE link
25622 (let* ((filename path)
25623 (abs-p (file-name-absolute-p filename))
25624 thefile file-is-image-p search)
25625 (save-match-data
25626 (if (string-match "::\\(.*\\)" filename)
25627 (setq search (match-string 1 filename)
25628 filename (replace-match "" t nil filename)))
25629 (setq valid
25630 (if (functionp link-validate)
25631 (funcall link-validate filename current-dir)
25633 (setq file-is-image-p (org-file-image-p filename))
25634 (setq thefile (if abs-p (expand-file-name filename) filename))
25635 (when (and org-export-html-link-org-files-as-html
25636 (string-match "\\.org$" thefile))
25637 (setq thefile (concat (substring thefile 0
25638 (match-beginning 0))
25639 "." html-extension))
25640 (if (and search
25641 ;; make sure this is can be used as target search
25642 (not (string-match "^[0-9]*$" search))
25643 (not (string-match "^\\*" search))
25644 (not (string-match "^/.*/$" search)))
25645 (setq thefile (concat thefile "#"
25646 (org-solidify-link-text
25647 (org-link-unescape search)))))
25648 (when (string-match "^file:" desc)
25649 (setq desc (replace-match "" t t desc))
25650 (if (string-match "\\.org$" desc)
25651 (setq desc (replace-match "" t t desc))))))
25652 (setq rpl (if (and file-is-image-p
25653 (or (eq t org-export-html-inline-images)
25654 (and org-export-html-inline-images
25655 (not descp))))
25656 (concat "<img src=\"" thefile "\"/>")
25657 (concat "<a href=\"" thefile "\">" desc "</a>")))
25658 (if (not valid) (setq rpl desc))))
25659 ((member type '("bbdb" "vm" "wl" "mhe" "rmail" "gnus" "shell" "info" "elisp"))
25660 (setq rpl (concat "<i>&lt;" type ":"
25661 (save-match-data (org-link-unescape path))
25662 "&gt;</i>"))))
25663 (setq line (replace-match rpl t t line)
25664 start (+ start (length rpl))))
25666 ;; TODO items
25667 (if (and (string-match org-todo-line-regexp line)
25668 (match-beginning 2))
25670 (setq line
25671 (concat (substring line 0 (match-beginning 2))
25672 "<span class=\""
25673 (if (member (match-string 2 line)
25674 org-done-keywords)
25675 "done" "todo")
25676 "\">" (match-string 2 line)
25677 "</span>" (substring line (match-end 2)))))
25679 ;; Does this contain a reference to a footnote?
25680 (when org-export-with-footnotes
25681 (setq start 0)
25682 (while (string-match "\\([^* \t].*?\\)\\[\\([0-9]+\\)\\]" line start)
25683 (if (get-text-property (match-beginning 2) 'org-protected line)
25684 (setq start (match-end 2))
25685 (let ((n (match-string 2 line)))
25686 (setq line
25687 (replace-match
25688 (format
25689 "%s<sup><a class=\"footref\" name=\"fnr.%s\" href=\"#fn.%s\">%s</a></sup>"
25690 (match-string 1 line) n n n)
25691 t t line))))))
25693 (cond
25694 ((string-match "^\\(\\*+\\)[ \t]+\\(.*\\)" line)
25695 ;; This is a headline
25696 (setq level (org-tr-level (- (match-end 1) (match-beginning 1)))
25697 txt (match-string 2 line))
25698 (if (string-match quote-re0 txt)
25699 (setq txt (replace-match "" t t txt)))
25700 (if (<= level (max umax umax-toc))
25701 (setq head-count (+ head-count 1)))
25702 (when in-local-list
25703 ;; Close any local lists before inserting a new header line
25704 (while local-list-num
25705 (org-close-li)
25706 (insert (if (car local-list-num) "</ol>\n" "</ul>"))
25707 (pop local-list-num))
25708 (setq local-list-indent nil
25709 in-local-list nil))
25710 (setq first-heading-pos (or first-heading-pos (point)))
25711 (org-html-level-start level txt umax
25712 (and org-export-with-toc (<= level umax))
25713 head-count)
25714 ;; QUOTES
25715 (when (string-match quote-re line)
25716 (insert "<pre>")
25717 (setq inquote t)))
25719 ((and org-export-with-tables
25720 (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)" line))
25721 (if (not table-open)
25722 ;; New table starts
25723 (setq table-open t table-buffer nil table-orig-buffer nil))
25724 ;; Accumulate lines
25725 (setq table-buffer (cons line table-buffer)
25726 table-orig-buffer (cons origline table-orig-buffer))
25727 (when (or (not lines)
25728 (not (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)"
25729 (car lines))))
25730 (setq table-open nil
25731 table-buffer (nreverse table-buffer)
25732 table-orig-buffer (nreverse table-orig-buffer))
25733 (org-close-par-maybe)
25734 (insert (org-format-table-html table-buffer table-orig-buffer))))
25736 ;; Normal lines
25737 (when (string-match
25738 (cond
25739 ((eq llt t) "^\\([ \t]*\\)\\(\\([-+*] \\)\\|\\([0-9]+[.)]\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
25740 ((= llt ?.) "^\\([ \t]*\\)\\(\\([-+*] \\)\\|\\([0-9]+\\.\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
25741 ((= llt ?\)) "^\\([ \t]*\\)\\(\\([-+*] \\)\\|\\([0-9]+)\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
25742 (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))
25743 line)
25744 (setq ind (org-get-string-indentation line)
25745 start-is-num (match-beginning 4)
25746 starter (if (match-beginning 2)
25747 (substring (match-string 2 line) 0 -1))
25748 line (substring line (match-beginning 5)))
25749 (unless (string-match "[^ \t]" line)
25750 ;; empty line. Pretend indentation is large.
25751 (setq ind (if org-empty-line-terminates-plain-lists
25753 (1+ (or (car local-list-indent) 1)))))
25754 (setq didclose nil)
25755 (while (and in-local-list
25756 (or (and (= ind (car local-list-indent))
25757 (not starter))
25758 (< ind (car local-list-indent))))
25759 (setq didclose t)
25760 (org-close-li)
25761 (insert (if (car local-list-num) "</ol>\n" "</ul>"))
25762 (pop local-list-num) (pop local-list-indent)
25763 (setq in-local-list local-list-indent))
25764 (cond
25765 ((and starter
25766 (or (not in-local-list)
25767 (> ind (car local-list-indent))))
25768 ;; Start new (level of) list
25769 (org-close-par-maybe)
25770 (insert (if start-is-num "<ol>\n<li>\n" "<ul>\n<li>\n"))
25771 (push start-is-num local-list-num)
25772 (push ind local-list-indent)
25773 (setq in-local-list t))
25774 (starter
25775 ;; continue current list
25776 (org-close-li)
25777 (insert "<li>\n"))
25778 (didclose
25779 ;; we did close a list, normal text follows: need <p>
25780 (org-open-par)))
25781 (if (string-match "^[ \t]*\\[\\([X ]\\)\\]" line)
25782 (setq line
25783 (replace-match
25784 (if (equal (match-string 1 line) "X")
25785 "<b>[X]</b>"
25786 "<b>[<span style=\"visibility:hidden;\">X</span>]</b>")
25787 t t line))))
25789 ;; Empty lines start a new paragraph. If hand-formatted lists
25790 ;; are not fully interpreted, lines starting with "-", "+", "*"
25791 ;; also start a new paragraph.
25792 (if (string-match "^ [-+*]-\\|^[ \t]*$" line) (org-open-par))
25794 ;; Is this the start of a footnote?
25795 (when org-export-with-footnotes
25796 (when (string-match "^[ \t]*\\[\\([0-9]+\\)\\]" line)
25797 (org-close-par-maybe)
25798 (let ((n (match-string 1 line)))
25799 (setq line (replace-match
25800 (format "<p class=\"footnote\"><sup><a class=\"footnum\" name=\"fn.%s\" href=\"#fnr.%s\">%s</a></sup>" n n n) t t line)))))
25802 ;; Check if the line break needs to be conserved
25803 (cond
25804 ((string-match "\\\\\\\\[ \t]*$" line)
25805 (setq line (replace-match "<br/>" t t line)))
25806 (org-export-preserve-breaks
25807 (setq line (concat line "<br/>"))))
25809 (insert line "\n")))))
25811 ;; Properly close all local lists and other lists
25812 (when inquote (insert "</pre>\n"))
25813 (when in-local-list
25814 ;; Close any local lists before inserting a new header line
25815 (while local-list-num
25816 (org-close-li)
25817 (insert (if (car local-list-num) "</ol>\n" "</ul>\n"))
25818 (pop local-list-num))
25819 (setq local-list-indent nil
25820 in-local-list nil))
25821 (org-html-level-start 1 nil umax
25822 (and org-export-with-toc (<= level umax))
25823 head-count)
25825 (unless body-only
25826 (when (plist-get opt-plist :auto-postamble)
25827 (insert "<div id=\"postamble\">")
25828 (when (and org-export-author-info author)
25829 (insert "<p class=\"author\"> "
25830 (nth 1 lang-words) ": " author "\n")
25831 (when email
25832 (if (listp (split-string email ",+ *"))
25833 (mapc (lambda(e)
25834 (insert "<a href=\"mailto:" e "\">&lt;"
25835 e "&gt;</a>\n"))
25836 (split-string email ",+ *"))
25837 (insert "<a href=\"mailto:" email "\">&lt;"
25838 email "&gt;</a>\n")))
25839 (insert "</p>\n"))
25840 (when (and date org-export-time-stamp-file)
25841 (insert "<p class=\"date\"> "
25842 (nth 2 lang-words) ": "
25843 date "</p>\n"))
25844 (insert "</div>"))
25846 (if org-export-html-with-timestamp
25847 (insert org-export-html-html-helper-timestamp))
25848 (insert (or (plist-get opt-plist :postamble) ""))
25849 (insert "</body>\n</html>\n"))
25851 (normal-mode)
25852 (if (eq major-mode default-major-mode) (html-mode))
25854 ;; insert the table of contents
25855 (goto-char (point-min))
25856 (when thetoc
25857 (if (or (re-search-forward
25858 "<p>\\s-*\\[TABLE-OF-CONTENTS\\]\\s-*</p>" nil t)
25859 (re-search-forward
25860 "\\[TABLE-OF-CONTENTS\\]" nil t))
25861 (progn
25862 (goto-char (match-beginning 0))
25863 (replace-match ""))
25864 (goto-char first-heading-pos)
25865 (when (looking-at "\\s-*</p>")
25866 (goto-char (match-end 0))
25867 (insert "\n")))
25868 (insert "<div id=\"table-of-contents\">\n")
25869 (mapc 'insert thetoc)
25870 (insert "</div>\n"))
25871 ;; remove empty paragraphs and lists
25872 (goto-char (point-min))
25873 (while (re-search-forward "<p>[ \r\n\t]*</p>" nil t)
25874 (replace-match ""))
25875 (goto-char (point-min))
25876 (while (re-search-forward "<li>[ \r\n\t]*</li>\n?" nil t)
25877 (replace-match ""))
25878 (goto-char (point-min))
25879 (while (re-search-forward "</ul>\\s-*<ul>\n?" nil t)
25880 (replace-match ""))
25881 ;; Convert whitespace place holders
25882 (goto-char (point-min))
25883 (let (beg end n)
25884 (while (setq beg (next-single-property-change (point) 'org-whitespace))
25885 (setq n (get-text-property beg 'org-whitespace)
25886 end (next-single-property-change beg 'org-whitespace))
25887 (goto-char beg)
25888 (delete-region beg end)
25889 (insert (format "<span style=\"visibility:hidden;\">%s</span>"
25890 (make-string n ?x)))))
25892 (or to-buffer (save-buffer))
25893 (goto-char (point-min))
25894 (message "Exporting... done")
25895 (if (eq to-buffer 'string)
25896 (prog1 (buffer-substring (point-min) (point-max))
25897 (kill-buffer (current-buffer)))
25898 (current-buffer)))))
25900 (defvar org-table-colgroup-info nil)
25901 (defun org-format-table-ascii (lines)
25902 "Format a table for ascii export."
25903 (if (stringp lines)
25904 (setq lines (org-split-string lines "\n")))
25905 (if (not (string-match "^[ \t]*|" (car lines)))
25906 ;; Table made by table.el - test for spanning
25907 lines
25909 ;; A normal org table
25910 ;; Get rid of hlines at beginning and end
25911 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
25912 (setq lines (nreverse lines))
25913 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
25914 (setq lines (nreverse lines))
25915 (when org-export-table-remove-special-lines
25916 ;; Check if the table has a marking column. If yes remove the
25917 ;; column and the special lines
25918 (setq lines (org-table-clean-before-export lines)))
25919 ;; Get rid of the vertical lines except for grouping
25920 (let ((vl (org-colgroup-info-to-vline-list org-table-colgroup-info))
25921 rtn line vl1 start)
25922 (while (setq line (pop lines))
25923 (if (string-match org-table-hline-regexp line)
25924 (and (string-match "|\\(.*\\)|" line)
25925 (setq line (replace-match " \\1" t nil line)))
25926 (setq start 0 vl1 vl)
25927 (while (string-match "|" line start)
25928 (setq start (match-end 0))
25929 (or (pop vl1) (setq line (replace-match " " t t line)))))
25930 (push line rtn))
25931 (nreverse rtn))))
25933 (defun org-colgroup-info-to-vline-list (info)
25934 (let (vl new last)
25935 (while info
25936 (setq last new new (pop info))
25937 (if (or (memq last '(:end :startend))
25938 (memq new '(:start :startend)))
25939 (push t vl)
25940 (push nil vl)))
25941 (setq vl (nreverse vl))
25942 (and vl (setcar vl nil))
25943 vl))
25945 (defun org-format-table-html (lines olines)
25946 "Find out which HTML converter to use and return the HTML code."
25947 (if (stringp lines)
25948 (setq lines (org-split-string lines "\n")))
25949 (if (string-match "^[ \t]*|" (car lines))
25950 ;; A normal org table
25951 (org-format-org-table-html lines)
25952 ;; Table made by table.el - test for spanning
25953 (let* ((hlines (delq nil (mapcar
25954 (lambda (x)
25955 (if (string-match "^[ \t]*\\+-" x) x
25956 nil))
25957 lines)))
25958 (first (car hlines))
25959 (ll (and (string-match "\\S-+" first)
25960 (match-string 0 first)))
25961 (re (concat "^[ \t]*" (regexp-quote ll)))
25962 (spanning (delq nil (mapcar (lambda (x) (not (string-match re x)))
25963 hlines))))
25964 (if (and (not spanning)
25965 (not org-export-prefer-native-exporter-for-tables))
25966 ;; We can use my own converter with HTML conversions
25967 (org-format-table-table-html lines)
25968 ;; Need to use the code generator in table.el, with the original text.
25969 (org-format-table-table-html-using-table-generate-source olines)))))
25971 (defun org-format-org-table-html (lines &optional splice)
25972 "Format a table into HTML."
25973 ;; Get rid of hlines at beginning and end
25974 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
25975 (setq lines (nreverse lines))
25976 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
25977 (setq lines (nreverse lines))
25978 (when org-export-table-remove-special-lines
25979 ;; Check if the table has a marking column. If yes remove the
25980 ;; column and the special lines
25981 (setq lines (org-table-clean-before-export lines)))
25983 (let ((head (and org-export-highlight-first-table-line
25984 (delq nil (mapcar
25985 (lambda (x) (string-match "^[ \t]*|-" x))
25986 (cdr lines)))))
25987 (nlines 0) fnum i
25988 tbopen line fields html gr colgropen)
25989 (if splice (setq head nil))
25990 (unless splice (push (if head "<thead>" "<tbody>") html))
25991 (setq tbopen t)
25992 (while (setq line (pop lines))
25993 (catch 'next-line
25994 (if (string-match "^[ \t]*|-" line)
25995 (progn
25996 (unless splice
25997 (push (if head "</thead>" "</tbody>") html)
25998 (if lines (push "<tbody>" html) (setq tbopen nil)))
25999 (setq head nil) ;; head ends here, first time around
26000 ;; ignore this line
26001 (throw 'next-line t)))
26002 ;; Break the line into fields
26003 (setq fields (org-split-string line "[ \t]*|[ \t]*"))
26004 (unless fnum (setq fnum (make-vector (length fields) 0)))
26005 (setq nlines (1+ nlines) i -1)
26006 (push (concat "<tr>"
26007 (mapconcat
26008 (lambda (x)
26009 (setq i (1+ i))
26010 (if (and (< i nlines)
26011 (string-match org-table-number-regexp x))
26012 (incf (aref fnum i)))
26013 (if head
26014 (concat (car org-export-table-header-tags) x
26015 (cdr org-export-table-header-tags))
26016 (concat (car org-export-table-data-tags) x
26017 (cdr org-export-table-data-tags))))
26018 fields "")
26019 "</tr>")
26020 html)))
26021 (unless splice (if tbopen (push "</tbody>" html)))
26022 (unless splice (push "</table>\n" html))
26023 (setq html (nreverse html))
26024 (unless splice
26025 ;; Put in col tags with the alignment (unfortuntely often ignored...)
26026 (push (mapconcat
26027 (lambda (x)
26028 (setq gr (pop org-table-colgroup-info))
26029 (format "%s<col align=\"%s\"></col>%s"
26030 (if (memq gr '(:start :startend))
26031 (prog1
26032 (if colgropen "</colgroup>\n<colgroup>" "<colgroup>")
26033 (setq colgropen t))
26035 (if (> (/ (float x) nlines) org-table-number-fraction)
26036 "right" "left")
26037 (if (memq gr '(:end :startend))
26038 (progn (setq colgropen nil) "</colgroup>")
26039 "")))
26040 fnum "")
26041 html)
26042 (if colgropen (setq html (cons (car html) (cons "</colgroup>" (cdr html)))))
26043 (push html-table-tag html))
26044 (concat (mapconcat 'identity html "\n") "\n")))
26046 (defun org-table-clean-before-export (lines)
26047 "Check if the table has a marking column.
26048 If yes remove the column and the special lines."
26049 (setq org-table-colgroup-info nil)
26050 (if (memq nil
26051 (mapcar
26052 (lambda (x) (or (string-match "^[ \t]*|-" x)
26053 (string-match "^[ \t]*| *\\([#!$*_^ /]\\) *|" x)))
26054 lines))
26055 (progn
26056 (setq org-table-clean-did-remove-column nil)
26057 (delq nil
26058 (mapcar
26059 (lambda (x)
26060 (cond
26061 ((string-match "^[ \t]*| */ *|" x)
26062 (setq org-table-colgroup-info
26063 (mapcar (lambda (x)
26064 (cond ((member x '("<" "&lt;")) :start)
26065 ((member x '(">" "&gt;")) :end)
26066 ((member x '("<>" "&lt;&gt;")) :startend)
26067 (t nil)))
26068 (org-split-string x "[ \t]*|[ \t]*")))
26069 nil)
26070 (t x)))
26071 lines)))
26072 (setq org-table-clean-did-remove-column t)
26073 (delq nil
26074 (mapcar
26075 (lambda (x)
26076 (cond
26077 ((string-match "^[ \t]*| */ *|" x)
26078 (setq org-table-colgroup-info
26079 (mapcar (lambda (x)
26080 (cond ((member x '("<" "&lt;")) :start)
26081 ((member x '(">" "&gt;")) :end)
26082 ((member x '("<>" "&lt;&gt;")) :startend)
26083 (t nil)))
26084 (cdr (org-split-string x "[ \t]*|[ \t]*"))))
26085 nil)
26086 ((string-match "^[ \t]*| *[!_^/] *|" x)
26087 nil) ; ignore this line
26088 ((or (string-match "^\\([ \t]*\\)|-+\\+" x)
26089 (string-match "^\\([ \t]*\\)|[^|]*|" x))
26090 ;; remove the first column
26091 (replace-match "\\1|" t nil x))))
26092 lines))))
26094 (defun org-format-table-table-html (lines)
26095 "Format a table generated by table.el into HTML.
26096 This conversion does *not* use `table-generate-source' from table.el.
26097 This has the advantage that Org-mode's HTML conversions can be used.
26098 But it has the disadvantage, that no cell- or row-spanning is allowed."
26099 (let (line field-buffer
26100 (head org-export-highlight-first-table-line)
26101 fields html empty)
26102 (setq html (concat html-table-tag "\n"))
26103 (while (setq line (pop lines))
26104 (setq empty "&nbsp;")
26105 (catch 'next-line
26106 (if (string-match "^[ \t]*\\+-" line)
26107 (progn
26108 (if field-buffer
26109 (progn
26110 (setq
26111 html
26112 (concat
26113 html
26114 "<tr>"
26115 (mapconcat
26116 (lambda (x)
26117 (if (equal x "") (setq x empty))
26118 (if head
26119 (concat (car org-export-table-header-tags) x
26120 (cdr org-export-table-header-tags))
26121 (concat (car org-export-table-data-tags) x
26122 (cdr org-export-table-data-tags))))
26123 field-buffer "\n")
26124 "</tr>\n"))
26125 (setq head nil)
26126 (setq field-buffer nil)))
26127 ;; Ignore this line
26128 (throw 'next-line t)))
26129 ;; Break the line into fields and store the fields
26130 (setq fields (org-split-string line "[ \t]*|[ \t]*"))
26131 (if field-buffer
26132 (setq field-buffer (mapcar
26133 (lambda (x)
26134 (concat x "<br/>" (pop fields)))
26135 field-buffer))
26136 (setq field-buffer fields))))
26137 (setq html (concat html "</table>\n"))
26138 html))
26140 (defun org-format-table-table-html-using-table-generate-source (lines)
26141 "Format a table into html, using `table-generate-source' from table.el.
26142 This has the advantage that cell- or row-spanning is allowed.
26143 But it has the disadvantage, that Org-mode's HTML conversions cannot be used."
26144 (require 'table)
26145 (with-current-buffer (get-buffer-create " org-tmp1 ")
26146 (erase-buffer)
26147 (insert (mapconcat 'identity lines "\n"))
26148 (goto-char (point-min))
26149 (if (not (re-search-forward "|[^+]" nil t))
26150 (error "Error processing table"))
26151 (table-recognize-table)
26152 (with-current-buffer (get-buffer-create " org-tmp2 ") (erase-buffer))
26153 (table-generate-source 'html " org-tmp2 ")
26154 (set-buffer " org-tmp2 ")
26155 (buffer-substring (point-min) (point-max))))
26157 (defun org-html-handle-time-stamps (s)
26158 "Format time stamps in string S, or remove them."
26159 (catch 'exit
26160 (let (r b)
26161 (while (string-match org-maybe-keyword-time-regexp s)
26162 (if (and (match-end 1) (equal (match-string 1 s) org-clock-string))
26163 ;; never export CLOCK
26164 (throw 'exit ""))
26165 (or b (setq b (substring s 0 (match-beginning 0))))
26166 (if (not org-export-with-timestamps)
26167 (setq r (concat r (substring s 0 (match-beginning 0)))
26168 s (substring s (match-end 0)))
26169 (setq r (concat
26170 r (substring s 0 (match-beginning 0))
26171 (if (match-end 1)
26172 (format "@<span class=\"timestamp-kwd\">%s @</span>"
26173 (match-string 1 s)))
26174 (format " @<span class=\"timestamp\">%s@</span>"
26175 (substring
26176 (org-translate-time (match-string 3 s)) 1 -1)))
26177 s (substring s (match-end 0)))))
26178 ;; Line break if line started and ended with time stamp stuff
26179 (if (not r)
26181 (setq r (concat r s))
26182 (unless (string-match "\\S-" (concat b s))
26183 (setq r (concat r "@<br/>")))
26184 r))))
26186 (defun org-html-protect (s)
26187 ;; convert & to &amp;, < to &lt; and > to &gt;
26188 (let ((start 0))
26189 (while (string-match "&" s start)
26190 (setq s (replace-match "&amp;" t t s)
26191 start (1+ (match-beginning 0))))
26192 (while (string-match "<" s)
26193 (setq s (replace-match "&lt;" t t s)))
26194 (while (string-match ">" s)
26195 (setq s (replace-match "&gt;" t t s))))
26198 (defun org-export-cleanup-toc-line (s)
26199 "Remove tags and time staps from lines going into the toc."
26200 (when (memq org-export-with-tags '(not-in-toc nil))
26201 (if (string-match (org-re " +:[[:alnum:]_@:]+: *$") s)
26202 (setq s (replace-match "" t t s))))
26203 (when org-export-remove-timestamps-from-toc
26204 (while (string-match org-maybe-keyword-time-regexp s)
26205 (setq s (replace-match "" t t s))))
26206 (while (string-match org-bracket-link-regexp s)
26207 (setq s (replace-match (match-string (if (match-end 3) 3 1) s)
26208 t t s)))
26211 (defun org-html-expand (string)
26212 "Prepare STRING for HTML export. Applies all active conversions.
26213 If there are links in the string, don't modify these."
26214 (let* ((re (concat org-bracket-link-regexp "\\|"
26215 (org-re "[ \t]+\\(:[[:alnum:]_@:]+:\\)[ \t]*$")))
26216 m s l res)
26217 (while (setq m (string-match re string))
26218 (setq s (substring string 0 m)
26219 l (match-string 0 string)
26220 string (substring string (match-end 0)))
26221 (push (org-html-do-expand s) res)
26222 (push l res))
26223 (push (org-html-do-expand string) res)
26224 (apply 'concat (nreverse res))))
26226 (defun org-html-do-expand (s)
26227 "Apply all active conversions to translate special ASCII to HTML."
26228 (setq s (org-html-protect s))
26229 (if org-export-html-expand
26230 (let ((start 0))
26231 (while (string-match "@&lt;\\([^&]*\\)&gt;" s)
26232 (setq s (replace-match "<\\1>" t nil s)))))
26233 (if org-export-with-emphasize
26234 (setq s (org-export-html-convert-emphasize s)))
26235 (if org-export-with-special-strings
26236 (setq s (org-export-html-convert-special-strings s)))
26237 (if org-export-with-sub-superscripts
26238 (setq s (org-export-html-convert-sub-super s)))
26239 (if org-export-with-TeX-macros
26240 (let ((start 0) wd ass)
26241 (while (setq start (string-match "\\\\\\([a-zA-Z]+\\)" s start))
26242 (if (get-text-property (match-beginning 0) 'org-protected s)
26243 (setq start (match-end 0))
26244 (setq wd (match-string 1 s))
26245 (if (setq ass (assoc wd org-html-entities))
26246 (setq s (replace-match (or (cdr ass)
26247 (concat "&" (car ass) ";"))
26248 t t s))
26249 (setq start (+ start (length wd))))))))
26252 (defun org-create-multibrace-regexp (left right n)
26253 "Create a regular expression which will match a balanced sexp.
26254 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
26255 as single character strings.
26256 The regexp returned will match the entire expression including the
26257 delimiters. It will also define a single group which contains the
26258 match except for the outermost delimiters. The maximum depth of
26259 stacked delimiters is N. Escaping delimiters is not possible."
26260 (let* ((nothing (concat "[^" "\\" left "\\" right "]*?"))
26261 (or "\\|")
26262 (re nothing)
26263 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
26264 (while (> n 1)
26265 (setq n (1- n)
26266 re (concat re or next)
26267 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
26268 (concat left "\\(" re "\\)" right)))
26270 (defvar org-match-substring-regexp
26271 (concat
26272 "\\([^\\]\\)\\([_^]\\)\\("
26273 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
26274 "\\|"
26275 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
26276 "\\|"
26277 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
26278 "The regular expression matching a sub- or superscript.")
26280 (defvar org-match-substring-with-braces-regexp
26281 (concat
26282 "\\([^\\]\\)\\([_^]\\)\\("
26283 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
26284 "\\)")
26285 "The regular expression matching a sub- or superscript, forcing braces.")
26287 (defconst org-export-html-special-string-regexps
26288 '(("\\\\-" . "&shy;")
26289 ("---\\([^-]\\)" . "&mdash;\\1")
26290 ("--\\([^-]\\)" . "&ndash;\\1")
26291 ("\\.\\.\\." . "&hellip;"))
26292 "Regular expressions for special string conversion.")
26294 (defun org-export-html-convert-special-strings (string)
26295 "Convert special characters in STRING to HTML."
26296 (let ((all org-export-html-special-string-regexps)
26297 e a re rpl start)
26298 (while (setq a (pop all))
26299 (setq re (car a) rpl (cdr a) start 0)
26300 (while (string-match re string start)
26301 (if (get-text-property (match-beginning 0) 'org-protected string)
26302 (setq start (match-end 0))
26303 (setq string (replace-match rpl t nil string)))))
26304 string))
26306 (defun org-export-html-convert-sub-super (string)
26307 "Convert sub- and superscripts in STRING to HTML."
26308 (let (key c (s 0) (requireb (eq org-export-with-sub-superscripts '{})))
26309 (while (string-match org-match-substring-regexp string s)
26310 (cond
26311 ((and requireb (match-end 8)) (setq s (match-end 2)))
26312 ((get-text-property (match-beginning 2) 'org-protected string)
26313 (setq s (match-end 2)))
26315 (setq s (match-end 1)
26316 key (if (string= (match-string 2 string) "_") "sub" "sup")
26317 c (or (match-string 8 string)
26318 (match-string 6 string)
26319 (match-string 5 string))
26320 string (replace-match
26321 (concat (match-string 1 string)
26322 "<" key ">" c "</" key ">")
26323 t t string)))))
26324 (while (string-match "\\\\\\([_^]\\)" string)
26325 (setq string (replace-match (match-string 1 string) t t string)))
26326 string))
26328 (defun org-export-html-convert-emphasize (string)
26329 "Apply emphasis."
26330 (let ((s 0) rpl)
26331 (while (string-match org-emph-re string s)
26332 (if (not (equal
26333 (substring string (match-beginning 3) (1+ (match-beginning 3)))
26334 (substring string (match-beginning 4) (1+ (match-beginning 4)))))
26335 (setq s (match-beginning 0)
26337 (concat
26338 (match-string 1 string)
26339 (nth 2 (assoc (match-string 3 string) org-emphasis-alist))
26340 (match-string 4 string)
26341 (nth 3 (assoc (match-string 3 string)
26342 org-emphasis-alist))
26343 (match-string 5 string))
26344 string (replace-match rpl t t string)
26345 s (+ s (- (length rpl) 2)))
26346 (setq s (1+ s))))
26347 string))
26349 (defvar org-par-open nil)
26350 (defun org-open-par ()
26351 "Insert <p>, but first close previous paragraph if any."
26352 (org-close-par-maybe)
26353 (insert "\n<p>")
26354 (setq org-par-open t))
26355 (defun org-close-par-maybe ()
26356 "Close paragraph if there is one open."
26357 (when org-par-open
26358 (insert "</p>")
26359 (setq org-par-open nil)))
26360 (defun org-close-li ()
26361 "Close <li> if necessary."
26362 (org-close-par-maybe)
26363 (insert "</li>\n"))
26365 (defvar body-only) ; dynamically scoped into this.
26366 (defun org-html-level-start (level title umax with-toc head-count)
26367 "Insert a new level in HTML export.
26368 When TITLE is nil, just close all open levels."
26369 (org-close-par-maybe)
26370 (let ((l org-level-max))
26371 (while (>= l level)
26372 (if (aref org-levels-open (1- l))
26373 (progn
26374 (org-html-level-close l umax)
26375 (aset org-levels-open (1- l) nil)))
26376 (setq l (1- l)))
26377 (when title
26378 ;; If title is nil, this means this function is called to close
26379 ;; all levels, so the rest is done only if title is given
26380 (when (string-match (org-re "\\(:[[:alnum:]_@:]+:\\)[ \t]*$") title)
26381 (setq title (replace-match
26382 (if org-export-with-tags
26383 (save-match-data
26384 (concat
26385 "&nbsp;&nbsp;&nbsp;<span class=\"tag\">"
26386 (mapconcat 'identity (org-split-string
26387 (match-string 1 title) ":")
26388 "&nbsp;")
26389 "</span>"))
26391 t t title)))
26392 (if (> level umax)
26393 (progn
26394 (if (aref org-levels-open (1- level))
26395 (progn
26396 (org-close-li)
26397 (insert "<li>" title "<br/>\n"))
26398 (aset org-levels-open (1- level) t)
26399 (org-close-par-maybe)
26400 (insert "<ul>\n<li>" title "<br/>\n")))
26401 (aset org-levels-open (1- level) t)
26402 (if (and org-export-with-section-numbers (not body-only))
26403 (setq title (concat (org-section-number level) " " title)))
26404 (setq level (+ level org-export-html-toplevel-hlevel -1))
26405 (if with-toc
26406 (insert (format "\n<div class=\"outline-%d\">\n<h%d id=\"sec-%d\">%s</h%d>\n"
26407 level level head-count title level))
26408 (insert (format "\n<div class=\"outline-%d\">\n<h%d>%s</h%d>\n" level level title level)))
26409 (org-open-par)))))
26411 (defun org-html-level-close (level max-outline-level)
26412 "Terminate one level in HTML export."
26413 (if (<= level max-outline-level)
26414 (insert "</div>\n")
26415 (org-close-li)
26416 (insert "</ul>\n")))
26418 ;;; iCalendar export
26420 ;;;###autoload
26421 (defun org-export-icalendar-this-file ()
26422 "Export current file as an iCalendar file.
26423 The iCalendar file will be located in the same directory as the Org-mode
26424 file, but with extension `.ics'."
26425 (interactive)
26426 (org-export-icalendar nil buffer-file-name))
26428 ;;;###autoload
26429 (defun org-export-icalendar-all-agenda-files ()
26430 "Export all files in `org-agenda-files' to iCalendar .ics files.
26431 Each iCalendar file will be located in the same directory as the Org-mode
26432 file, but with extension `.ics'."
26433 (interactive)
26434 (apply 'org-export-icalendar nil (org-agenda-files t)))
26436 ;;;###autoload
26437 (defun org-export-icalendar-combine-agenda-files ()
26438 "Export all files in `org-agenda-files' to a single combined iCalendar file.
26439 The file is stored under the name `org-combined-agenda-icalendar-file'."
26440 (interactive)
26441 (apply 'org-export-icalendar t (org-agenda-files t)))
26443 (defun org-export-icalendar (combine &rest files)
26444 "Create iCalendar files for all elements of FILES.
26445 If COMBINE is non-nil, combine all calendar entries into a single large
26446 file and store it under the name `org-combined-agenda-icalendar-file'."
26447 (save-excursion
26448 (org-prepare-agenda-buffers files)
26449 (let* ((dir (org-export-directory
26450 :ical (list :publishing-directory
26451 org-export-publishing-directory)))
26452 file ical-file ical-buffer category started org-agenda-new-buffers)
26454 (and (get-buffer "*ical-tmp*") (kill-buffer "*ical-tmp*"))
26455 (when combine
26456 (setq ical-file
26457 (if (file-name-absolute-p org-combined-agenda-icalendar-file)
26458 org-combined-agenda-icalendar-file
26459 (expand-file-name org-combined-agenda-icalendar-file dir))
26460 ical-buffer (org-get-agenda-file-buffer ical-file))
26461 (set-buffer ical-buffer) (erase-buffer))
26462 (while (setq file (pop files))
26463 (catch 'nextfile
26464 (org-check-agenda-file file)
26465 (set-buffer (org-get-agenda-file-buffer file))
26466 (unless combine
26467 (setq ical-file (concat (file-name-as-directory dir)
26468 (file-name-sans-extension
26469 (file-name-nondirectory buffer-file-name))
26470 ".ics"))
26471 (setq ical-buffer (org-get-agenda-file-buffer ical-file))
26472 (with-current-buffer ical-buffer (erase-buffer)))
26473 (setq category (or org-category
26474 (file-name-sans-extension
26475 (file-name-nondirectory buffer-file-name))))
26476 (if (symbolp category) (setq category (symbol-name category)))
26477 (let ((standard-output ical-buffer))
26478 (if combine
26479 (and (not started) (setq started t)
26480 (org-start-icalendar-file org-icalendar-combined-name))
26481 (org-start-icalendar-file category))
26482 (org-print-icalendar-entries combine)
26483 (when (or (and combine (not files)) (not combine))
26484 (org-finish-icalendar-file)
26485 (set-buffer ical-buffer)
26486 (save-buffer)
26487 (run-hooks 'org-after-save-iCalendar-file-hook)))))
26488 (org-release-buffers org-agenda-new-buffers))))
26490 (defvar org-after-save-iCalendar-file-hook nil
26491 "Hook run after an iCalendar file has been saved.
26492 The iCalendar buffer is still current when this hook is run.
26493 A good way to use this is to tell a desktop calenndar application to re-read
26494 the iCalendar file.")
26496 (defun org-print-icalendar-entries (&optional combine)
26497 "Print iCalendar entries for the current Org-mode file to `standard-output'.
26498 When COMBINE is non nil, add the category to each line."
26499 (let ((re1 (concat org-ts-regexp "\\|<%%([^>\n]+>"))
26500 (re2 (concat "--?-?\\(" org-ts-regexp "\\)"))
26501 (dts (org-ical-ts-to-string
26502 (format-time-string (cdr org-time-stamp-formats) (current-time))
26503 "DTSTART"))
26504 hd ts ts2 state status (inc t) pos b sexp rrule
26505 scheduledp deadlinep tmp pri category entry location summary desc
26506 (sexp-buffer (get-buffer-create "*ical-tmp*")))
26507 (org-refresh-category-properties)
26508 (save-excursion
26509 (goto-char (point-min))
26510 (while (re-search-forward re1 nil t)
26511 (catch :skip
26512 (org-agenda-skip)
26513 (setq pos (match-beginning 0)
26514 ts (match-string 0)
26515 inc t
26516 hd (org-get-heading)
26517 summary (org-icalendar-cleanup-string
26518 (org-entry-get nil "SUMMARY"))
26519 desc (org-icalendar-cleanup-string
26520 (or (org-entry-get nil "DESCRIPTION")
26521 (and org-icalendar-include-body (org-get-entry)))
26522 t org-icalendar-include-body)
26523 location (org-icalendar-cleanup-string
26524 (org-entry-get nil "LOCATION"))
26525 category (org-get-category))
26526 (if (looking-at re2)
26527 (progn
26528 (goto-char (match-end 0))
26529 (setq ts2 (match-string 1) inc nil))
26530 (setq tmp (buffer-substring (max (point-min)
26531 (- pos org-ds-keyword-length))
26532 pos)
26533 ts2 (if (string-match "[0-9]\\{1,2\\}:[0-9][0-9]-\\([0-9]\\{1,2\\}:[0-9][0-9]\\)" ts)
26534 (progn
26535 (setq inc nil)
26536 (replace-match "\\1" t nil ts))
26538 deadlinep (string-match org-deadline-regexp tmp)
26539 scheduledp (string-match org-scheduled-regexp tmp)
26540 ;; donep (org-entry-is-done-p)
26542 (if (or (string-match org-tr-regexp hd)
26543 (string-match org-ts-regexp hd))
26544 (setq hd (replace-match "" t t hd)))
26545 (if (string-match "\\+\\([0-9]+\\)\\([dwmy]\\)>" ts)
26546 (setq rrule
26547 (concat "\nRRULE:FREQ="
26548 (cdr (assoc
26549 (match-string 2 ts)
26550 '(("d" . "DAILY")("w" . "WEEKLY")
26551 ("m" . "MONTHLY")("y" . "YEARLY"))))
26552 ";INTERVAL=" (match-string 1 ts)))
26553 (setq rrule ""))
26554 (setq summary (or summary hd))
26555 (if (string-match org-bracket-link-regexp summary)
26556 (setq summary
26557 (replace-match (if (match-end 3)
26558 (match-string 3 summary)
26559 (match-string 1 summary))
26560 t t summary)))
26561 (if deadlinep (setq summary (concat "DL: " summary)))
26562 (if scheduledp (setq summary (concat "S: " summary)))
26563 (if (string-match "\\`<%%" ts)
26564 (with-current-buffer sexp-buffer
26565 (insert (substring ts 1 -1) " " summary "\n"))
26566 (princ (format "BEGIN:VEVENT
26568 %s%s
26569 SUMMARY:%s%s%s
26570 CATEGORIES:%s
26571 END:VEVENT\n"
26572 (org-ical-ts-to-string ts "DTSTART")
26573 (org-ical-ts-to-string ts2 "DTEND" inc)
26574 rrule summary
26575 (if (and desc (string-match "\\S-" desc))
26576 (concat "\nDESCRIPTION: " desc) "")
26577 (if (and location (string-match "\\S-" location))
26578 (concat "\nLOCATION: " location) "")
26579 category)))))
26581 (when (and org-icalendar-include-sexps
26582 (condition-case nil (require 'icalendar) (error nil))
26583 (fboundp 'icalendar-export-region))
26584 ;; Get all the literal sexps
26585 (goto-char (point-min))
26586 (while (re-search-forward "^&?%%(" nil t)
26587 (catch :skip
26588 (org-agenda-skip)
26589 (setq b (match-beginning 0))
26590 (goto-char (1- (match-end 0)))
26591 (forward-sexp 1)
26592 (end-of-line 1)
26593 (setq sexp (buffer-substring b (point)))
26594 (with-current-buffer sexp-buffer
26595 (insert sexp "\n"))
26596 (princ (org-diary-to-ical-string sexp-buffer)))))
26598 (when org-icalendar-include-todo
26599 (goto-char (point-min))
26600 (while (re-search-forward org-todo-line-regexp nil t)
26601 (catch :skip
26602 (org-agenda-skip)
26603 (setq state (match-string 2))
26604 (setq status (if (member state org-done-keywords)
26605 "COMPLETED" "NEEDS-ACTION"))
26606 (when (and state
26607 (or (not (member state org-done-keywords))
26608 (eq org-icalendar-include-todo 'all))
26609 (not (member org-archive-tag (org-get-tags-at)))
26611 (setq hd (match-string 3)
26612 summary (org-icalendar-cleanup-string
26613 (org-entry-get nil "SUMMARY"))
26614 desc (org-icalendar-cleanup-string
26615 (or (org-entry-get nil "DESCRIPTION")
26616 (and org-icalendar-include-body (org-get-entry)))
26617 t org-icalendar-include-body)
26618 location (org-icalendar-cleanup-string
26619 (org-entry-get nil "LOCATION")))
26620 (if (string-match org-bracket-link-regexp hd)
26621 (setq hd (replace-match (if (match-end 3) (match-string 3 hd)
26622 (match-string 1 hd))
26623 t t hd)))
26624 (if (string-match org-priority-regexp hd)
26625 (setq pri (string-to-char (match-string 2 hd))
26626 hd (concat (substring hd 0 (match-beginning 1))
26627 (substring hd (match-end 1))))
26628 (setq pri org-default-priority))
26629 (setq pri (floor (1+ (* 8. (/ (float (- org-lowest-priority pri))
26630 (- org-lowest-priority org-highest-priority))))))
26632 (princ (format "BEGIN:VTODO
26634 SUMMARY:%s%s%s
26635 CATEGORIES:%s
26636 SEQUENCE:1
26637 PRIORITY:%d
26638 STATUS:%s
26639 END:VTODO\n"
26641 (or summary hd)
26642 (if (and location (string-match "\\S-" location))
26643 (concat "\nLOCATION: " location) "")
26644 (if (and desc (string-match "\\S-" desc))
26645 (concat "\nDESCRIPTION: " desc) "")
26646 category pri status)))))))))
26648 (defun org-icalendar-cleanup-string (s &optional is-body maxlength)
26649 "Take out stuff and quote what needs to be quoted.
26650 When IS-BODY is non-nil, assume that this is the body of an item, clean up
26651 whitespace, newlines, drawers, and timestamps, and cut it down to MAXLENGTH
26652 characters."
26653 (if (not s)
26655 (when is-body
26656 (let ((re (concat "\\(" org-drawer-regexp "\\)[^\000]*?:END:.*\n?"))
26657 (re2 (concat "^[ \t]*" org-keyword-time-regexp ".*\n?")))
26658 (while (string-match re s) (setq s (replace-match "" t t s)))
26659 (while (string-match re2 s) (setq s (replace-match "" t t s)))))
26660 (let ((start 0))
26661 (while (string-match "\\([,;\\]\\)" s start)
26662 (setq start (+ (match-beginning 0) 2)
26663 s (replace-match "\\\\\\1" nil nil s))))
26664 (when is-body
26665 (while (string-match "[ \t]*\n[ \t]*" s)
26666 (setq s (replace-match "\\n" t t s))))
26667 (setq s (org-trim s))
26668 (if is-body
26669 (if maxlength
26670 (if (and (numberp maxlength)
26671 (> (length s) maxlength))
26672 (setq s (substring s 0 maxlength)))))
26675 (defun org-get-entry ()
26676 "Clean-up description string."
26677 (save-excursion
26678 (org-back-to-heading t)
26679 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
26681 (defun org-start-icalendar-file (name)
26682 "Start an iCalendar file by inserting the header."
26683 (let ((user user-full-name)
26684 (name (or name "unknown"))
26685 (timezone (cadr (current-time-zone))))
26686 (princ
26687 (format "BEGIN:VCALENDAR
26688 VERSION:2.0
26689 X-WR-CALNAME:%s
26690 PRODID:-//%s//Emacs with Org-mode//EN
26691 X-WR-TIMEZONE:%s
26692 CALSCALE:GREGORIAN\n" name user timezone))))
26694 (defun org-finish-icalendar-file ()
26695 "Finish an iCalendar file by inserting the END statement."
26696 (princ "END:VCALENDAR\n"))
26698 (defun org-ical-ts-to-string (s keyword &optional inc)
26699 "Take a time string S and convert it to iCalendar format.
26700 KEYWORD is added in front, to make a complete line like DTSTART....
26701 When INC is non-nil, increase the hour by two (if time string contains
26702 a time), or the day by one (if it does not contain a time)."
26703 (let ((t1 (org-parse-time-string s 'nodefault))
26704 t2 fmt have-time time)
26705 (if (and (car t1) (nth 1 t1) (nth 2 t1))
26706 (setq t2 t1 have-time t)
26707 (setq t2 (org-parse-time-string s)))
26708 (let ((s (car t2)) (mi (nth 1 t2)) (h (nth 2 t2))
26709 (d (nth 3 t2)) (m (nth 4 t2)) (y (nth 5 t2)))
26710 (when inc
26711 (if have-time
26712 (if org-agenda-default-appointment-duration
26713 (setq mi (+ org-agenda-default-appointment-duration mi))
26714 (setq h (+ 2 h)))
26715 (setq d (1+ d))))
26716 (setq time (encode-time s mi h d m y)))
26717 (setq fmt (if have-time ":%Y%m%dT%H%M%S" ";VALUE=DATE:%Y%m%d"))
26718 (concat keyword (format-time-string fmt time))))
26720 ;;; XOXO export
26722 (defun org-export-as-xoxo-insert-into (buffer &rest output)
26723 (with-current-buffer buffer
26724 (apply 'insert output)))
26725 (put 'org-export-as-xoxo-insert-into 'lisp-indent-function 1)
26727 (defun org-export-as-xoxo (&optional buffer)
26728 "Export the org buffer as XOXO.
26729 The XOXO buffer is named *xoxo-<source buffer name>*"
26730 (interactive (list (current-buffer)))
26731 ;; A quickie abstraction
26733 ;; Output everything as XOXO
26734 (with-current-buffer (get-buffer buffer)
26735 (let* ((pos (point))
26736 (opt-plist (org-combine-plists (org-default-export-plist)
26737 (org-infile-export-plist)))
26738 (filename (concat (file-name-as-directory
26739 (org-export-directory :xoxo opt-plist))
26740 (file-name-sans-extension
26741 (file-name-nondirectory buffer-file-name))
26742 ".html"))
26743 (out (find-file-noselect filename))
26744 (last-level 1)
26745 (hanging-li nil))
26746 (goto-char (point-min)) ;; CD: beginning-of-buffer is not allowed.
26747 ;; Check the output buffer is empty.
26748 (with-current-buffer out (erase-buffer))
26749 ;; Kick off the output
26750 (org-export-as-xoxo-insert-into out "<ol class='xoxo'>\n")
26751 (while (re-search-forward "^\\(\\*+\\)[ \t]+\\(.+\\)" (point-max) 't)
26752 (let* ((hd (match-string-no-properties 1))
26753 (level (length hd))
26754 (text (concat
26755 (match-string-no-properties 2)
26756 (save-excursion
26757 (goto-char (match-end 0))
26758 (let ((str ""))
26759 (catch 'loop
26760 (while 't
26761 (forward-line)
26762 (if (looking-at "^[ \t]\\(.*\\)")
26763 (setq str (concat str (match-string-no-properties 1)))
26764 (throw 'loop str)))))))))
26766 ;; Handle level rendering
26767 (cond
26768 ((> level last-level)
26769 (org-export-as-xoxo-insert-into out "\n<ol>\n"))
26771 ((< level last-level)
26772 (dotimes (- (- last-level level) 1)
26773 (if hanging-li
26774 (org-export-as-xoxo-insert-into out "</li>\n"))
26775 (org-export-as-xoxo-insert-into out "</ol>\n"))
26776 (when hanging-li
26777 (org-export-as-xoxo-insert-into out "</li>\n")
26778 (setq hanging-li nil)))
26780 ((equal level last-level)
26781 (if hanging-li
26782 (org-export-as-xoxo-insert-into out "</li>\n")))
26785 (setq last-level level)
26787 ;; And output the new li
26788 (setq hanging-li 't)
26789 (if (equal ?+ (elt text 0))
26790 (org-export-as-xoxo-insert-into out "<li class='" (substring text 1) "'>")
26791 (org-export-as-xoxo-insert-into out "<li>" text))))
26793 ;; Finally finish off the ol
26794 (dotimes (- last-level 1)
26795 (if hanging-li
26796 (org-export-as-xoxo-insert-into out "</li>\n"))
26797 (org-export-as-xoxo-insert-into out "</ol>\n"))
26799 (goto-char pos)
26800 ;; Finish the buffer off and clean it up.
26801 (switch-to-buffer-other-window out)
26802 (indent-region (point-min) (point-max) nil)
26803 (save-buffer)
26804 (goto-char (point-min))
26808 ;;;; Key bindings
26810 ;; Make `C-c C-x' a prefix key
26811 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
26813 ;; TAB key with modifiers
26814 (org-defkey org-mode-map "\C-i" 'org-cycle)
26815 (org-defkey org-mode-map [(tab)] 'org-cycle)
26816 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
26817 (org-defkey org-mode-map [(meta tab)] 'org-complete)
26818 (org-defkey org-mode-map "\M-\t" 'org-complete)
26819 (org-defkey org-mode-map "\M-\C-i" 'org-complete)
26820 ;; The following line is necessary under Suse GNU/Linux
26821 (unless (featurep 'xemacs)
26822 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
26823 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
26824 (define-key org-mode-map [backtab] 'org-shifttab)
26826 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
26827 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
26828 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
26830 ;; Cursor keys with modifiers
26831 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
26832 (org-defkey org-mode-map [(meta right)] 'org-metaright)
26833 (org-defkey org-mode-map [(meta up)] 'org-metaup)
26834 (org-defkey org-mode-map [(meta down)] 'org-metadown)
26836 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
26837 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
26838 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
26839 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
26841 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
26842 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
26843 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
26844 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
26846 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
26847 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
26849 ;;; Extra keys for tty access.
26850 ;; We only set them when really needed because otherwise the
26851 ;; menus don't show the simple keys
26853 (when (or (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
26854 (not window-system))
26855 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
26856 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
26857 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
26858 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
26859 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
26860 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
26861 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
26862 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
26863 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
26864 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
26865 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
26866 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
26867 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
26868 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
26869 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
26870 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
26871 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
26872 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
26873 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
26874 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
26875 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
26876 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft))
26878 ;; All the other keys
26880 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
26881 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
26882 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree)
26883 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
26884 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
26885 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-toggle-archive-tag)
26886 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
26887 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
26888 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
26889 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
26890 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
26891 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
26892 (org-defkey org-mode-map "\C-c\C-v" 'org-show-todo-tree)
26893 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
26894 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
26895 (org-defkey org-mode-map "\C-c\\" 'org-tags-sparse-tree) ; Minor-mode res.
26896 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
26897 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
26898 (org-defkey org-mode-map [(control return)] 'org-insert-heading-after-current)
26899 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
26900 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
26901 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
26902 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
26903 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
26904 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
26905 (org-defkey org-mode-map "\C-c\C-z" 'org-time-stamp) ; Alternative binding
26906 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
26907 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
26908 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
26909 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
26910 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
26911 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
26912 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
26913 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
26914 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
26915 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
26916 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
26917 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
26918 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
26919 (org-defkey org-mode-map "\C-c^" 'org-sort)
26920 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
26921 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
26922 (org-defkey org-mode-map "\C-c#" 'org-update-checkbox-count)
26923 (org-defkey org-mode-map "\C-m" 'org-return)
26924 (org-defkey org-mode-map "\C-j" 'org-return-indent)
26925 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
26926 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
26927 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
26928 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
26929 (org-defkey org-mode-map "\C-c'" 'org-table-edit-formulas)
26930 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
26931 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
26932 (org-defkey org-mode-map "\C-c*" 'org-table-recalculate)
26933 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
26934 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
26935 (org-defkey org-mode-map "\C-c\C-q" 'org-table-wrap-region)
26936 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
26937 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
26938 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
26939 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
26940 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
26942 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-cut-special)
26943 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
26944 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
26945 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
26947 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
26948 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
26949 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
26950 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
26951 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
26952 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
26953 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
26954 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
26955 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
26956 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
26957 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
26958 (org-defkey org-mode-map "\C-c\C-xr" 'org-insert-columns-dblock)
26960 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
26962 (when (featurep 'xemacs)
26963 (org-defkey org-mode-map 'button3 'popup-mode-menu))
26965 (defsubst org-table-p () (org-at-table-p))
26967 (defun org-self-insert-command (N)
26968 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
26969 If the cursor is in a table looking at whitespace, the whitespace is
26970 overwritten, and the table is not marked as requiring realignment."
26971 (interactive "p")
26972 (if (and (org-table-p)
26973 (progn
26974 ;; check if we blank the field, and if that triggers align
26975 (and org-table-auto-blank-field
26976 (member last-command
26977 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
26978 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
26979 ;; got extra space, this field does not determine column width
26980 (let (org-table-may-need-update) (org-table-blank-field))
26981 ;; no extra space, this field may determine column width
26982 (org-table-blank-field)))
26984 (eq N 1)
26985 (looking-at "[^|\n]* |"))
26986 (let (org-table-may-need-update)
26987 (goto-char (1- (match-end 0)))
26988 (delete-backward-char 1)
26989 (goto-char (match-beginning 0))
26990 (self-insert-command N))
26991 (setq org-table-may-need-update t)
26992 (self-insert-command N)
26993 (org-fix-tags-on-the-fly)))
26995 (defun org-fix-tags-on-the-fly ()
26996 (when (and (equal (char-after (point-at-bol)) ?*)
26997 (org-on-heading-p))
26998 (org-align-tags-here org-tags-column)))
27000 (defun org-delete-backward-char (N)
27001 "Like `delete-backward-char', insert whitespace at field end in tables.
27002 When deleting backwards, in tables this function will insert whitespace in
27003 front of the next \"|\" separator, to keep the table aligned. The table will
27004 still be marked for re-alignment if the field did fill the entire column,
27005 because, in this case the deletion might narrow the column."
27006 (interactive "p")
27007 (if (and (org-table-p)
27008 (eq N 1)
27009 (string-match "|" (buffer-substring (point-at-bol) (point)))
27010 (looking-at ".*?|"))
27011 (let ((pos (point))
27012 (noalign (looking-at "[^|\n\r]* |"))
27013 (c org-table-may-need-update))
27014 (backward-delete-char N)
27015 (skip-chars-forward "^|")
27016 (insert " ")
27017 (goto-char (1- pos))
27018 ;; noalign: if there were two spaces at the end, this field
27019 ;; does not determine the width of the column.
27020 (if noalign (setq org-table-may-need-update c)))
27021 (backward-delete-char N)
27022 (org-fix-tags-on-the-fly)))
27024 (defun org-delete-char (N)
27025 "Like `delete-char', but insert whitespace at field end in tables.
27026 When deleting characters, in tables this function will insert whitespace in
27027 front of the next \"|\" separator, to keep the table aligned. The table will
27028 still be marked for re-alignment if the field did fill the entire column,
27029 because, in this case the deletion might narrow the column."
27030 (interactive "p")
27031 (if (and (org-table-p)
27032 (not (bolp))
27033 (not (= (char-after) ?|))
27034 (eq N 1))
27035 (if (looking-at ".*?|")
27036 (let ((pos (point))
27037 (noalign (looking-at "[^|\n\r]* |"))
27038 (c org-table-may-need-update))
27039 (replace-match (concat
27040 (substring (match-string 0) 1 -1)
27041 " |"))
27042 (goto-char pos)
27043 ;; noalign: if there were two spaces at the end, this field
27044 ;; does not determine the width of the column.
27045 (if noalign (setq org-table-may-need-update c)))
27046 (delete-char N))
27047 (delete-char N)
27048 (org-fix-tags-on-the-fly)))
27050 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
27051 (put 'org-self-insert-command 'delete-selection t)
27052 (put 'orgtbl-self-insert-command 'delete-selection t)
27053 (put 'org-delete-char 'delete-selection 'supersede)
27054 (put 'org-delete-backward-char 'delete-selection 'supersede)
27056 ;; Make `flyspell-mode' delay after some commands
27057 (put 'org-self-insert-command 'flyspell-delayed t)
27058 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
27059 (put 'org-delete-char 'flyspell-delayed t)
27060 (put 'org-delete-backward-char 'flyspell-delayed t)
27062 ;; Make pabbrev-mode expand after org-mode commands
27063 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
27064 (put 'orgybl-self-insert-command 'pabbrev-expand-after-command t)
27066 ;; How to do this: Measure non-white length of current string
27067 ;; If equal to column width, we should realign.
27069 (defun org-remap (map &rest commands)
27070 "In MAP, remap the functions given in COMMANDS.
27071 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
27072 (let (new old)
27073 (while commands
27074 (setq old (pop commands) new (pop commands))
27075 (if (fboundp 'command-remapping)
27076 (org-defkey map (vector 'remap old) new)
27077 (substitute-key-definition old new map global-map)))))
27079 (when (eq org-enable-table-editor 'optimized)
27080 ;; If the user wants maximum table support, we need to hijack
27081 ;; some standard editing functions
27082 (org-remap org-mode-map
27083 'self-insert-command 'org-self-insert-command
27084 'delete-char 'org-delete-char
27085 'delete-backward-char 'org-delete-backward-char)
27086 (org-defkey org-mode-map "|" 'org-force-self-insert))
27088 (defun org-shiftcursor-error ()
27089 "Throw an error because Shift-Cursor command was applied in wrong context."
27090 (error "This command is active in special context like tables, headlines or timestamps"))
27092 (defun org-shifttab (&optional arg)
27093 "Global visibility cycling or move to previous table field.
27094 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
27095 on context.
27096 See the individual commands for more information."
27097 (interactive "P")
27098 (cond
27099 ((org-at-table-p) (call-interactively 'org-table-previous-field))
27100 (arg (message "Content view to level: ")
27101 (org-content (prefix-numeric-value arg))
27102 (setq org-cycle-global-status 'overview))
27103 (t (call-interactively 'org-global-cycle))))
27105 (defun org-shiftmetaleft ()
27106 "Promote subtree or delete table column.
27107 Calls `org-promote-subtree', `org-outdent-item',
27108 or `org-table-delete-column', depending on context.
27109 See the individual commands for more information."
27110 (interactive)
27111 (cond
27112 ((org-at-table-p) (call-interactively 'org-table-delete-column))
27113 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
27114 ((org-at-item-p) (call-interactively 'org-outdent-item))
27115 (t (org-shiftcursor-error))))
27117 (defun org-shiftmetaright ()
27118 "Demote subtree or insert table column.
27119 Calls `org-demote-subtree', `org-indent-item',
27120 or `org-table-insert-column', depending on context.
27121 See the individual commands for more information."
27122 (interactive)
27123 (cond
27124 ((org-at-table-p) (call-interactively 'org-table-insert-column))
27125 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
27126 ((org-at-item-p) (call-interactively 'org-indent-item))
27127 (t (org-shiftcursor-error))))
27129 (defun org-shiftmetaup (&optional arg)
27130 "Move subtree up or kill table row.
27131 Calls `org-move-subtree-up' or `org-table-kill-row' or
27132 `org-move-item-up' depending on context. See the individual commands
27133 for more information."
27134 (interactive "P")
27135 (cond
27136 ((org-at-table-p) (call-interactively 'org-table-kill-row))
27137 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
27138 ((org-at-item-p) (call-interactively 'org-move-item-up))
27139 (t (org-shiftcursor-error))))
27140 (defun org-shiftmetadown (&optional arg)
27141 "Move subtree down or insert table row.
27142 Calls `org-move-subtree-down' or `org-table-insert-row' or
27143 `org-move-item-down', depending on context. See the individual
27144 commands for more information."
27145 (interactive "P")
27146 (cond
27147 ((org-at-table-p) (call-interactively 'org-table-insert-row))
27148 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
27149 ((org-at-item-p) (call-interactively 'org-move-item-down))
27150 (t (org-shiftcursor-error))))
27152 (defun org-metaleft (&optional arg)
27153 "Promote heading or move table column to left.
27154 Calls `org-do-promote' or `org-table-move-column', depending on context.
27155 With no specific context, calls the Emacs default `backward-word'.
27156 See the individual commands for more information."
27157 (interactive "P")
27158 (cond
27159 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
27160 ((or (org-on-heading-p) (org-region-active-p))
27161 (call-interactively 'org-do-promote))
27162 ((org-at-item-p) (call-interactively 'org-outdent-item))
27163 (t (call-interactively 'backward-word))))
27165 (defun org-metaright (&optional arg)
27166 "Demote subtree or move table column to right.
27167 Calls `org-do-demote' or `org-table-move-column', depending on context.
27168 With no specific context, calls the Emacs default `forward-word'.
27169 See the individual commands for more information."
27170 (interactive "P")
27171 (cond
27172 ((org-at-table-p) (call-interactively 'org-table-move-column))
27173 ((or (org-on-heading-p) (org-region-active-p))
27174 (call-interactively 'org-do-demote))
27175 ((org-at-item-p) (call-interactively 'org-indent-item))
27176 (t (call-interactively 'forward-word))))
27178 (defun org-metaup (&optional arg)
27179 "Move subtree up or move table row up.
27180 Calls `org-move-subtree-up' or `org-table-move-row' or
27181 `org-move-item-up', depending on context. See the individual commands
27182 for more information."
27183 (interactive "P")
27184 (cond
27185 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
27186 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
27187 ((org-at-item-p) (call-interactively 'org-move-item-up))
27188 (t (transpose-lines 1) (beginning-of-line -1))))
27190 (defun org-metadown (&optional arg)
27191 "Move subtree down or move table row down.
27192 Calls `org-move-subtree-down' or `org-table-move-row' or
27193 `org-move-item-down', depending on context. See the individual
27194 commands for more information."
27195 (interactive "P")
27196 (cond
27197 ((org-at-table-p) (call-interactively 'org-table-move-row))
27198 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
27199 ((org-at-item-p) (call-interactively 'org-move-item-down))
27200 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
27202 (defun org-shiftup (&optional arg)
27203 "Increase item in timestamp or increase priority of current headline.
27204 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
27205 depending on context. See the individual commands for more information."
27206 (interactive "P")
27207 (cond
27208 ((org-at-timestamp-p t)
27209 (call-interactively (if org-edit-timestamp-down-means-later
27210 'org-timestamp-down 'org-timestamp-up)))
27211 ((org-on-heading-p) (call-interactively 'org-priority-up))
27212 ((org-at-item-p) (call-interactively 'org-previous-item))
27213 (t (call-interactively 'org-beginning-of-item) (beginning-of-line 1))))
27215 (defun org-shiftdown (&optional arg)
27216 "Decrease item in timestamp or decrease priority of current headline.
27217 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
27218 depending on context. See the individual commands for more information."
27219 (interactive "P")
27220 (cond
27221 ((org-at-timestamp-p t)
27222 (call-interactively (if org-edit-timestamp-down-means-later
27223 'org-timestamp-up 'org-timestamp-down)))
27224 ((org-on-heading-p) (call-interactively 'org-priority-down))
27225 (t (call-interactively 'org-next-item))))
27227 (defun org-shiftright ()
27228 "Next TODO keyword or timestamp one day later, depending on context."
27229 (interactive)
27230 (cond
27231 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
27232 ((org-on-heading-p) (org-call-with-arg 'org-todo 'right))
27233 ((org-at-item-p) (org-call-with-arg 'org-cycle-list-bullet nil))
27234 ((org-at-property-p) (call-interactively 'org-property-next-allowed-value))
27235 (t (org-shiftcursor-error))))
27237 (defun org-shiftleft ()
27238 "Previous TODO keyword or timestamp one day earlier, depending on context."
27239 (interactive)
27240 (cond
27241 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
27242 ((org-on-heading-p) (org-call-with-arg 'org-todo 'left))
27243 ((org-at-item-p) (org-call-with-arg 'org-cycle-list-bullet 'previous))
27244 ((org-at-property-p)
27245 (call-interactively 'org-property-previous-allowed-value))
27246 (t (org-shiftcursor-error))))
27248 (defun org-shiftcontrolright ()
27249 "Switch to next TODO set."
27250 (interactive)
27251 (cond
27252 ((org-on-heading-p) (org-call-with-arg 'org-todo 'nextset))
27253 (t (org-shiftcursor-error))))
27255 (defun org-shiftcontrolleft ()
27256 "Switch to previous TODO set."
27257 (interactive)
27258 (cond
27259 ((org-on-heading-p) (org-call-with-arg 'org-todo 'previousset))
27260 (t (org-shiftcursor-error))))
27262 (defun org-ctrl-c-ret ()
27263 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
27264 (interactive)
27265 (cond
27266 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
27267 (t (call-interactively 'org-insert-heading))))
27269 (defun org-copy-special ()
27270 "Copy region in table or copy current subtree.
27271 Calls `org-table-copy' or `org-copy-subtree', depending on context.
27272 See the individual commands for more information."
27273 (interactive)
27274 (call-interactively
27275 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
27277 (defun org-cut-special ()
27278 "Cut region in table or cut current subtree.
27279 Calls `org-table-copy' or `org-cut-subtree', depending on context.
27280 See the individual commands for more information."
27281 (interactive)
27282 (call-interactively
27283 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
27285 (defun org-paste-special (arg)
27286 "Paste rectangular region into table, or past subtree relative to level.
27287 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
27288 See the individual commands for more information."
27289 (interactive "P")
27290 (if (org-at-table-p)
27291 (org-table-paste-rectangle)
27292 (org-paste-subtree arg)))
27294 (defun org-ctrl-c-ctrl-c (&optional arg)
27295 "Set tags in headline, or update according to changed information at point.
27297 This command does many different things, depending on context:
27299 - If the cursor is in a headline, prompt for tags and insert them
27300 into the current line, aligned to `org-tags-column'. When called
27301 with prefix arg, realign all tags in the current buffer.
27303 - If the cursor is in one of the special #+KEYWORD lines, this
27304 triggers scanning the buffer for these lines and updating the
27305 information.
27307 - If the cursor is inside a table, realign the table. This command
27308 works even if the automatic table editor has been turned off.
27310 - If the cursor is on a #+TBLFM line, re-apply the formulas to
27311 the entire table.
27313 - If the cursor is a the beginning of a dynamic block, update it.
27315 - If the cursor is inside a table created by the table.el package,
27316 activate that table.
27318 - If the current buffer is a remember buffer, close note and file it.
27319 with a prefix argument, file it without further interaction to the default
27320 location.
27322 - If the cursor is on a <<<target>>>, update radio targets and corresponding
27323 links in this buffer.
27325 - If the cursor is on a numbered item in a plain list, renumber the
27326 ordered list.
27328 - If the cursor is on a checkbox, toggle it."
27329 (interactive "P")
27330 (let ((org-enable-table-editor t))
27331 (cond
27332 ((or org-clock-overlays
27333 org-occur-highlights
27334 org-latex-fragment-image-overlays)
27335 (org-remove-clock-overlays)
27336 (org-remove-occur-highlights)
27337 (org-remove-latex-fragment-image-overlays)
27338 (message "Temporary highlights/overlays removed from current buffer"))
27339 ((and (local-variable-p 'org-finish-function (current-buffer))
27340 (fboundp org-finish-function))
27341 (funcall org-finish-function))
27342 ((org-at-property-p)
27343 (call-interactively 'org-property-action))
27344 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
27345 ((org-on-heading-p) (call-interactively 'org-set-tags))
27346 ((org-at-table.el-p)
27347 (require 'table)
27348 (beginning-of-line 1)
27349 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
27350 (call-interactively 'table-recognize-table))
27351 ((org-at-table-p)
27352 (org-table-maybe-eval-formula)
27353 (if arg
27354 (call-interactively 'org-table-recalculate)
27355 (org-table-maybe-recalculate-line))
27356 (call-interactively 'org-table-align))
27357 ((org-at-item-checkbox-p)
27358 (call-interactively 'org-toggle-checkbox))
27359 ((org-at-item-p)
27360 (call-interactively 'org-maybe-renumber-ordered-list))
27361 ((save-excursion (beginning-of-line 1) (looking-at "#\\+BEGIN:"))
27362 ;; Dynamic block
27363 (beginning-of-line 1)
27364 (org-update-dblock))
27365 ((save-excursion (beginning-of-line 1) (looking-at "#\\+\\([A-Z]+\\)"))
27366 (cond
27367 ((equal (match-string 1) "TBLFM")
27368 ;; Recalculate the table before this line
27369 (save-excursion
27370 (beginning-of-line 1)
27371 (skip-chars-backward " \r\n\t")
27372 (if (org-at-table-p)
27373 (org-call-with-arg 'org-table-recalculate t))))
27375 (call-interactively 'org-mode-restart))))
27376 (t (error "C-c C-c can do nothing useful at this location.")))))
27378 (defun org-mode-restart ()
27379 "Restart Org-mode, to scan again for special lines.
27380 Also updates the keyword regular expressions."
27381 (interactive)
27382 (let ((org-inhibit-startup t)) (org-mode))
27383 (message "Org-mode restarted to refresh keyword and special line setup"))
27385 (defun org-kill-note-or-show-branches ()
27386 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
27387 (interactive)
27388 (if (not org-finish-function)
27389 (call-interactively 'show-branches)
27390 (let ((org-note-abort t))
27391 (funcall org-finish-function))))
27393 (defun org-return (&optional indent)
27394 "Goto next table row or insert a newline.
27395 Calls `org-table-next-row' or `newline', depending on context.
27396 See the individual commands for more information."
27397 (interactive)
27398 (cond
27399 ((bobp) (if indent (newline-and-indent) (newline)))
27400 ((and (org-at-heading-p)
27401 (looking-at
27402 (org-re "\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$")))
27403 (org-show-entry)
27404 (end-of-line 1)
27405 (newline))
27406 ((org-at-table-p)
27407 (org-table-justify-field-maybe)
27408 (call-interactively 'org-table-next-row))
27409 (t (if indent (newline-and-indent) (newline)))))
27411 (defun org-return-indent ()
27412 (interactive)
27413 "Goto next table row or insert a newline and indent.
27414 Calls `org-table-next-row' or `newline-and-indent', depending on
27415 context. See the individual commands for more information."
27416 (org-return t))
27418 (defun org-ctrl-c-minus ()
27419 "Insert separator line in table or modify bullet type in list.
27420 Calls `org-table-insert-hline' or `org-cycle-list-bullet',
27421 depending on context."
27422 (interactive)
27423 (cond
27424 ((org-at-table-p)
27425 (call-interactively 'org-table-insert-hline))
27426 ((org-on-heading-p)
27427 ;; Convert to item
27428 (save-excursion
27429 (beginning-of-line 1)
27430 (if (looking-at "\\*+ ")
27431 (replace-match (concat (make-string (- (match-end 0) (point)) ?\ ) "- ")))))
27432 ((org-in-item-p)
27433 (call-interactively 'org-cycle-list-bullet))
27434 (t (error "`C-c -' does have no function here."))))
27436 (defun org-meta-return (&optional arg)
27437 "Insert a new heading or wrap a region in a table.
27438 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
27439 See the individual commands for more information."
27440 (interactive "P")
27441 (cond
27442 ((org-at-table-p)
27443 (call-interactively 'org-table-wrap-region))
27444 (t (call-interactively 'org-insert-heading))))
27446 ;;; Menu entries
27448 ;; Define the Org-mode menus
27449 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
27450 '("Tbl"
27451 ["Align" org-ctrl-c-ctrl-c (org-at-table-p)]
27452 ["Next Field" org-cycle (org-at-table-p)]
27453 ["Previous Field" org-shifttab (org-at-table-p)]
27454 ["Next Row" org-return (org-at-table-p)]
27455 "--"
27456 ["Blank Field" org-table-blank-field (org-at-table-p)]
27457 ["Edit Field" org-table-edit-field (org-at-table-p)]
27458 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
27459 "--"
27460 ("Column"
27461 ["Move Column Left" org-metaleft (org-at-table-p)]
27462 ["Move Column Right" org-metaright (org-at-table-p)]
27463 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
27464 ["Insert Column" org-shiftmetaright (org-at-table-p)])
27465 ("Row"
27466 ["Move Row Up" org-metaup (org-at-table-p)]
27467 ["Move Row Down" org-metadown (org-at-table-p)]
27468 ["Delete Row" org-shiftmetaup (org-at-table-p)]
27469 ["Insert Row" org-shiftmetadown (org-at-table-p)]
27470 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
27471 "--"
27472 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
27473 ("Rectangle"
27474 ["Copy Rectangle" org-copy-special (org-at-table-p)]
27475 ["Cut Rectangle" org-cut-special (org-at-table-p)]
27476 ["Paste Rectangle" org-paste-special (org-at-table-p)]
27477 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
27478 "--"
27479 ("Calculate"
27480 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
27481 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
27482 ["Edit Formulas" org-table-edit-formulas (org-at-table-p)]
27483 "--"
27484 ["Recalculate line" org-table-recalculate (org-at-table-p)]
27485 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
27486 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
27487 "--"
27488 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
27489 "--"
27490 ["Sum Column/Rectangle" org-table-sum
27491 (or (org-at-table-p) (org-region-active-p))]
27492 ["Which Column?" org-table-current-column (org-at-table-p)])
27493 ["Debug Formulas"
27494 org-table-toggle-formula-debugger
27495 :style toggle :selected org-table-formula-debug]
27496 ["Show Col/Row Numbers"
27497 org-table-toggle-coordinate-overlays
27498 :style toggle :selected org-table-overlay-coordinates]
27499 "--"
27500 ["Create" org-table-create (and (not (org-at-table-p))
27501 org-enable-table-editor)]
27502 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
27503 ["Import from File" org-table-import (not (org-at-table-p))]
27504 ["Export to File" org-table-export (org-at-table-p)]
27505 "--"
27506 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
27508 (easy-menu-define org-org-menu org-mode-map "Org menu"
27509 '("Org"
27510 ("Show/Hide"
27511 ["Cycle Visibility" org-cycle (or (bobp) (outline-on-heading-p))]
27512 ["Cycle Global Visibility" org-shifttab (not (org-at-table-p))]
27513 ["Sparse Tree" org-occur t]
27514 ["Reveal Context" org-reveal t]
27515 ["Show All" show-all t]
27516 "--"
27517 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
27518 "--"
27519 ["New Heading" org-insert-heading t]
27520 ("Navigate Headings"
27521 ["Up" outline-up-heading t]
27522 ["Next" outline-next-visible-heading t]
27523 ["Previous" outline-previous-visible-heading t]
27524 ["Next Same Level" outline-forward-same-level t]
27525 ["Previous Same Level" outline-backward-same-level t]
27526 "--"
27527 ["Jump" org-goto t])
27528 ("Edit Structure"
27529 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
27530 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
27531 "--"
27532 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
27533 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
27534 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
27535 "--"
27536 ["Promote Heading" org-metaleft (not (org-at-table-p))]
27537 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
27538 ["Demote Heading" org-metaright (not (org-at-table-p))]
27539 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
27540 "--"
27541 ["Sort Region/Children" org-sort (not (org-at-table-p))]
27542 "--"
27543 ["Convert to odd levels" org-convert-to-odd-levels t]
27544 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
27545 ("Editing"
27546 ["Emphasis..." org-emphasize t])
27547 ("Archive"
27548 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
27549 ; ["Check and Tag Children" (org-toggle-archive-tag (4))
27550 ; :active t :keys "C-u C-c C-x C-a"]
27551 ["Sparse trees open ARCHIVE trees"
27552 (setq org-sparse-tree-open-archived-trees
27553 (not org-sparse-tree-open-archived-trees))
27554 :style toggle :selected org-sparse-tree-open-archived-trees]
27555 ["Cycling opens ARCHIVE trees"
27556 (setq org-cycle-open-archived-trees (not org-cycle-open-archived-trees))
27557 :style toggle :selected org-cycle-open-archived-trees]
27558 ["Agenda includes ARCHIVE trees"
27559 (setq org-agenda-skip-archived-trees (not org-agenda-skip-archived-trees))
27560 :style toggle :selected (not org-agenda-skip-archived-trees)]
27561 "--"
27562 ["Move Subtree to Archive" org-advertized-archive-subtree t]
27563 ; ["Check and Move Children" (org-archive-subtree '(4))
27564 ; :active t :keys "C-u C-c C-x C-s"]
27566 "--"
27567 ("TODO Lists"
27568 ["TODO/DONE/-" org-todo t]
27569 ("Select keyword"
27570 ["Next keyword" org-shiftright (org-on-heading-p)]
27571 ["Previous keyword" org-shiftleft (org-on-heading-p)]
27572 ["Complete Keyword" org-complete (assq :todo-keyword (org-context))]
27573 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))]
27574 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))])
27575 ["Show TODO Tree" org-show-todo-tree t]
27576 ["Global TODO list" org-todo-list t]
27577 "--"
27578 ["Set Priority" org-priority t]
27579 ["Priority Up" org-shiftup t]
27580 ["Priority Down" org-shiftdown t])
27581 ("TAGS and Properties"
27582 ["Set Tags" 'org-ctrl-c-ctrl-c (org-at-heading-p)]
27583 ["Change tag in region" 'org-change-tag-in-region (org-region-active-p)]
27584 "--"
27585 ["Set property" 'org-set-property t]
27586 ["Column view of properties" org-columns t]
27587 ["Insert Column View DBlock" org-insert-columns-dblock t])
27588 ("Dates and Scheduling"
27589 ["Timestamp" org-time-stamp t]
27590 ["Timestamp (inactive)" org-time-stamp-inactive t]
27591 ("Change Date"
27592 ["1 Day Later" org-shiftright t]
27593 ["1 Day Earlier" org-shiftleft t]
27594 ["1 ... Later" org-shiftup t]
27595 ["1 ... Earlier" org-shiftdown t])
27596 ["Compute Time Range" org-evaluate-time-range t]
27597 ["Schedule Item" org-schedule t]
27598 ["Deadline" org-deadline t]
27599 "--"
27600 ["Custom time format" org-toggle-time-stamp-overlays
27601 :style radio :selected org-display-custom-times]
27602 "--"
27603 ["Goto Calendar" org-goto-calendar t]
27604 ["Date from Calendar" org-date-from-calendar t])
27605 ("Logging work"
27606 ["Clock in" org-clock-in t]
27607 ["Clock out" org-clock-out t]
27608 ["Clock cancel" org-clock-cancel t]
27609 ["Goto running clock" org-clock-goto t]
27610 ["Display times" org-clock-display t]
27611 ["Create clock table" org-clock-report t]
27612 "--"
27613 ["Record DONE time"
27614 (progn (setq org-log-done (not org-log-done))
27615 (message "Switching to %s will %s record a timestamp"
27616 (car org-done-keywords)
27617 (if org-log-done "automatically" "not")))
27618 :style toggle :selected org-log-done])
27619 "--"
27620 ["Agenda Command..." org-agenda t]
27621 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
27622 ("File List for Agenda")
27623 ("Special views current file"
27624 ["TODO Tree" org-show-todo-tree t]
27625 ["Check Deadlines" org-check-deadlines t]
27626 ["Timeline" org-timeline t]
27627 ["Tags Tree" org-tags-sparse-tree t])
27628 "--"
27629 ("Hyperlinks"
27630 ["Store Link (Global)" org-store-link t]
27631 ["Insert Link" org-insert-link t]
27632 ["Follow Link" org-open-at-point t]
27633 "--"
27634 ["Next link" org-next-link t]
27635 ["Previous link" org-previous-link t]
27636 "--"
27637 ["Descriptive Links"
27638 (progn (org-add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
27639 :style radio :selected (member '(org-link) buffer-invisibility-spec)]
27640 ["Literal Links"
27641 (progn
27642 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
27643 :style radio :selected (not (member '(org-link) buffer-invisibility-spec))])
27644 "--"
27645 ["Export/Publish..." org-export t]
27646 ("LaTeX"
27647 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
27648 :selected org-cdlatex-mode]
27649 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
27650 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
27651 ["Modify math symbol" org-cdlatex-math-modify
27652 (org-inside-LaTeX-fragment-p)]
27653 ["Export LaTeX fragments as images"
27654 (setq org-export-with-LaTeX-fragments (not org-export-with-LaTeX-fragments))
27655 :style toggle :selected org-export-with-LaTeX-fragments])
27656 "--"
27657 ("Documentation"
27658 ["Show Version" org-version t]
27659 ["Info Documentation" org-info t])
27660 ("Customize"
27661 ["Browse Org Group" org-customize t]
27662 "--"
27663 ["Expand This Menu" org-create-customize-menu
27664 (fboundp 'customize-menu-create)])
27665 "--"
27666 ["Refresh setup" org-mode-restart t]
27669 (defun org-info (&optional node)
27670 "Read documentation for Org-mode in the info system.
27671 With optional NODE, go directly to that node."
27672 (interactive)
27673 (require 'info)
27674 (info (format "(org)%s" (or node ""))))
27676 (defun org-install-agenda-files-menu ()
27677 (let ((bl (buffer-list)))
27678 (save-excursion
27679 (while bl
27680 (set-buffer (pop bl))
27681 (if (org-mode-p) (setq bl nil)))
27682 (when (org-mode-p)
27683 (easy-menu-change
27684 '("Org") "File List for Agenda"
27685 (append
27686 (list
27687 ["Edit File List" (org-edit-agenda-file-list) t]
27688 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
27689 ["Remove Current File from List" org-remove-file t]
27690 ["Cycle through agenda files" org-cycle-agenda-files t]
27691 ["Occur in all agenda files" org-occur-in-agenda-files t]
27692 "--")
27693 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
27695 ;;;; Documentation
27697 (defun org-customize ()
27698 "Call the customize function with org as argument."
27699 (interactive)
27700 (customize-browse 'org))
27702 (defun org-create-customize-menu ()
27703 "Create a full customization menu for Org-mode, insert it into the menu."
27704 (interactive)
27705 (if (fboundp 'customize-menu-create)
27706 (progn
27707 (easy-menu-change
27708 '("Org") "Customize"
27709 `(["Browse Org group" org-customize t]
27710 "--"
27711 ,(customize-menu-create 'org)
27712 ["Set" Custom-set t]
27713 ["Save" Custom-save t]
27714 ["Reset to Current" Custom-reset-current t]
27715 ["Reset to Saved" Custom-reset-saved t]
27716 ["Reset to Standard Settings" Custom-reset-standard t]))
27717 (message "\"Org\"-menu now contains full customization menu"))
27718 (error "Cannot expand menu (outdated version of cus-edit.el)")))
27720 ;;;; Miscellaneous stuff
27723 ;;; Generally useful functions
27725 (defun org-context ()
27726 "Return a list of contexts of the current cursor position.
27727 If several contexts apply, all are returned.
27728 Each context entry is a list with a symbol naming the context, and
27729 two positions indicating start and end of the context. Possible
27730 contexts are:
27732 :headline anywhere in a headline
27733 :headline-stars on the leading stars in a headline
27734 :todo-keyword on a TODO keyword (including DONE) in a headline
27735 :tags on the TAGS in a headline
27736 :priority on the priority cookie in a headline
27737 :item on the first line of a plain list item
27738 :item-bullet on the bullet/number of a plain list item
27739 :checkbox on the checkbox in a plain list item
27740 :table in an org-mode table
27741 :table-special on a special filed in a table
27742 :table-table in a table.el table
27743 :link on a hyperlink
27744 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
27745 :target on a <<target>>
27746 :radio-target on a <<<radio-target>>>
27747 :latex-fragment on a LaTeX fragment
27748 :latex-preview on a LaTeX fragment with overlayed preview image
27750 This function expects the position to be visible because it uses font-lock
27751 faces as a help to recognize the following contexts: :table-special, :link,
27752 and :keyword."
27753 (let* ((f (get-text-property (point) 'face))
27754 (faces (if (listp f) f (list f)))
27755 (p (point)) clist o)
27756 ;; First the large context
27757 (cond
27758 ((org-on-heading-p t)
27759 (push (list :headline (point-at-bol) (point-at-eol)) clist)
27760 (when (progn
27761 (beginning-of-line 1)
27762 (looking-at org-todo-line-tags-regexp))
27763 (push (org-point-in-group p 1 :headline-stars) clist)
27764 (push (org-point-in-group p 2 :todo-keyword) clist)
27765 (push (org-point-in-group p 4 :tags) clist))
27766 (goto-char p)
27767 (skip-chars-backward "^[\n\r \t") (or (eobp) (backward-char 1))
27768 (if (looking-at "\\[#[A-Z0-9]\\]")
27769 (push (org-point-in-group p 0 :priority) clist)))
27771 ((org-at-item-p)
27772 (push (org-point-in-group p 2 :item-bullet) clist)
27773 (push (list :item (point-at-bol)
27774 (save-excursion (org-end-of-item) (point)))
27775 clist)
27776 (and (org-at-item-checkbox-p)
27777 (push (org-point-in-group p 0 :checkbox) clist)))
27779 ((org-at-table-p)
27780 (push (list :table (org-table-begin) (org-table-end)) clist)
27781 (if (memq 'org-formula faces)
27782 (push (list :table-special
27783 (previous-single-property-change p 'face)
27784 (next-single-property-change p 'face)) clist)))
27785 ((org-at-table-p 'any)
27786 (push (list :table-table) clist)))
27787 (goto-char p)
27789 ;; Now the small context
27790 (cond
27791 ((org-at-timestamp-p)
27792 (push (org-point-in-group p 0 :timestamp) clist))
27793 ((memq 'org-link faces)
27794 (push (list :link
27795 (previous-single-property-change p 'face)
27796 (next-single-property-change p 'face)) clist))
27797 ((memq 'org-special-keyword faces)
27798 (push (list :keyword
27799 (previous-single-property-change p 'face)
27800 (next-single-property-change p 'face)) clist))
27801 ((org-on-target-p)
27802 (push (org-point-in-group p 0 :target) clist)
27803 (goto-char (1- (match-beginning 0)))
27804 (if (looking-at org-radio-target-regexp)
27805 (push (org-point-in-group p 0 :radio-target) clist))
27806 (goto-char p))
27807 ((setq o (car (delq nil
27808 (mapcar
27809 (lambda (x)
27810 (if (memq x org-latex-fragment-image-overlays) x))
27811 (org-overlays-at (point))))))
27812 (push (list :latex-fragment
27813 (org-overlay-start o) (org-overlay-end o)) clist)
27814 (push (list :latex-preview
27815 (org-overlay-start o) (org-overlay-end o)) clist))
27816 ((org-inside-LaTeX-fragment-p)
27817 ;; FIXME: positions wrong.
27818 (push (list :latex-fragment (point) (point)) clist)))
27820 (setq clist (nreverse (delq nil clist)))
27821 clist))
27823 ;; FIXME: Compare with at-regexp-p Do we need both?
27824 (defun org-in-regexp (re &optional nlines visually)
27825 "Check if point is inside a match of regexp.
27826 Normally only the current line is checked, but you can include NLINES extra
27827 lines both before and after point into the search.
27828 If VISUALLY is set, require that the cursor is not after the match but
27829 really on, so that the block visually is on the match."
27830 (catch 'exit
27831 (let ((pos (point))
27832 (eol (point-at-eol (+ 1 (or nlines 0))))
27833 (inc (if visually 1 0)))
27834 (save-excursion
27835 (beginning-of-line (- 1 (or nlines 0)))
27836 (while (re-search-forward re eol t)
27837 (if (and (<= (match-beginning 0) pos)
27838 (>= (+ inc (match-end 0)) pos))
27839 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
27841 (defun org-at-regexp-p (regexp)
27842 "Is point inside a match of REGEXP in the current line?"
27843 (catch 'exit
27844 (save-excursion
27845 (let ((pos (point)) (end (point-at-eol)))
27846 (beginning-of-line 1)
27847 (while (re-search-forward regexp end t)
27848 (if (and (<= (match-beginning 0) pos)
27849 (>= (match-end 0) pos))
27850 (throw 'exit t)))
27851 nil))))
27853 (defun org-occur-in-agenda-files (regexp &optional nlines)
27854 "Call `multi-occur' with buffers for all agenda files."
27855 (interactive "sOrg-files matching: \np")
27856 (let* ((files (org-agenda-files))
27857 (tnames (mapcar 'file-truename files))
27858 (extra org-agenda-text-search-extra-files)
27860 (while (setq f (pop extra))
27861 (unless (member (file-truename f) tnames)
27862 (add-to-list 'files f 'append)
27863 (add-to-list 'tnames (file-truename f) 'append)))
27864 (multi-occur
27865 (mapcar (lambda (x) (or (get-file-buffer x) (find-file-noselect x))) files)
27866 regexp)))
27868 (if (boundp 'occur-mode-find-occurrence-hook)
27869 ;; Emacs 23
27870 (add-hook 'occur-mode-find-occurrence-hook
27871 (lambda ()
27872 (when (org-mode-p)
27873 (org-reveal))))
27874 ;; Emacs 22
27875 (defadvice occur-mode-goto-occurrence
27876 (after org-occur-reveal activate)
27877 (and (org-mode-p) (org-reveal)))
27878 (defadvice occur-mode-goto-occurrence-other-window
27879 (after org-occur-reveal activate)
27880 (and (org-mode-p) (org-reveal)))
27881 (defadvice occur-mode-display-occurrence
27882 (after org-occur-reveal activate)
27883 (when (org-mode-p)
27884 (let ((pos (occur-mode-find-occurrence)))
27885 (with-current-buffer (marker-buffer pos)
27886 (save-excursion
27887 (goto-char pos)
27888 (org-reveal)))))))
27890 (defun org-uniquify (list)
27891 "Remove duplicate elements from LIST."
27892 (let (res)
27893 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
27894 res))
27896 (defun org-delete-all (elts list)
27897 "Remove all elements in ELTS from LIST."
27898 (while elts
27899 (setq list (delete (pop elts) list)))
27900 list)
27902 (defun org-back-over-empty-lines ()
27903 "Move backwards over witespace, to the beginning of the first empty line.
27904 Returns the number o empty lines passed."
27905 (let ((pos (point)))
27906 (skip-chars-backward " \t\n\r")
27907 (beginning-of-line 2)
27908 (goto-char (min (point) pos))
27909 (count-lines (point) pos)))
27911 (defun org-skip-whitespace ()
27912 (skip-chars-forward " \t\n\r"))
27914 (defun org-point-in-group (point group &optional context)
27915 "Check if POINT is in match-group GROUP.
27916 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
27917 match. If the match group does ot exist or point is not inside it,
27918 return nil."
27919 (and (match-beginning group)
27920 (>= point (match-beginning group))
27921 (<= point (match-end group))
27922 (if context
27923 (list context (match-beginning group) (match-end group))
27924 t)))
27926 (defun org-switch-to-buffer-other-window (&rest args)
27927 "Switch to buffer in a second window on the current frame.
27928 In particular, do not allow pop-up frames."
27929 (let (pop-up-frames special-display-buffer-names special-display-regexps
27930 special-display-function)
27931 (apply 'switch-to-buffer-other-window args)))
27933 (defun org-combine-plists (&rest plists)
27934 "Create a single property list from all plists in PLISTS.
27935 The process starts by copying the first list, and then setting properties
27936 from the other lists. Settings in the last list are the most significant
27937 ones and overrule settings in the other lists."
27938 (let ((rtn (copy-sequence (pop plists)))
27939 p v ls)
27940 (while plists
27941 (setq ls (pop plists))
27942 (while ls
27943 (setq p (pop ls) v (pop ls))
27944 (setq rtn (plist-put rtn p v))))
27945 rtn))
27947 (defun org-move-line-down (arg)
27948 "Move the current line down. With prefix argument, move it past ARG lines."
27949 (interactive "p")
27950 (let ((col (current-column))
27951 beg end pos)
27952 (beginning-of-line 1) (setq beg (point))
27953 (beginning-of-line 2) (setq end (point))
27954 (beginning-of-line (+ 1 arg))
27955 (setq pos (move-marker (make-marker) (point)))
27956 (insert (delete-and-extract-region beg end))
27957 (goto-char pos)
27958 (move-to-column col)))
27960 (defun org-move-line-up (arg)
27961 "Move the current line up. With prefix argument, move it past ARG lines."
27962 (interactive "p")
27963 (let ((col (current-column))
27964 beg end pos)
27965 (beginning-of-line 1) (setq beg (point))
27966 (beginning-of-line 2) (setq end (point))
27967 (beginning-of-line (- arg))
27968 (setq pos (move-marker (make-marker) (point)))
27969 (insert (delete-and-extract-region beg end))
27970 (goto-char pos)
27971 (move-to-column col)))
27973 (defun org-replace-escapes (string table)
27974 "Replace %-escapes in STRING with values in TABLE.
27975 TABLE is an association list with keys like \"%a\" and string values.
27976 The sequences in STRING may contain normal field width and padding information,
27977 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
27978 so values can contain further %-escapes if they are define later in TABLE."
27979 (let ((case-fold-search nil)
27980 e re rpl)
27981 (while (setq e (pop table))
27982 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
27983 (while (string-match re string)
27984 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
27985 (cdr e)))
27986 (setq string (replace-match rpl t t string))))
27987 string))
27990 (defun org-sublist (list start end)
27991 "Return a section of LIST, from START to END.
27992 Counting starts at 1."
27993 (let (rtn (c start))
27994 (setq list (nthcdr (1- start) list))
27995 (while (and list (<= c end))
27996 (push (pop list) rtn)
27997 (setq c (1+ c)))
27998 (nreverse rtn)))
28000 (defun org-find-base-buffer-visiting (file)
28001 "Like `find-buffer-visiting' but alway return the base buffer and
28002 not an indirect buffer"
28003 (let ((buf (find-buffer-visiting file)))
28004 (if buf
28005 (or (buffer-base-buffer buf) buf)
28006 nil)))
28008 (defun org-image-file-name-regexp ()
28009 "Return regexp matching the file names of images."
28010 (if (fboundp 'image-file-name-regexp)
28011 (image-file-name-regexp)
28012 (let ((image-file-name-extensions
28013 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
28014 "xbm" "xpm" "pbm" "pgm" "ppm")))
28015 (concat "\\."
28016 (regexp-opt (nconc (mapcar 'upcase
28017 image-file-name-extensions)
28018 image-file-name-extensions)
28020 "\\'"))))
28022 (defun org-file-image-p (file)
28023 "Return non-nil if FILE is an image."
28024 (save-match-data
28025 (string-match (org-image-file-name-regexp) file)))
28027 ;;; Paragraph filling stuff.
28028 ;; We want this to be just right, so use the full arsenal.
28030 (defun org-indent-line-function ()
28031 "Indent line like previous, but further if previous was headline or item."
28032 (interactive)
28033 (let* ((pos (point))
28034 (itemp (org-at-item-p))
28035 column bpos bcol tpos tcol bullet btype bullet-type)
28036 ;; Find the previous relevant line
28037 (beginning-of-line 1)
28038 (cond
28039 ((looking-at "#") (setq column 0))
28040 ((looking-at "\\*+ ") (setq column 0))
28042 (beginning-of-line 0)
28043 (while (and (not (bobp)) (looking-at "[ \t]*[\n:#|]"))
28044 (beginning-of-line 0))
28045 (cond
28046 ((looking-at "\\*+[ \t]+")
28047 (goto-char (match-end 0))
28048 (setq column (current-column)))
28049 ((org-in-item-p)
28050 (org-beginning-of-item)
28051 ; (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
28052 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*\\(\\[[- X]\\][ \t]*\\)?")
28053 (setq bpos (match-beginning 1) tpos (match-end 0)
28054 bcol (progn (goto-char bpos) (current-column))
28055 tcol (progn (goto-char tpos) (current-column))
28056 bullet (match-string 1)
28057 bullet-type (if (string-match "[0-9]" bullet) "n" bullet))
28058 (if (not itemp)
28059 (setq column tcol)
28060 (goto-char pos)
28061 (beginning-of-line 1)
28062 (if (looking-at "\\S-")
28063 (progn
28064 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
28065 (setq bullet (match-string 1)
28066 btype (if (string-match "[0-9]" bullet) "n" bullet))
28067 (setq column (if (equal btype bullet-type) bcol tcol)))
28068 (setq column (org-get-indentation)))))
28069 (t (setq column (org-get-indentation))))))
28070 (goto-char pos)
28071 (if (<= (current-column) (current-indentation))
28072 (indent-line-to column)
28073 (save-excursion (indent-line-to column)))
28074 (setq column (current-column))
28075 (beginning-of-line 1)
28076 (if (looking-at
28077 "\\([ \t]+\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
28078 (replace-match (concat "\\1" (format org-property-format
28079 (match-string 2) (match-string 3)))
28080 t nil))
28081 (move-to-column column)))
28083 (defun org-set-autofill-regexps ()
28084 (interactive)
28085 ;; In the paragraph separator we include headlines, because filling
28086 ;; text in a line directly attached to a headline would otherwise
28087 ;; fill the headline as well.
28088 (org-set-local 'comment-start-skip "^#+[ \t]*")
28089 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|]")
28090 ;; The paragraph starter includes hand-formatted lists.
28091 (org-set-local 'paragraph-start
28092 "\f\\|[ ]*$\\|\\*+ \\|\f\\|[ \t]*\\([-+*][ \t]+\\|[0-9]+[.)][ \t]+\\)\\|[ \t]*[:|]")
28093 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
28094 ;; But only if the user has not turned off tables or fixed-width regions
28095 (org-set-local
28096 'auto-fill-inhibit-regexp
28097 (concat "\\*+ \\|#\\+"
28098 "\\|[ \t]*" org-keyword-time-regexp
28099 (if (or org-enable-table-editor org-enable-fixed-width-editor)
28100 (concat
28101 "\\|[ \t]*["
28102 (if org-enable-table-editor "|" "")
28103 (if org-enable-fixed-width-editor ":" "")
28104 "]"))))
28105 ;; We use our own fill-paragraph function, to make sure that tables
28106 ;; and fixed-width regions are not wrapped. That function will pass
28107 ;; through to `fill-paragraph' when appropriate.
28108 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
28109 ; Adaptive filling: To get full control, first make sure that
28110 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
28111 (org-set-local 'adaptive-fill-regexp "\000")
28112 (org-set-local 'adaptive-fill-function
28113 'org-adaptive-fill-function)
28114 (org-set-local
28115 'align-mode-rules-list
28116 '((org-in-buffer-settings
28117 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
28118 (modes . '(org-mode))))))
28120 (defun org-fill-paragraph (&optional justify)
28121 "Re-align a table, pass through to fill-paragraph if no table."
28122 (let ((table-p (org-at-table-p))
28123 (table.el-p (org-at-table.el-p)))
28124 (cond ((and (equal (char-after (point-at-bol)) ?*)
28125 (save-excursion (goto-char (point-at-bol))
28126 (looking-at outline-regexp)))
28127 t) ; skip headlines
28128 (table.el-p t) ; skip table.el tables
28129 (table-p (org-table-align) t) ; align org-mode tables
28130 (t nil)))) ; call paragraph-fill
28132 ;; For reference, this is the default value of adaptive-fill-regexp
28133 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
28135 (defun org-adaptive-fill-function ()
28136 "Return a fill prefix for org-mode files.
28137 In particular, this makes sure hanging paragraphs for hand-formatted lists
28138 work correctly."
28139 (cond ((looking-at "#[ \t]+")
28140 (match-string 0))
28141 ((looking-at "[ \t]*\\([-*+] \\|[0-9]+[.)] \\)?")
28142 (save-excursion
28143 (goto-char (match-end 0))
28144 (make-string (current-column) ?\ )))
28145 (t nil)))
28147 ;;;; Functions extending outline functionality
28150 (defun org-beginning-of-line (&optional arg)
28151 "Go to the beginning of the current line. If that is invisible, continue
28152 to a visible line beginning. This makes the function of C-a more intuitive.
28153 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
28154 first attempt, and only move to after the tags when the cursor is already
28155 beyond the end of the headline."
28156 (interactive "P")
28157 (let ((pos (point)))
28158 (beginning-of-line 1)
28159 (if (bobp)
28161 (backward-char 1)
28162 (if (org-invisible-p)
28163 (while (and (not (bobp)) (org-invisible-p))
28164 (backward-char 1)
28165 (beginning-of-line 1))
28166 (forward-char 1)))
28167 (when org-special-ctrl-a/e
28168 (cond
28169 ((and (looking-at org-todo-line-regexp)
28170 (= (char-after (match-end 1)) ?\ ))
28171 (goto-char
28172 (if (eq org-special-ctrl-a/e t)
28173 (cond ((> pos (match-beginning 3)) (match-beginning 3))
28174 ((= pos (point)) (match-beginning 3))
28175 (t (point)))
28176 (cond ((> pos (point)) (point))
28177 ((not (eq last-command this-command)) (point))
28178 (t (match-beginning 3))))))
28179 ((org-at-item-p)
28180 (goto-char
28181 (if (eq org-special-ctrl-a/e t)
28182 (cond ((> pos (match-end 4)) (match-end 4))
28183 ((= pos (point)) (match-end 4))
28184 (t (point)))
28185 (cond ((> pos (point)) (point))
28186 ((not (eq last-command this-command)) (point))
28187 (t (match-end 4))))))))))
28189 (defun org-end-of-line (&optional arg)
28190 "Go to the end of the line.
28191 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
28192 first attempt, and only move to after the tags when the cursor is already
28193 beyond the end of the headline."
28194 (interactive "P")
28195 (if (or (not org-special-ctrl-a/e)
28196 (not (org-on-heading-p)))
28197 (end-of-line arg)
28198 (let ((pos (point)))
28199 (beginning-of-line 1)
28200 (if (looking-at (org-re ".*?\\([ \t]*\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
28201 (if (eq org-special-ctrl-a/e t)
28202 (if (or (< pos (match-beginning 1))
28203 (= pos (match-end 0)))
28204 (goto-char (match-beginning 1))
28205 (goto-char (match-end 0)))
28206 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
28207 (goto-char (match-end 0))
28208 (goto-char (match-beginning 1))))
28209 (end-of-line arg)))))
28211 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
28212 (define-key org-mode-map "\C-e" 'org-end-of-line)
28214 (defun org-kill-line (&optional arg)
28215 "Kill line, to tags or end of line."
28216 (interactive "P")
28217 (cond
28218 ((or (not org-special-ctrl-k)
28219 (bolp)
28220 (not (org-on-heading-p)))
28221 (call-interactively 'kill-line))
28222 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$"))
28223 (kill-region (point) (match-beginning 1))
28224 (org-set-tags nil t))
28225 (t (kill-region (point) (point-at-eol)))))
28227 (define-key org-mode-map "\C-k" 'org-kill-line)
28229 (defun org-invisible-p ()
28230 "Check if point is at a character currently not visible."
28231 ;; Early versions of noutline don't have `outline-invisible-p'.
28232 (if (fboundp 'outline-invisible-p)
28233 (outline-invisible-p)
28234 (get-char-property (point) 'invisible)))
28236 (defun org-invisible-p2 ()
28237 "Check if point is at a character currently not visible."
28238 (save-excursion
28239 (if (and (eolp) (not (bobp))) (backward-char 1))
28240 ;; Early versions of noutline don't have `outline-invisible-p'.
28241 (if (fboundp 'outline-invisible-p)
28242 (outline-invisible-p)
28243 (get-char-property (point) 'invisible))))
28245 (defalias 'org-back-to-heading 'outline-back-to-heading)
28246 (defalias 'org-on-heading-p 'outline-on-heading-p)
28247 (defalias 'org-at-heading-p 'outline-on-heading-p)
28248 (defun org-at-heading-or-item-p ()
28249 (or (org-on-heading-p) (org-at-item-p)))
28251 (defun org-on-target-p ()
28252 (or (org-in-regexp org-radio-target-regexp)
28253 (org-in-regexp org-target-regexp)))
28255 (defun org-up-heading-all (arg)
28256 "Move to the heading line of which the present line is a subheading.
28257 This function considers both visible and invisible heading lines.
28258 With argument, move up ARG levels."
28259 (if (fboundp 'outline-up-heading-all)
28260 (outline-up-heading-all arg) ; emacs 21 version of outline.el
28261 (outline-up-heading arg t))) ; emacs 22 version of outline.el
28263 (defun org-up-heading-safe ()
28264 "Move to the heading line of which the present line is a subheading.
28265 This version will not throw an error. It will return the level of the
28266 headline found, or nil if no higher level is found."
28267 (let ((pos (point)) start-level level
28268 (re (concat "^" outline-regexp)))
28269 (catch 'exit
28270 (outline-back-to-heading t)
28271 (setq start-level (funcall outline-level))
28272 (if (equal start-level 1) (throw 'exit nil))
28273 (while (re-search-backward re nil t)
28274 (setq level (funcall outline-level))
28275 (if (< level start-level) (throw 'exit level)))
28276 nil)))
28278 (defun org-first-sibling-p ()
28279 "Is this heading the first child of its parents?"
28280 (interactive)
28281 (let ((re (concat "^" outline-regexp))
28282 level l)
28283 (unless (org-at-heading-p t)
28284 (error "Not at a heading"))
28285 (setq level (funcall outline-level))
28286 (save-excursion
28287 (if (not (re-search-backward re nil t))
28289 (setq l (funcall outline-level))
28290 (< l level)))))
28292 (defun org-goto-sibling (&optional previous)
28293 "Goto the next sibling, even if it is invisible.
28294 When PREVIOUS is set, go to the previous sibling instead. Returns t
28295 when a sibling was found. When none is found, return nil and don't
28296 move point."
28297 (let ((fun (if previous 're-search-backward 're-search-forward))
28298 (pos (point))
28299 (re (concat "^" outline-regexp))
28300 level l)
28301 (when (condition-case nil (org-back-to-heading t) (error nil))
28302 (setq level (funcall outline-level))
28303 (catch 'exit
28304 (or previous (forward-char 1))
28305 (while (funcall fun re nil t)
28306 (setq l (funcall outline-level))
28307 (when (< l level) (goto-char pos) (throw 'exit nil))
28308 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
28309 (goto-char pos)
28310 nil))))
28312 (defun org-show-siblings ()
28313 "Show all siblings of the current headline."
28314 (save-excursion
28315 (while (org-goto-sibling) (org-flag-heading nil)))
28316 (save-excursion
28317 (while (org-goto-sibling 'previous)
28318 (org-flag-heading nil))))
28320 (defun org-show-hidden-entry ()
28321 "Show an entry where even the heading is hidden."
28322 (save-excursion
28323 (org-show-entry)))
28325 (defun org-flag-heading (flag &optional entry)
28326 "Flag the current heading. FLAG non-nil means make invisible.
28327 When ENTRY is non-nil, show the entire entry."
28328 (save-excursion
28329 (org-back-to-heading t)
28330 ;; Check if we should show the entire entry
28331 (if entry
28332 (progn
28333 (org-show-entry)
28334 (save-excursion
28335 (and (outline-next-heading)
28336 (org-flag-heading nil))))
28337 (outline-flag-region (max (point-min) (1- (point)))
28338 (save-excursion (outline-end-of-heading) (point))
28339 flag))))
28341 (defun org-end-of-subtree (&optional invisible-OK to-heading)
28342 ;; This is an exact copy of the original function, but it uses
28343 ;; `org-back-to-heading', to make it work also in invisible
28344 ;; trees. And is uses an invisible-OK argument.
28345 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
28346 (org-back-to-heading invisible-OK)
28347 (let ((first t)
28348 (level (funcall outline-level)))
28349 (while (and (not (eobp))
28350 (or first (> (funcall outline-level) level)))
28351 (setq first nil)
28352 (outline-next-heading))
28353 (unless to-heading
28354 (if (memq (preceding-char) '(?\n ?\^M))
28355 (progn
28356 ;; Go to end of line before heading
28357 (forward-char -1)
28358 (if (memq (preceding-char) '(?\n ?\^M))
28359 ;; leave blank line before heading
28360 (forward-char -1))))))
28361 (point))
28363 (defun org-show-subtree ()
28364 "Show everything after this heading at deeper levels."
28365 (outline-flag-region
28366 (point)
28367 (save-excursion
28368 (outline-end-of-subtree) (outline-next-heading) (point))
28369 nil))
28371 (defun org-show-entry ()
28372 "Show the body directly following this heading.
28373 Show the heading too, if it is currently invisible."
28374 (interactive)
28375 (save-excursion
28376 (condition-case nil
28377 (progn
28378 (org-back-to-heading t)
28379 (outline-flag-region
28380 (max (point-min) (1- (point)))
28381 (save-excursion
28382 (re-search-forward
28383 (concat "[\r\n]\\(" outline-regexp "\\)") nil 'move)
28384 (or (match-beginning 1) (point-max)))
28385 nil))
28386 (error nil))))
28388 (defun org-make-options-regexp (kwds)
28389 "Make a regular expression for keyword lines."
28390 (concat
28392 "#?[ \t]*\\+\\("
28393 (mapconcat 'regexp-quote kwds "\\|")
28394 "\\):[ \t]*"
28395 "\\(.+\\)"))
28397 ;; Make isearch reveal the necessary context
28398 (defun org-isearch-end ()
28399 "Reveal context after isearch exits."
28400 (when isearch-success ; only if search was successful
28401 (if (featurep 'xemacs)
28402 ;; Under XEmacs, the hook is run in the correct place,
28403 ;; we directly show the context.
28404 (org-show-context 'isearch)
28405 ;; In Emacs the hook runs *before* restoring the overlays.
28406 ;; So we have to use a one-time post-command-hook to do this.
28407 ;; (Emacs 22 has a special variable, see function `org-mode')
28408 (unless (and (boundp 'isearch-mode-end-hook-quit)
28409 isearch-mode-end-hook-quit)
28410 ;; Only when the isearch was not quitted.
28411 (org-add-hook 'post-command-hook 'org-isearch-post-command
28412 'append 'local)))))
28414 (defun org-isearch-post-command ()
28415 "Remove self from hook, and show context."
28416 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
28417 (org-show-context 'isearch))
28420 ;;;; Integration with and fixes for other packages
28422 ;;; Imenu support
28424 (defvar org-imenu-markers nil
28425 "All markers currently used by Imenu.")
28426 (make-variable-buffer-local 'org-imenu-markers)
28428 (defun org-imenu-new-marker (&optional pos)
28429 "Return a new marker for use by Imenu, and remember the marker."
28430 (let ((m (make-marker)))
28431 (move-marker m (or pos (point)))
28432 (push m org-imenu-markers)
28435 (defun org-imenu-get-tree ()
28436 "Produce the index for Imenu."
28437 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
28438 (setq org-imenu-markers nil)
28439 (let* ((n org-imenu-depth)
28440 (re (concat "^" outline-regexp))
28441 (subs (make-vector (1+ n) nil))
28442 (last-level 0)
28443 m tree level head)
28444 (save-excursion
28445 (save-restriction
28446 (widen)
28447 (goto-char (point-max))
28448 (while (re-search-backward re nil t)
28449 (setq level (org-reduced-level (funcall outline-level)))
28450 (when (<= level n)
28451 (looking-at org-complex-heading-regexp)
28452 (setq head (org-match-string-no-properties 4)
28453 m (org-imenu-new-marker))
28454 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
28455 (if (>= level last-level)
28456 (push (cons head m) (aref subs level))
28457 (push (cons head (aref subs (1+ level))) (aref subs level))
28458 (loop for i from (1+ level) to n do (aset subs i nil)))
28459 (setq last-level level)))))
28460 (aref subs 1)))
28462 (eval-after-load "imenu"
28463 '(progn
28464 (add-hook 'imenu-after-jump-hook
28465 (lambda () (org-show-context 'org-goto)))))
28467 ;; Speedbar support
28469 (defun org-speedbar-set-agenda-restriction ()
28470 "Restrict future agenda commands to the location at point in speedbar.
28471 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
28472 (interactive)
28473 (let (p m tp np dir txt w)
28474 (cond
28475 ((setq p (text-property-any (point-at-bol) (point-at-eol)
28476 'org-imenu t))
28477 (setq m (get-text-property p 'org-imenu-marker))
28478 (save-excursion
28479 (save-restriction
28480 (set-buffer (marker-buffer m))
28481 (goto-char m)
28482 (org-agenda-set-restriction-lock 'subtree))))
28483 ((setq p (text-property-any (point-at-bol) (point-at-eol)
28484 'speedbar-function 'speedbar-find-file))
28485 (setq tp (previous-single-property-change
28486 (1+ p) 'speedbar-function)
28487 np (next-single-property-change
28488 tp 'speedbar-function)
28489 dir (speedbar-line-directory)
28490 txt (buffer-substring-no-properties (or tp (point-min))
28491 (or np (point-max))))
28492 (save-excursion
28493 (save-restriction
28494 (set-buffer (find-file-noselect
28495 (let ((default-directory dir))
28496 (expand-file-name txt))))
28497 (unless (org-mode-p)
28498 (error "Cannot restrict to non-Org-mode file"))
28499 (org-agenda-set-restriction-lock 'file))))
28500 (t (error "Don't know how to restrict Org-mode's agenda")))
28501 (org-move-overlay org-speedbar-restriction-lock-overlay
28502 (point-at-bol) (point-at-eol))
28503 (setq current-prefix-arg nil)
28504 (org-agenda-maybe-redo)))
28506 (eval-after-load "speedbar"
28507 '(progn
28508 (speedbar-add-supported-extension ".org")
28509 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
28510 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
28511 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
28512 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
28513 (add-hook 'speedbar-visiting-tag-hook
28514 (lambda () (org-show-context 'org-goto)))))
28517 ;;; Fixes and Hacks
28519 ;; Make flyspell not check words in links, to not mess up our keymap
28520 (defun org-mode-flyspell-verify ()
28521 "Don't let flyspell put overlays at active buttons."
28522 (not (get-text-property (point) 'keymap)))
28524 ;; Make `bookmark-jump' show the jump location if it was hidden.
28525 (eval-after-load "bookmark"
28526 '(if (boundp 'bookmark-after-jump-hook)
28527 ;; We can use the hook
28528 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
28529 ;; Hook not available, use advice
28530 (defadvice bookmark-jump (after org-make-visible activate)
28531 "Make the position visible."
28532 (org-bookmark-jump-unhide))))
28534 (defun org-bookmark-jump-unhide ()
28535 "Unhide the current position, to show the bookmark location."
28536 (and (org-mode-p)
28537 (or (org-invisible-p)
28538 (save-excursion (goto-char (max (point-min) (1- (point))))
28539 (org-invisible-p)))
28540 (org-show-context 'bookmark-jump)))
28542 ;; Fix a bug in htmlize where there are text properties (face nil)
28543 (eval-after-load "htmlize"
28544 '(progn
28545 (defadvice htmlize-faces-in-buffer (after org-no-nil-faces activate)
28546 "Make sure there are no nil faces"
28547 (setq ad-return-value (delq nil ad-return-value)))))
28549 ;; Make session.el ignore our circular variable
28550 (eval-after-load "session"
28551 '(add-to-list 'session-globals-exclude 'org-mark-ring))
28553 ;;;; Experimental code
28555 (defun org-closed-in-range ()
28556 "Sparse tree of items closed in a certain time range.
28557 Still experimental, may disappear in the future."
28558 (interactive)
28559 ;; Get the time interval from the user.
28560 (let* ((time1 (time-to-seconds
28561 (org-read-date nil 'to-time nil "Starting date: ")))
28562 (time2 (time-to-seconds
28563 (org-read-date nil 'to-time nil "End date:")))
28564 ;; callback function
28565 (callback (lambda ()
28566 (let ((time
28567 (time-to-seconds
28568 (apply 'encode-time
28569 (org-parse-time-string
28570 (match-string 1))))))
28571 ;; check if time in interval
28572 (and (>= time time1) (<= time time2))))))
28573 ;; make tree, check each match with the callback
28574 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
28576 ;;;; Finish up
28578 (provide 'org)
28580 (run-hooks 'org-load-hook)
28582 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
28583 ;;; org.el ends here