Implementing search view.
[org-mode.git] / org.el
blob88849e4c4ef2cd982616bdd1b1cf0006ef850e55
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)
175 (defun org-load-default-extensions ()
176 "Load all extensions that are listed in `org-default-extensions'."
177 (mapc 'require org-default-extensions))
179 ;; FIXME: Needs a separate group...
180 (defcustom org-completion-fallback-command 'hippie-expand
181 "The expansion command called by \\[org-complete] in normal context.
182 Normal means, no org-mode-specific context."
183 :group 'org
184 :type 'function)
186 (defgroup org-startup nil
187 "Options concerning startup of Org-mode."
188 :tag "Org Startup"
189 :group 'org)
191 (defcustom org-startup-folded t
192 "Non-nil means, entering Org-mode will switch to OVERVIEW.
193 This can also be configured on a per-file basis by adding one of
194 the following lines anywhere in the buffer:
196 #+STARTUP: fold
197 #+STARTUP: nofold
198 #+STARTUP: content"
199 :group 'org-startup
200 :type '(choice
201 (const :tag "nofold: show all" nil)
202 (const :tag "fold: overview" t)
203 (const :tag "content: all headlines" content)))
205 (defcustom org-startup-truncated t
206 "Non-nil means, entering Org-mode will set `truncate-lines'.
207 This is useful since some lines containing links can be very long and
208 uninteresting. Also tables look terrible when wrapped."
209 :group 'org-startup
210 :type 'boolean)
212 (defcustom org-startup-align-all-tables nil
213 "Non-nil means, align all tables when visiting a file.
214 This is useful when the column width in tables is forced with <N> cookies
215 in table fields. Such tables will look correct only after the first re-align.
216 This can also be configured on a per-file basis by adding one of
217 the following lines anywhere in the buffer:
218 #+STARTUP: align
219 #+STARTUP: noalign"
220 :group 'org-startup
221 :type 'boolean)
223 (defcustom org-insert-mode-line-in-empty-file nil
224 "Non-nil means insert the first line setting Org-mode in empty files.
225 When the function `org-mode' is called interactively in an empty file, this
226 normally means that the file name does not automatically trigger Org-mode.
227 To ensure that the file will always be in Org-mode in the future, a
228 line enforcing Org-mode will be inserted into the buffer, if this option
229 has been set."
230 :group 'org-startup
231 :type 'boolean)
233 (defcustom org-replace-disputed-keys nil
234 "Non-nil means use alternative key bindings for some keys.
235 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
236 These keys are also used by other packages like `CUA-mode' or `windmove.el'.
237 If you want to use Org-mode together with one of these other modes,
238 or more generally if you would like to move some Org-mode commands to
239 other keys, set this variable and configure the keys with the variable
240 `org-disputed-keys'.
242 This option is only relevant at load-time of Org-mode, and must be set
243 *before* org.el is loaded. Changing it requires a restart of Emacs to
244 become effective."
245 :group 'org-startup
246 :type 'boolean)
248 (if (fboundp 'defvaralias)
249 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys))
251 (defcustom org-disputed-keys
252 '(([(shift up)] . [(meta p)])
253 ([(shift down)] . [(meta n)])
254 ([(shift left)] . [(meta -)])
255 ([(shift right)] . [(meta +)])
256 ([(control shift right)] . [(meta shift +)])
257 ([(control shift left)] . [(meta shift -)]))
258 "Keys for which Org-mode and other modes compete.
259 This is an alist, cars are the default keys, second element specifies
260 the alternative to use when `org-replace-disputed-keys' is t.
262 Keys can be specified in any syntax supported by `define-key'.
263 The value of this option takes effect only at Org-mode's startup,
264 therefore you'll have to restart Emacs to apply it after changing."
265 :group 'org-startup
266 :type 'alist)
268 (defun org-key (key)
269 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
270 Or return the original if not disputed."
271 (if org-replace-disputed-keys
272 (let* ((nkey (key-description key))
273 (x (org-find-if (lambda (x)
274 (equal (key-description (car x)) nkey))
275 org-disputed-keys)))
276 (if x (cdr x) key))
277 key))
279 (defun org-find-if (predicate seq)
280 (catch 'exit
281 (while seq
282 (if (funcall predicate (car seq))
283 (throw 'exit (car seq))
284 (pop seq)))))
286 (defun org-defkey (keymap key def)
287 "Define a key, possibly translated, as returned by `org-key'."
288 (define-key keymap (org-key key) def))
290 (defcustom org-ellipsis nil
291 "The ellipsis to use in the Org-mode outline.
292 When nil, just use the standard three dots. When a string, use that instead,
293 When a face, use the standart 3 dots, but with the specified face.
294 The change affects only Org-mode (which will then use its own display table).
295 Changing this requires executing `M-x org-mode' in a buffer to become
296 effective."
297 :group 'org-startup
298 :type '(choice (const :tag "Default" nil)
299 (face :tag "Face" :value org-warning)
300 (string :tag "String" :value "...#")))
302 (defvar org-display-table nil
303 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
305 (defgroup org-keywords nil
306 "Keywords in Org-mode."
307 :tag "Org Keywords"
308 :group 'org)
310 (defcustom org-deadline-string "DEADLINE:"
311 "String to mark deadline entries.
312 A deadline is this string, followed by a time stamp. Should be a word,
313 terminated by a colon. You can insert a schedule keyword and
314 a timestamp with \\[org-deadline].
315 Changes become only effective after restarting Emacs."
316 :group 'org-keywords
317 :type 'string)
319 (defcustom org-scheduled-string "SCHEDULED:"
320 "String to mark scheduled TODO entries.
321 A schedule is this string, followed by a time stamp. Should be a word,
322 terminated by a colon. You can insert a schedule keyword and
323 a timestamp with \\[org-schedule].
324 Changes become only effective after restarting Emacs."
325 :group 'org-keywords
326 :type 'string)
328 (defcustom org-closed-string "CLOSED:"
329 "String used as the prefix for timestamps logging closing a TODO entry."
330 :group 'org-keywords
331 :type 'string)
333 (defcustom org-clock-string "CLOCK:"
334 "String used as prefix for timestamps clocking work hours on an item."
335 :group 'org-keywords
336 :type 'string)
338 (defcustom org-comment-string "COMMENT"
339 "Entries starting with this keyword will never be exported.
340 An entry can be toggled between COMMENT and normal with
341 \\[org-toggle-comment].
342 Changes become only effective after restarting Emacs."
343 :group 'org-keywords
344 :type 'string)
346 (defcustom org-quote-string "QUOTE"
347 "Entries starting with this keyword will be exported in fixed-width font.
348 Quoting applies only to the text in the entry following the headline, and does
349 not extend beyond the next headline, even if that is lower level.
350 An entry can be toggled between QUOTE and normal with
351 \\[org-toggle-fixed-width-section]."
352 :group 'org-keywords
353 :type 'string)
355 (defconst org-repeat-re
356 ; (concat "\\(?:\\<\\(?:" org-scheduled-string "\\|" org-deadline-string "\\)"
357 ; " +<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*\\)\\(\\+[0-9]+[dwmy]\\)")
358 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*\\(\\+[0-9]+[dwmy]\\)"
359 "Regular expression for specifying repeated events.
360 After a match, group 1 contains the repeat expression.")
362 (defgroup org-structure nil
363 "Options concerning the general structure of Org-mode files."
364 :tag "Org Structure"
365 :group 'org)
367 (defgroup org-reveal-location nil
368 "Options about how to make context of a location visible."
369 :tag "Org Reveal Location"
370 :group 'org-structure)
372 (defconst org-context-choice
373 '(choice
374 (const :tag "Always" t)
375 (const :tag "Never" nil)
376 (repeat :greedy t :tag "Individual contexts"
377 (cons
378 (choice :tag "Context"
379 (const agenda)
380 (const org-goto)
381 (const occur-tree)
382 (const tags-tree)
383 (const link-search)
384 (const mark-goto)
385 (const bookmark-jump)
386 (const isearch)
387 (const default))
388 (boolean))))
389 "Contexts for the reveal options.")
391 (defcustom org-show-hierarchy-above '((default . t))
392 "Non-nil means, show full hierarchy when revealing a location.
393 Org-mode often shows locations in an org-mode file which might have
394 been invisible before. When this is set, the hierarchy of headings
395 above the exposed location is shown.
396 Turning this off for example for sparse trees makes them very compact.
397 Instead of t, this can also be an alist specifying this option for different
398 contexts. Valid contexts are
399 agenda when exposing an entry from the agenda
400 org-goto when using the command `org-goto' on key C-c C-j
401 occur-tree when using the command `org-occur' on key C-c /
402 tags-tree when constructing a sparse tree based on tags matches
403 link-search when exposing search matches associated with a link
404 mark-goto when exposing the jump goal of a mark
405 bookmark-jump when exposing a bookmark location
406 isearch when exiting from an incremental search
407 default default for all contexts not set explicitly"
408 :group 'org-reveal-location
409 :type org-context-choice)
411 (defcustom org-show-following-heading '((default . nil))
412 "Non-nil means, show following heading when revealing a location.
413 Org-mode often shows locations in an org-mode file which might have
414 been invisible before. When this is set, the heading following the
415 match is shown.
416 Turning this off for example for sparse trees makes them very compact,
417 but makes it harder to edit the location of the match. In such a case,
418 use the command \\[org-reveal] to show more context.
419 Instead of t, this can also be an alist specifying this option for different
420 contexts. See `org-show-hierarchy-above' for valid contexts."
421 :group 'org-reveal-location
422 :type org-context-choice)
424 (defcustom org-show-siblings '((default . nil) (isearch t))
425 "Non-nil means, show all sibling heading when revealing a location.
426 Org-mode often shows locations in an org-mode file which might have
427 been invisible before. When this is set, the sibling of the current entry
428 heading are all made visible. If `org-show-hierarchy-above' is t,
429 the same happens on each level of the hierarchy above the current entry.
431 By default this is on for the isearch context, off for all other contexts.
432 Turning this off for example for sparse trees makes them very compact,
433 but makes it harder to edit the location of the match. In such a case,
434 use the command \\[org-reveal] to show more context.
435 Instead of t, this can also be an alist specifying this option for different
436 contexts. See `org-show-hierarchy-above' for valid contexts."
437 :group 'org-reveal-location
438 :type org-context-choice)
440 (defcustom org-show-entry-below '((default . nil))
441 "Non-nil means, show the entry below a headline when revealing a location.
442 Org-mode often shows locations in an org-mode file which might have
443 been invisible before. When this is set, the text below the headline that is
444 exposed is also shown.
446 By default this is off for all contexts.
447 Instead of t, this can also be an alist specifying this option for different
448 contexts. See `org-show-hierarchy-above' for valid contexts."
449 :group 'org-reveal-location
450 :type org-context-choice)
452 (defgroup org-cycle nil
453 "Options concerning visibility cycling in Org-mode."
454 :tag "Org Cycle"
455 :group 'org-structure)
457 (defcustom org-drawers '("PROPERTIES" "CLOCK")
458 "Names of drawers. Drawers are not opened by cycling on the headline above.
459 Drawers only open with a TAB on the drawer line itself. A drawer looks like
460 this:
461 :DRAWERNAME:
462 .....
463 :END:
464 The drawer \"PROPERTIES\" is special for capturing properties through
465 the property API.
467 Drawers can be defined on the per-file basis with a line like:
469 #+DRAWERS: HIDDEN STATE PROPERTIES"
470 :group 'org-structure
471 :type '(repeat (string :tag "Drawer Name")))
473 (defcustom org-cycle-global-at-bob nil
474 "Cycle globally if cursor is at beginning of buffer and not at a headline.
475 This makes it possible to do global cycling without having to use S-TAB or
476 C-u TAB. For this special case to work, the first line of the buffer
477 must not be a headline - it may be empty ot some other text. When used in
478 this way, `org-cycle-hook' is disables temporarily, to make sure the
479 cursor stays at the beginning of the buffer.
480 When this option is nil, don't do anything special at the beginning
481 of the buffer."
482 :group 'org-cycle
483 :type 'boolean)
485 (defcustom org-cycle-emulate-tab t
486 "Where should `org-cycle' emulate TAB.
487 nil Never
488 white Only in completely white lines
489 whitestart Only at the beginning of lines, before the first non-white char
490 t Everywhere except in headlines
491 exc-hl-bol Everywhere except at the start of a headline
492 If TAB is used in a place where it does not emulate TAB, the current subtree
493 visibility is cycled."
494 :group 'org-cycle
495 :type '(choice (const :tag "Never" nil)
496 (const :tag "Only in completely white lines" white)
497 (const :tag "Before first char in a line" whitestart)
498 (const :tag "Everywhere except in headlines" t)
499 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)
502 (defcustom org-cycle-separator-lines 2
503 "Number of empty lines needed to keep an empty line between collapsed trees.
504 If you leave an empty line between the end of a subtree and the following
505 headline, this empty line is hidden when the subtree is folded.
506 Org-mode will leave (exactly) one empty line visible if the number of
507 empty lines is equal or larger to the number given in this variable.
508 So the default 2 means, at least 2 empty lines after the end of a subtree
509 are needed to produce free space between a collapsed subtree and the
510 following headline.
512 Special case: when 0, never leave empty lines in collapsed view."
513 :group 'org-cycle
514 :type 'integer)
516 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
517 org-cycle-hide-drawers
518 org-cycle-show-empty-lines
519 org-optimize-window-after-visibility-change)
520 "Hook that is run after `org-cycle' has changed the buffer visibility.
521 The function(s) in this hook must accept a single argument which indicates
522 the new state that was set by the most recent `org-cycle' command. The
523 argument is a symbol. After a global state change, it can have the values
524 `overview', `content', or `all'. After a local state change, it can have
525 the values `folded', `children', or `subtree'."
526 :group 'org-cycle
527 :type 'hook)
529 (defgroup org-edit-structure nil
530 "Options concerning structure editing in Org-mode."
531 :tag "Org Edit Structure"
532 :group 'org-structure)
534 (defcustom org-odd-levels-only nil
535 "Non-nil means, skip even levels and only use odd levels for the outline.
536 This has the effect that two stars are being added/taken away in
537 promotion/demotion commands. It also influences how levels are
538 handled by the exporters.
539 Changing it requires restart of `font-lock-mode' to become effective
540 for fontification also in regions already fontified.
541 You may also set this on a per-file basis by adding one of the following
542 lines to the buffer:
544 #+STARTUP: odd
545 #+STARTUP: oddeven"
546 :group 'org-edit-structure
547 :group 'org-font-lock
548 :type 'boolean)
550 (defcustom org-adapt-indentation t
551 "Non-nil means, adapt indentation when promoting and demoting.
552 When this is set and the *entire* text in an entry is indented, the
553 indentation is increased by one space in a demotion command, and
554 decreased by one in a promotion command. If any line in the entry
555 body starts at column 0, indentation is not changed at all."
556 :group 'org-edit-structure
557 :type 'boolean)
559 (defcustom org-special-ctrl-a/e nil
560 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
561 When t, `C-a' will bring back the cursor to the beginning of the
562 headline text, i.e. after the stars and after a possible TODO keyword.
563 In an item, this will be the position after the bullet.
564 When the cursor is already at that position, another `C-a' will bring
565 it to the beginning of the line.
566 `C-e' will jump to the end of the headline, ignoring the presence of tags
567 in the headline. A second `C-e' will then jump to the true end of the
568 line, after any tags.
569 When set to the symbol `reversed', the first `C-a' or `C-e' works normally,
570 and only a directly following, identical keypress will bring the cursor
571 to the special positions."
572 :group 'org-edit-structure
573 :type '(choice
574 (const :tag "off" nil)
575 (const :tag "after bullet first" t)
576 (const :tag "border first" reversed)))
578 (if (fboundp 'defvaralias)
579 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e))
581 (defcustom org-special-ctrl-k nil
582 "Non-nil means `C-k' will behave specially in headlines.
583 When nil, `C-k' will call the default `kill-line' command.
584 When t, the following will happen while the cursor is in the headline:
586 - When the cursor is at the beginning of a headline, kill the entire
587 line and possible the folded subtree below the line.
588 - When in the middle of the headline text, kill the headline up to the tags.
589 - When after the headline text, kill the tags."
590 :group 'org-edit-structure
591 :type 'boolean)
593 (defcustom org-M-RET-may-split-line '((default . t))
594 "Non-nil means, M-RET will split the line at the cursor position.
595 When nil, it will go to the end of the line before making a
596 new line.
597 You may also set this option in a different way for different
598 contexts. Valid contexts are:
600 headline when creating a new headline
601 item when creating a new item
602 table in a table field
603 default the value to be used for all contexts not explicitly
604 customized"
605 :group 'org-structure
606 :group 'org-table
607 :type '(choice
608 (const :tag "Always" t)
609 (const :tag "Never" nil)
610 (repeat :greedy t :tag "Individual contexts"
611 (cons
612 (choice :tag "Context"
613 (const headline)
614 (const item)
615 (const table)
616 (const default))
617 (boolean)))))
620 (defcustom org-blank-before-new-entry '((heading . nil)
621 (plain-list-item . nil))
622 "Should `org-insert-heading' leave a blank line before new heading/item?
623 The value is an alist, with `heading' and `plain-list-item' as car,
624 and a boolean flag as cdr."
625 :group 'org-edit-structure
626 :type '(list
627 (cons (const heading) (boolean))
628 (cons (const plain-list-item) (boolean))))
630 (defcustom org-insert-heading-hook nil
631 "Hook being run after inserting a new heading."
632 :group 'org-edit-structure
633 :type 'hook)
635 (defcustom org-enable-fixed-width-editor t
636 "Non-nil means, lines starting with \":\" are treated as fixed-width.
637 This currently only means, they are never auto-wrapped.
638 When nil, such lines will be treated like ordinary lines.
639 See also the QUOTE keyword."
640 :group 'org-edit-structure
641 :type 'boolean)
643 (defcustom org-goto-auto-isearch t
644 "Non-nil means, typing characters in org-goto starts incremental search."
645 :group 'org-edit-structure
646 :type 'boolean)
648 (defgroup org-sparse-trees nil
649 "Options concerning sparse trees in Org-mode."
650 :tag "Org Sparse Trees"
651 :group 'org-structure)
653 (defcustom org-highlight-sparse-tree-matches t
654 "Non-nil means, highlight all matches that define a sparse tree.
655 The highlights will automatically disappear the next time the buffer is
656 changed by an edit command."
657 :group 'org-sparse-trees
658 :type 'boolean)
660 (defcustom org-remove-highlights-with-change t
661 "Non-nil means, any change to the buffer will remove temporary highlights.
662 Such highlights are created by `org-occur' and `org-clock-display'.
663 When nil, `C-c C-c needs to be used to get rid of the highlights.
664 The highlights created by `org-preview-latex-fragment' always need
665 `C-c C-c' to be removed."
666 :group 'org-sparse-trees
667 :group 'org-time
668 :type 'boolean)
671 (defcustom org-occur-hook '(org-first-headline-recenter)
672 "Hook that is run after `org-occur' has constructed a sparse tree.
673 This can be used to recenter the window to show as much of the structure
674 as possible."
675 :group 'org-sparse-trees
676 :type 'hook)
678 (defgroup org-plain-lists nil
679 "Options concerning plain lists in Org-mode."
680 :tag "Org Plain lists"
681 :group 'org-structure)
683 (defcustom org-cycle-include-plain-lists nil
684 "Non-nil means, include plain lists into visibility cycling.
685 This means that during cycling, plain list items will *temporarily* be
686 interpreted as outline headlines with a level given by 1000+i where i is the
687 indentation of the bullet. In all other operations, plain list items are
688 not seen as headlines. For example, you cannot assign a TODO keyword to
689 such an item."
690 :group 'org-plain-lists
691 :type 'boolean)
693 (defcustom org-plain-list-ordered-item-terminator t
694 "The character that makes a line with leading number an ordered list item.
695 Valid values are ?. and ?\). To get both terminators, use t. While
696 ?. may look nicer, it creates the danger that a line with leading
697 number may be incorrectly interpreted as an item. ?\) therefore is
698 the safe choice."
699 :group 'org-plain-lists
700 :type '(choice (const :tag "dot like in \"2.\"" ?.)
701 (const :tag "paren like in \"2)\"" ?\))
702 (const :tab "both" t)))
704 (defcustom org-auto-renumber-ordered-lists t
705 "Non-nil means, automatically renumber ordered plain lists.
706 Renumbering happens when the sequence have been changed with
707 \\[org-shiftmetaup] or \\[org-shiftmetadown]. After other editing commands,
708 use \\[org-ctrl-c-ctrl-c] to trigger renumbering."
709 :group 'org-plain-lists
710 :type 'boolean)
712 (defcustom org-provide-checkbox-statistics t
713 "Non-nil means, update checkbox statistics after insert and toggle.
714 When this is set, checkbox statistics is updated each time you either insert
715 a new checkbox with \\[org-insert-todo-heading] or toggle a checkbox
716 with \\[org-ctrl-c-ctrl-c\\]."
717 :group 'org-plain-lists
718 :type 'boolean)
720 (defgroup org-archive nil
721 "Options concerning archiving in Org-mode."
722 :tag "Org Archive"
723 :group 'org-structure)
725 (defcustom org-archive-tag "ARCHIVE"
726 "The tag that marks a subtree as archived.
727 An archived subtree does not open during visibility cycling, and does
728 not contribute to the agenda listings.
729 After changing this, font-lock must be restarted in the relevant buffers to
730 get the proper fontification."
731 :group 'org-archive
732 :group 'org-keywords
733 :type 'string)
735 (defcustom org-agenda-skip-archived-trees t
736 "Non-nil means, the agenda will skip any items located in archived trees.
737 An archived tree is a tree marked with the tag ARCHIVE."
738 :group 'org-archive
739 :group 'org-agenda-skip
740 :type 'boolean)
742 (defcustom org-cycle-open-archived-trees nil
743 "Non-nil means, `org-cycle' will open archived trees.
744 An archived tree is a tree marked with the tag ARCHIVE.
745 When nil, archived trees will stay folded. You can still open them with
746 normal outline commands like `show-all', but not with the cycling commands."
747 :group 'org-archive
748 :group 'org-cycle
749 :type 'boolean)
751 (defcustom org-sparse-tree-open-archived-trees nil
752 "Non-nil means sparse tree construction shows matches in archived trees.
753 When nil, matches in these trees are highlighted, but the trees are kept in
754 collapsed state."
755 :group 'org-archive
756 :group 'org-sparse-trees
757 :type 'boolean)
759 (defcustom org-archive-location "%s_archive::"
760 "The location where subtrees should be archived.
761 This string consists of two parts, separated by a double-colon.
763 The first part is a file name - when omitted, archiving happens in the same
764 file. %s will be replaced by the current file name (without directory part).
765 Archiving to a different file is useful to keep archived entries from
766 contributing to the Org-mode Agenda.
768 The part after the double colon is a headline. The archived entries will be
769 filed under that headline. When omitted, the subtrees are simply filed away
770 at the end of the file, as top-level entries.
772 Here are a few examples:
773 \"%s_archive::\"
774 If the current file is Projects.org, archive in file
775 Projects.org_archive, as top-level trees. This is the default.
777 \"::* Archived Tasks\"
778 Archive in the current file, under the top-level headline
779 \"* Archived Tasks\".
781 \"~/org/archive.org::\"
782 Archive in file ~/org/archive.org (absolute path), as top-level trees.
784 \"basement::** Finished Tasks\"
785 Archive in file ./basement (relative path), as level 3 trees
786 below the level 2 heading \"** Finished Tasks\".
788 You may set this option on a per-file basis by adding to the buffer a
789 line like
791 #+ARCHIVE: basement::** Finished Tasks"
792 :group 'org-archive
793 :type 'string)
795 (defcustom org-archive-mark-done t
796 "Non-nil means, mark entries as DONE when they are moved to the archive file.
797 This can be a string to set the keyword to use. When t, Org-mode will
798 use the first keyword in its list that means done."
799 :group 'org-archive
800 :type '(choice
801 (const :tag "No" nil)
802 (const :tag "Yes" t)
803 (string :tag "Use this keyword")))
805 (defcustom org-archive-stamp-time t
806 "Non-nil means, add a time stamp to entries moved to an archive file.
807 This variable is obsolete and has no effect anymore, instead add ot remove
808 `time' from the variablle `org-archive-save-context-info'."
809 :group 'org-archive
810 :type 'boolean)
812 (defcustom org-archive-save-context-info '(time file olpath category todo itags)
813 "Parts of context info that should be stored as properties when archiving.
814 When a subtree is moved to an archive file, it looses information given by
815 context, like inherited tags, the category, and possibly also the TODO
816 state (depending on the variable `org-archive-mark-done').
817 This variable can be a list of any of the following symbols:
819 time The time of archiving.
820 file The file where the entry originates.
821 itags The local tags, in the headline of the subtree.
822 ltags The tags the subtree inherits from further up the hierarchy.
823 todo The pre-archive TODO state.
824 category The category, taken from file name or #+CATEGORY lines.
825 olpath The outline path to the item. These are all headlines above
826 the current item, separated by /, like a file path.
828 For each symbol present in the list, a property will be created in
829 the archived entry, with a prefix \"PRE_ARCHIVE_\", to remember this
830 information."
831 :group 'org-archive
832 :type '(set :greedy t
833 (const :tag "Time" time)
834 (const :tag "File" file)
835 (const :tag "Category" category)
836 (const :tag "TODO state" todo)
837 (const :tag "TODO state" priority)
838 (const :tag "Inherited tags" itags)
839 (const :tag "Outline path" olpath)
840 (const :tag "Local tags" ltags)))
842 (defgroup org-imenu-and-speedbar nil
843 "Options concerning imenu and speedbar in Org-mode."
844 :tag "Org Imenu and Speedbar"
845 :group 'org-structure)
847 (defcustom org-imenu-depth 2
848 "The maximum level for Imenu access to Org-mode headlines.
849 This also applied for speedbar access."
850 :group 'org-imenu-and-speedbar
851 :type 'number)
853 (defgroup org-table nil
854 "Options concerning tables in Org-mode."
855 :tag "Org Table"
856 :group 'org)
858 (defcustom org-enable-table-editor 'optimized
859 "Non-nil means, lines starting with \"|\" are handled by the table editor.
860 When nil, such lines will be treated like ordinary lines.
862 When equal to the symbol `optimized', the table editor will be optimized to
863 do the following:
864 - Automatic overwrite mode in front of whitespace in table fields.
865 This makes the structure of the table stay in tact as long as the edited
866 field does not exceed the column width.
867 - Minimize the number of realigns. Normally, the table is aligned each time
868 TAB or RET are pressed to move to another field. With optimization this
869 happens only if changes to a field might have changed the column width.
870 Optimization requires replacing the functions `self-insert-command',
871 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
872 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
873 very good at guessing when a re-align will be necessary, but you can always
874 force one with \\[org-ctrl-c-ctrl-c].
876 If you would like to use the optimized version in Org-mode, but the
877 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
879 This variable can be used to turn on and off the table editor during a session,
880 but in order to toggle optimization, a restart is required.
882 See also the variable `org-table-auto-blank-field'."
883 :group 'org-table
884 :type '(choice
885 (const :tag "off" nil)
886 (const :tag "on" t)
887 (const :tag "on, optimized" optimized)))
889 (defcustom orgtbl-optimized (eq org-enable-table-editor 'optimized)
890 "Non-nil means, use the optimized table editor version for `orgtbl-mode'.
891 In the optimized version, the table editor takes over all simple keys that
892 normally just insert a character. In tables, the characters are inserted
893 in a way to minimize disturbing the table structure (i.e. in overwrite mode
894 for empty fields). Outside tables, the correct binding of the keys is
895 restored.
897 The default for this option is t if the optimized version is also used in
898 Org-mode. See the variable `org-enable-table-editor' for details. Changing
899 this variable requires a restart of Emacs to become effective."
900 :group 'org-table
901 :type 'boolean)
903 (defcustom orgtbl-radio-table-templates
904 '((latex-mode "% BEGIN RECEIVE ORGTBL %n
905 % END RECEIVE ORGTBL %n
906 \\begin{comment}
907 #+ORGTBL: SEND %n orgtbl-to-latex :splice nil :skip 0
908 | | |
909 \\end{comment}\n")
910 (texinfo-mode "@c BEGIN RECEIVE ORGTBL %n
911 @c END RECEIVE ORGTBL %n
912 @ignore
913 #+ORGTBL: SEND %n orgtbl-to-html :splice nil :skip 0
914 | | |
915 @end ignore\n")
916 (html-mode "<!-- BEGIN RECEIVE ORGTBL %n -->
917 <!-- END RECEIVE ORGTBL %n -->
918 <!--
919 #+ORGTBL: SEND %n orgtbl-to-html :splice nil :skip 0
920 | | |
921 -->\n"))
922 "Templates for radio tables in different major modes.
923 All occurrences of %n in a template will be replaced with the name of the
924 table, obtained by prompting the user."
925 :group 'org-table
926 :type '(repeat
927 (list (symbol :tag "Major mode")
928 (string :tag "Format"))))
930 (defgroup org-table-settings nil
931 "Settings for tables in Org-mode."
932 :tag "Org Table Settings"
933 :group 'org-table)
935 (defcustom org-table-default-size "5x2"
936 "The default size for newly created tables, Columns x Rows."
937 :group 'org-table-settings
938 :type 'string)
940 (defcustom org-table-number-regexp
941 "^\\([<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%:]*\\|\\(0[xX]\\)[0-9a-fA-F]+\\|nan\\)$"
942 "Regular expression for recognizing numbers in table columns.
943 If a table column contains mostly numbers, it will be aligned to the
944 right. If not, it will be aligned to the left.
946 The default value of this option is a regular expression which allows
947 anything which looks remotely like a number as used in scientific
948 context. For example, all of the following will be considered a
949 number:
950 12 12.2 2.4e-08 2x10^12 4.034+-0.02 2.7(10) >3.5
952 Other options offered by the customize interface are more restrictive."
953 :group 'org-table-settings
954 :type '(choice
955 (const :tag "Positive Integers"
956 "^[0-9]+$")
957 (const :tag "Integers"
958 "^[-+]?[0-9]+$")
959 (const :tag "Floating Point Numbers"
960 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.[0-9]*\\)$")
961 (const :tag "Floating Point Number or Integer"
962 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.?[0-9]*\\)$")
963 (const :tag "Exponential, Floating point, Integer"
964 "^[-+]?[0-9.]+\\([eEdD][-+0-9]+\\)?$")
965 (const :tag "Very General Number-Like, including hex"
966 "^\\([<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%]*\\|\\(0[xX]\\)[0-9a-fA-F]+\\|nan\\)$")
967 (string :tag "Regexp:")))
969 (defcustom org-table-number-fraction 0.5
970 "Fraction of numbers in a column required to make the column align right.
971 In a column all non-white fields are considered. If at least this
972 fraction of fields is matched by `org-table-number-fraction',
973 alignment to the right border applies."
974 :group 'org-table-settings
975 :type 'number)
977 (defgroup org-table-editing nil
978 "Behavior of tables during editing in Org-mode."
979 :tag "Org Table Editing"
980 :group 'org-table)
982 (defcustom org-table-automatic-realign t
983 "Non-nil means, automatically re-align table when pressing TAB or RETURN.
984 When nil, aligning is only done with \\[org-table-align], or after column
985 removal/insertion."
986 :group 'org-table-editing
987 :type 'boolean)
989 (defcustom org-table-auto-blank-field t
990 "Non-nil means, automatically blank table field when starting to type into it.
991 This only happens when typing immediately after a field motion
992 command (TAB, S-TAB or RET).
993 Only relevant when `org-enable-table-editor' is equal to `optimized'."
994 :group 'org-table-editing
995 :type 'boolean)
997 (defcustom org-table-tab-jumps-over-hlines t
998 "Non-nil means, tab in the last column of a table with jump over a hline.
999 If a horizontal separator line is following the current line,
1000 `org-table-next-field' can either create a new row before that line, or jump
1001 over the line. When this option is nil, a new line will be created before
1002 this line."
1003 :group 'org-table-editing
1004 :type 'boolean)
1006 (defcustom org-table-tab-recognizes-table.el t
1007 "Non-nil means, TAB will automatically notice a table.el table.
1008 When it sees such a table, it moves point into it and - if necessary -
1009 calls `table-recognize-table'."
1010 :group 'org-table-editing
1011 :type 'boolean)
1013 (defgroup org-table-calculation nil
1014 "Options concerning tables in Org-mode."
1015 :tag "Org Table Calculation"
1016 :group 'org-table)
1018 (defcustom org-table-use-standard-references t
1019 "Should org-mode work with table refrences like B3 instead of @3$2?
1020 Possible values are:
1021 nil never use them
1022 from accept as input, do not present for editing
1023 t: accept as input and present for editing"
1024 :group 'org-table-calculation
1025 :type '(choice
1026 (const :tag "Never, don't even check unser input for them" nil)
1027 (const :tag "Always, both as user input, and when editing" t)
1028 (const :tag "Convert user input, don't offer during editing" 'from)))
1030 (defcustom org-table-copy-increment t
1031 "Non-nil means, increment when copying current field with \\[org-table-copy-down]."
1032 :group 'org-table-calculation
1033 :type 'boolean)
1035 (defcustom org-calc-default-modes
1036 '(calc-internal-prec 12
1037 calc-float-format (float 5)
1038 calc-angle-mode deg
1039 calc-prefer-frac nil
1040 calc-symbolic-mode nil
1041 calc-date-format (YYYY "-" MM "-" DD " " Www (" " HH ":" mm))
1042 calc-display-working-message t
1044 "List with Calc mode settings for use in calc-eval for table formulas.
1045 The list must contain alternating symbols (Calc modes variables and values).
1046 Don't remove any of the default settings, just change the values. Org-mode
1047 relies on the variables to be present in the list."
1048 :group 'org-table-calculation
1049 :type 'plist)
1051 (defcustom org-table-formula-evaluate-inline t
1052 "Non-nil means, TAB and RET evaluate a formula in current table field.
1053 If the current field starts with an equal sign, it is assumed to be a formula
1054 which should be evaluated as described in the manual and in the documentation
1055 string of the command `org-table-eval-formula'. This feature requires the
1056 Emacs calc package.
1057 When this variable is nil, formula calculation is only available through
1058 the command \\[org-table-eval-formula]."
1059 :group 'org-table-calculation
1060 :type 'boolean)
1062 (defcustom org-table-formula-use-constants t
1063 "Non-nil means, interpret constants in formulas in tables.
1064 A constant looks like `$c' or `$Grav' and will be replaced before evaluation
1065 by the value given in `org-table-formula-constants', or by a value obtained
1066 from the `constants.el' package."
1067 :group 'org-table-calculation
1068 :type 'boolean)
1070 (defcustom org-table-formula-constants nil
1071 "Alist with constant names and values, for use in table formulas.
1072 The car of each element is a name of a constant, without the `$' before it.
1073 The cdr is the value as a string. For example, if you'd like to use the
1074 speed of light in a formula, you would configure
1076 (setq org-table-formula-constants '((\"c\" . \"299792458.\")))
1078 and then use it in an equation like `$1*$c'.
1080 Constants can also be defined on a per-file basis using a line like
1082 #+CONSTANTS: c=299792458. pi=3.14 eps=2.4e-6"
1083 :group 'org-table-calculation
1084 :type '(repeat
1085 (cons (string :tag "name")
1086 (string :tag "value"))))
1088 (defvar org-table-formula-constants-local nil
1089 "Local version of `org-table-formula-constants'.")
1090 (make-variable-buffer-local 'org-table-formula-constants-local)
1092 (defcustom org-table-allow-automatic-line-recalculation t
1093 "Non-nil means, lines marked with |#| or |*| will be recomputed automatically.
1094 Automatically means, when TAB or RET or C-c C-c are pressed in the line."
1095 :group 'org-table-calculation
1096 :type 'boolean)
1098 (defgroup org-link nil
1099 "Options concerning links in Org-mode."
1100 :tag "Org Link"
1101 :group 'org)
1103 (defvar org-link-abbrev-alist-local nil
1104 "Buffer-local version of `org-link-abbrev-alist', which see.
1105 The value of this is taken from the #+LINK lines.")
1106 (make-variable-buffer-local 'org-link-abbrev-alist-local)
1108 (defcustom org-link-abbrev-alist nil
1109 "Alist of link abbreviations.
1110 The car of each element is a string, to be replaced at the start of a link.
1111 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1112 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1114 [[linkkey:tag][description]]
1116 If REPLACE is a string, the tag will simply be appended to create the link.
1117 If the string contains \"%s\", the tag will be inserted there.
1119 REPLACE may also be a function that will be called with the tag as the
1120 only argument to create the link, which should be returned as a string.
1122 See the manual for examples."
1123 :group 'org-link
1124 :type 'alist)
1126 (defcustom org-descriptive-links t
1127 "Non-nil means, hide link part and only show description of bracket links.
1128 Bracket links are like [[link][descritpion]]. This variable sets the initial
1129 state in new org-mode buffers. The setting can then be toggled on a
1130 per-buffer basis from the Org->Hyperlinks menu."
1131 :group 'org-link
1132 :type 'boolean)
1134 (defcustom org-link-file-path-type 'adaptive
1135 "How the path name in file links should be stored.
1136 Valid values are:
1138 relative Relative to the current directory, i.e. the directory of the file
1139 into which the link is being inserted.
1140 absolute Absolute path, if possible with ~ for home directory.
1141 noabbrev Absolute path, no abbreviation of home directory.
1142 adaptive Use relative path for files in the current directory and sub-
1143 directories of it. For other files, use an absolute path."
1144 :group 'org-link
1145 :type '(choice
1146 (const relative)
1147 (const absolute)
1148 (const noabbrev)
1149 (const adaptive)))
1151 (defcustom org-activate-links '(bracket angle plain radio tag date)
1152 "Types of links that should be activated in Org-mode files.
1153 This is a list of symbols, each leading to the activation of a certain link
1154 type. In principle, it does not hurt to turn on most link types - there may
1155 be a small gain when turning off unused link types. The types are:
1157 bracket The recommended [[link][description]] or [[link]] links with hiding.
1158 angular Links in angular brackes that may contain whitespace like
1159 <bbdb:Carsten Dominik>.
1160 plain Plain links in normal text, no whitespace, like http://google.com.
1161 radio Text that is matched by a radio target, see manual for details.
1162 tag Tag settings in a headline (link to tag search).
1163 date Time stamps (link to calendar).
1165 Changing this variable requires a restart of Emacs to become effective."
1166 :group 'org-link
1167 :type '(set (const :tag "Double bracket links (new style)" bracket)
1168 (const :tag "Angular bracket links (old style)" angular)
1169 (const :tag "plain text links" plain)
1170 (const :tag "Radio target matches" radio)
1171 (const :tag "Tags" tag)
1172 (const :tag "Tags" target)
1173 (const :tag "Timestamps" date)))
1175 (defgroup org-link-store nil
1176 "Options concerning storing links in Org-mode"
1177 :tag "Org Store Link"
1178 :group 'org-link)
1180 (defcustom org-email-link-description-format "Email %c: %.30s"
1181 "Format of the description part of a link to an email or usenet message.
1182 The following %-excapes will be replaced by corresponding information:
1184 %F full \"From\" field
1185 %f name, taken from \"From\" field, address if no name
1186 %T full \"To\" field
1187 %t first name in \"To\" field, address if no name
1188 %c correspondent. Unually \"from NAME\", but if you sent it yourself, it
1189 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1190 %s subject
1191 %m message-id.
1193 You may use normal field width specification between the % and the letter.
1194 This is for example useful to limit the length of the subject.
1196 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1197 :group 'org-link-store
1198 :type 'string)
1200 (defcustom org-from-is-user-regexp
1201 (let (r1 r2)
1202 (when (and user-mail-address (not (string= user-mail-address "")))
1203 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1204 (when (and user-full-name (not (string= user-full-name "")))
1205 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1206 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1207 "Regexp mached against the \"From:\" header of an email or usenet message.
1208 It should match if the message is from the user him/herself."
1209 :group 'org-link-store
1210 :type 'regexp)
1212 (defcustom org-context-in-file-links t
1213 "Non-nil means, file links from `org-store-link' contain context.
1214 A search string will be added to the file name with :: as separator and
1215 used to find the context when the link is activated by the command
1216 `org-open-at-point'.
1217 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1218 negates this setting for the duration of the command."
1219 :group 'org-link-store
1220 :type 'boolean)
1222 (defcustom org-keep-stored-link-after-insertion nil
1223 "Non-nil means, keep link in list for entire session.
1225 The command `org-store-link' adds a link pointing to the current
1226 location to an internal list. These links accumulate during a session.
1227 The command `org-insert-link' can be used to insert links into any
1228 Org-mode file (offering completion for all stored links). When this
1229 option is nil, every link which has been inserted once using \\[org-insert-link]
1230 will be removed from the list, to make completing the unused links
1231 more efficient."
1232 :group 'org-link-store
1233 :type 'boolean)
1235 (defcustom org-usenet-links-prefer-google nil
1236 "Non-nil means, `org-store-link' will create web links to Google groups.
1237 When nil, Gnus will be used for such links.
1238 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1239 negates this setting for the duration of the command."
1240 :group 'org-link-store
1241 :type 'boolean)
1243 (defgroup org-link-follow nil
1244 "Options concerning following links in Org-mode"
1245 :tag "Org Follow Link"
1246 :group 'org-link)
1248 (defcustom org-tab-follows-link nil
1249 "Non-nil means, on links TAB will follow the link.
1250 Needs to be set before org.el is loaded."
1251 :group 'org-link-follow
1252 :type 'boolean)
1254 (defcustom org-return-follows-link nil
1255 "Non-nil means, on links RET will follow the link.
1256 Needs to be set before org.el is loaded."
1257 :group 'org-link-follow
1258 :type 'boolean)
1260 (defcustom org-mouse-1-follows-link t
1261 "Non-nil means, mouse-1 on a link will follow the link.
1262 A longer mouse click will still set point. Does not wortk on XEmacs.
1263 Needs to be set before org.el is loaded."
1264 :group 'org-link-follow
1265 :type 'boolean)
1267 (defcustom org-mark-ring-length 4
1268 "Number of different positions to be recorded in the ring
1269 Changing this requires a restart of Emacs to work correctly."
1270 :group 'org-link-follow
1271 :type 'interger)
1273 (defcustom org-link-frame-setup
1274 '((vm . vm-visit-folder-other-frame)
1275 (gnus . gnus-other-frame)
1276 (file . find-file-other-window))
1277 "Setup the frame configuration for following links.
1278 When following a link with Emacs, it may often be useful to display
1279 this link in another window or frame. This variable can be used to
1280 set this up for the different types of links.
1281 For VM, use any of
1282 `vm-visit-folder'
1283 `vm-visit-folder-other-frame'
1284 For Gnus, use any of
1285 `gnus'
1286 `gnus-other-frame'
1287 For FILE, use any of
1288 `find-file'
1289 `find-file-other-window'
1290 `find-file-other-frame'
1291 For the calendar, use the variable `calendar-setup'.
1292 For BBDB, it is currently only possible to display the matches in
1293 another window."
1294 :group 'org-link-follow
1295 :type '(list
1296 (cons (const vm)
1297 (choice
1298 (const vm-visit-folder)
1299 (const vm-visit-folder-other-window)
1300 (const vm-visit-folder-other-frame)))
1301 (cons (const gnus)
1302 (choice
1303 (const gnus)
1304 (const gnus-other-frame)))
1305 (cons (const file)
1306 (choice
1307 (const find-file)
1308 (const find-file-other-window)
1309 (const find-file-other-frame)))))
1311 (defcustom org-display-internal-link-with-indirect-buffer nil
1312 "Non-nil means, use indirect buffer to display infile links.
1313 Activating internal links (from one location in a file to another location
1314 in the same file) normally just jumps to the location. When the link is
1315 activated with a C-u prefix (or with mouse-3), the link is displayed in
1316 another window. When this option is set, the other window actually displays
1317 an indirect buffer clone of the current buffer, to avoid any visibility
1318 changes to the current buffer."
1319 :group 'org-link-follow
1320 :type 'boolean)
1322 (defcustom org-open-non-existing-files nil
1323 "Non-nil means, `org-open-file' will open non-existing files.
1324 When nil, an error will be generated."
1325 :group 'org-link-follow
1326 :type 'boolean)
1328 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1329 "Function and arguments to call for following mailto links.
1330 This is a list with the first element being a lisp function, and the
1331 remaining elements being arguments to the function. In string arguments,
1332 %a will be replaced by the address, and %s will be replaced by the subject
1333 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1334 :group 'org-link-follow
1335 :type '(choice
1336 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1337 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1338 (const :tag "message-mail" (message-mail "%a" "%s"))
1339 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1341 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1342 "Non-nil means, ask for confirmation before executing shell links.
1343 Shell links can be dangerous: just think about a link
1345 [[shell:rm -rf ~/*][Google Search]]
1347 This link would show up in your Org-mode document as \"Google Search\",
1348 but really it would remove your entire home directory.
1349 Therefore we advise against setting this variable to nil.
1350 Just change it to `y-or-n-p' of you want to confirm with a
1351 single keystroke rather than having to type \"yes\"."
1352 :group 'org-link-follow
1353 :type '(choice
1354 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1355 (const :tag "with y-or-n (faster)" y-or-n-p)
1356 (const :tag "no confirmation (dangerous)" nil)))
1358 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1359 "Non-nil means, ask for confirmation before executing Emacs Lisp links.
1360 Elisp links can be dangerous: just think about a link
1362 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1364 This link would show up in your Org-mode document as \"Google Search\",
1365 but really it would remove your entire home directory.
1366 Therefore we advise against setting this variable to nil.
1367 Just change it to `y-or-n-p' of you want to confirm with a
1368 single keystroke rather than having to type \"yes\"."
1369 :group 'org-link-follow
1370 :type '(choice
1371 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1372 (const :tag "with y-or-n (faster)" y-or-n-p)
1373 (const :tag "no confirmation (dangerous)" nil)))
1375 (defconst org-file-apps-defaults-gnu
1376 '((remote . emacs)
1377 (t . mailcap))
1378 "Default file applications on a UNIX or GNU/Linux system.
1379 See `org-file-apps'.")
1381 (defconst org-file-apps-defaults-macosx
1382 '((remote . emacs)
1383 (t . "open %s")
1384 ("ps" . "gv %s")
1385 ("ps.gz" . "gv %s")
1386 ("eps" . "gv %s")
1387 ("eps.gz" . "gv %s")
1388 ("dvi" . "xdvi %s")
1389 ("fig" . "xfig %s"))
1390 "Default file applications on a MacOS X system.
1391 The system \"open\" is known as a default, but we use X11 applications
1392 for some files for which the OS does not have a good default.
1393 See `org-file-apps'.")
1395 (defconst org-file-apps-defaults-windowsnt
1396 (list
1397 '(remote . emacs)
1398 (cons t
1399 (list (if (featurep 'xemacs)
1400 'mswindows-shell-execute
1401 'w32-shell-execute)
1402 "open" 'file)))
1403 "Default file applications on a Windows NT system.
1404 The system \"open\" is used for most files.
1405 See `org-file-apps'.")
1407 (defcustom org-file-apps
1409 ("txt" . emacs)
1410 ("tex" . emacs)
1411 ("ltx" . emacs)
1412 ("org" . emacs)
1413 ("el" . emacs)
1414 ("bib" . emacs)
1416 "External applications for opening `file:path' items in a document.
1417 Org-mode uses system defaults for different file types, but
1418 you can use this variable to set the application for a given file
1419 extension. The entries in this list are cons cells where the car identifies
1420 files and the cdr the corresponding command. Possible values for the
1421 file identifier are
1422 \"ext\" A string identifying an extension
1423 `directory' Matches a directory
1424 `remote' Matches a remote file, accessible through tramp or efs.
1425 Remote files most likely should be visited through Emacs
1426 because external applications cannot handle such paths.
1427 t Default for all remaining files
1429 Possible values for the command are:
1430 `emacs' The file will be visited by the current Emacs process.
1431 `default' Use the default application for this file type.
1432 string A command to be executed by a shell; %s will be replaced
1433 by the path to the file.
1434 sexp A Lisp form which will be evaluated. The file path will
1435 be available in the Lisp variable `file'.
1436 For more examples, see the system specific constants
1437 `org-file-apps-defaults-macosx'
1438 `org-file-apps-defaults-windowsnt'
1439 `org-file-apps-defaults-gnu'."
1440 :group 'org-link-follow
1441 :type '(repeat
1442 (cons (choice :value ""
1443 (string :tag "Extension")
1444 (const :tag "Default for unrecognized files" t)
1445 (const :tag "Remote file" remote)
1446 (const :tag "Links to a directory" directory))
1447 (choice :value ""
1448 (const :tag "Visit with Emacs" emacs)
1449 (const :tag "Use system default" default)
1450 (string :tag "Command")
1451 (sexp :tag "Lisp form")))))
1453 (defcustom org-mhe-search-all-folders nil
1454 "Non-nil means, that the search for the mh-message will be extended to
1455 all folders if the message cannot be found in the folder given in the link.
1456 Searching all folders is very efficient with one of the search engines
1457 supported by MH-E, but will be slow with pick."
1458 :group 'org-link-follow
1459 :type 'boolean)
1461 (defgroup org-remember nil
1462 "Options concerning interaction with remember.el."
1463 :tag "Org Remember"
1464 :group 'org)
1466 (defcustom org-directory "~/org"
1467 "Directory with org files.
1468 This directory will be used as default to prompt for org files.
1469 Used by the hooks for remember.el."
1470 :group 'org-remember
1471 :type 'directory)
1473 (defcustom org-default-notes-file "~/.notes"
1474 "Default target for storing notes.
1475 Used by the hooks for remember.el. This can be a string, or nil to mean
1476 the value of `remember-data-file'.
1477 You can set this on a per-template basis with the variable
1478 `org-remember-templates'."
1479 :group 'org-remember
1480 :type '(choice
1481 (const :tag "Default from remember-data-file" nil)
1482 file))
1484 (defcustom org-remember-store-without-prompt t
1485 "Non-nil means, `C-c C-c' stores remember note without further promts.
1486 In this case, you need `C-u C-c C-c' to get the prompts for
1487 note file and headline.
1488 When this variable is nil, `C-c C-c' give you the prompts, and
1489 `C-u C-c C-c' trigger the fasttrack."
1490 :group 'org-remember
1491 :type 'boolean)
1493 (defcustom org-remember-interactive-interface 'refile
1494 "The interface to be used for interactive filing of remember notes.
1495 This is only used when the interactive mode for selecting a filing
1496 location is used (see the variable `org-remember-store-without-prompt').
1497 Allowed vaues are:
1498 outline The interface shows an outline of the relevant file
1499 and the correct heading is found by moving through
1500 the outline or by searching with incremental search.
1501 outline-path-completion Headlines in the current buffer are offered via
1502 completion.
1503 refile Use the refile interface, and offer headlines,
1504 possibly from different buffers."
1505 :group 'org-remember
1506 :type '(choice
1507 (const :tag "Refile" refile)
1508 (const :tag "Outline" outline)
1509 (const :tag "Outline-path-completion" outline-path-completion)))
1511 (defcustom org-goto-interface 'outline
1512 "The default interface to be used for `org-goto'.
1513 Allowed vaues are:
1514 outline The interface shows an outline of the relevant file
1515 and the correct heading is found by moving through
1516 the outline or by searching with incremental search.
1517 outline-path-completion Headlines in the current buffer are offered via
1518 completion."
1519 :group 'org-remember ; FIXME: different group for org-goto and org-refile
1520 :type '(choice
1521 (const :tag "Outline" outline)
1522 (const :tag "Outline-path-completion" outline-path-completion)))
1524 (defcustom org-remember-default-headline ""
1525 "The headline that should be the default location in the notes file.
1526 When filing remember notes, the cursor will start at that position.
1527 You can set this on a per-template basis with the variable
1528 `org-remember-templates'."
1529 :group 'org-remember
1530 :type 'string)
1532 (defcustom org-remember-templates nil
1533 "Templates for the creation of remember buffers.
1534 When nil, just let remember make the buffer.
1535 When not nil, this is a list of 5-element lists. In each entry, the first
1536 element is the name of the template, which should be a single short word.
1537 The second element is a character, a unique key to select this template.
1538 The third element is the template. The fourth element is optional and can
1539 specify a destination file for remember items created with this template.
1540 The default file is given by `org-default-notes-file'. An optional fifth
1541 element can specify the headline in that file that should be offered
1542 first when the user is asked to file the entry. The default headline is
1543 given in the variable `org-remember-default-headline'.
1545 The template specifies the structure of the remember buffer. It should have
1546 a first line starting with a star, to act as the org-mode headline.
1547 Furthermore, the following %-escapes will be replaced with content:
1549 %^{prompt} Prompt the user for a string and replace this sequence with it.
1550 A default value and a completion table ca be specified like this:
1551 %^{prompt|default|completion2|completion3|...}
1552 %t time stamp, date only
1553 %T time stamp with date and time
1554 %u, %U like the above, but inactive time stamps
1555 %^t like %t, but prompt for date. Similarly %^T, %^u, %^U
1556 You may define a prompt like %^{Please specify birthday}t
1557 %n user name (taken from `user-full-name')
1558 %a annotation, normally the link created with org-store-link
1559 %i initial content, the region active. If %i is indented,
1560 the entire inserted text will be indented as well.
1561 %c content of the clipboard, or current kill ring head
1562 %^g prompt for tags, with completion on tags in target file
1563 %^G prompt for tags, with completion all tags in all agenda files
1564 %:keyword specific information for certain link types, see below
1565 %[pathname] insert the contents of the file given by `pathname'
1566 %(sexp) evaluate elisp `(sexp)' and replace with the result
1567 %! Store this note immediately after filling the template
1569 %? After completing the template, position cursor here.
1571 Apart from these general escapes, you can access information specific to the
1572 link type that is created. For example, calling `remember' in emails or gnus
1573 will record the author and the subject of the message, which you can access
1574 with %:author and %:subject, respectively. Here is a complete list of what
1575 is recorded for each link type.
1577 Link type | Available information
1578 -------------------+------------------------------------------------------
1579 bbdb | %:type %:name %:company
1580 vm, wl, mh, rmail | %:type %:subject %:message-id
1581 | %:from %:fromname %:fromaddress
1582 | %:to %:toname %:toaddress
1583 | %:fromto (either \"to NAME\" or \"from NAME\")
1584 gnus | %:group, for messages also all email fields
1585 w3, w3m | %:type %:url
1586 info | %:type %:file %:node
1587 calendar | %:type %:date"
1588 :group 'org-remember
1589 :get (lambda (var) ; Make sure all entries have 5 elements
1590 (mapcar (lambda (x)
1591 (if (not (stringp (car x))) (setq x (cons "" x)))
1592 (cond ((= (length x) 4) (append x '("")))
1593 ((= (length x) 3) (append x '("" "")))
1594 (t x)))
1595 (default-value var)))
1596 :type '(repeat
1597 :tag "enabled"
1598 (list :value ("" ?a "\n" nil nil)
1599 (string :tag "Name")
1600 (character :tag "Selection Key")
1601 (string :tag "Template")
1602 (choice
1603 (file :tag "Destination file")
1604 (const :tag "Prompt for file" nil))
1605 (choice
1606 (string :tag "Destination headline")
1607 (const :tag "Selection interface for heading")))))
1609 (defcustom org-reverse-note-order nil
1610 "Non-nil means, store new notes at the beginning of a file or entry.
1611 When nil, new notes will be filed to the end of a file or entry.
1612 This can also be a list with cons cells of regular expressions that
1613 are matched against file names, and values."
1614 :group 'org-remember
1615 :type '(choice
1616 (const :tag "Reverse always" t)
1617 (const :tag "Reverse never" nil)
1618 (repeat :tag "By file name regexp"
1619 (cons regexp boolean))))
1621 (defcustom org-refile-targets nil
1622 "Targets for refiling entries with \\[org-refile].
1623 This is list of cons cells. Each cell contains:
1624 - a specification of the files to be considered, either a list of files,
1625 or a symbol whose function or value fields will be used to retrieve
1626 a file name or a list of file names. Nil means, refile to a different
1627 heading in the current buffer.
1628 - A specification of how to find candidate refile targets. This may be
1629 any of
1630 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
1631 This tag has to be present in all target headlines, inheritance will
1632 not be considered.
1633 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
1634 todo keyword.
1635 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1636 headlines that are refiling targets.
1637 - a cons cell (:level . N). Any headline of level N is considered a target.
1638 - a cons cell (:maxlevel . N). Any headline with level <= N is a target."
1639 ;; FIXME: what if there are a var and func with same name???
1640 :group 'org-remember
1641 :type '(repeat
1642 (cons
1643 (choice :value org-agenda-files
1644 (const :tag "All agenda files" org-agenda-files)
1645 (const :tag "Current buffer" nil)
1646 (function) (variable) (file))
1647 (choice :tag "Identify target headline by"
1648 (cons :tag "Specific tag" (const :tag) (string))
1649 (cons :tag "TODO keyword" (const :todo) (string))
1650 (cons :tag "Regular expression" (const :regexp) (regexp))
1651 (cons :tag "Level number" (const :level) (integer))
1652 (cons :tag "Max Level number" (const :maxlevel) (integer))))))
1654 (defcustom org-refile-use-outline-path nil
1655 "Non-nil means, provide refile targets as paths.
1656 So a level 3 headline will be available as level1/level2/level3.
1657 When the value is `file', also include the file name (without directory)
1658 into the path. When `full-file-path', include the full file path."
1659 :group 'org-remember
1660 :type '(choice
1661 (const :tag "Not" nil)
1662 (const :tag "Yes" t)
1663 (const :tag "Start with file name" file)
1664 (const :tag "Start with full file path" full-file-path)))
1666 (defgroup org-todo nil
1667 "Options concerning TODO items in Org-mode."
1668 :tag "Org TODO"
1669 :group 'org)
1671 (defgroup org-progress nil
1672 "Options concerning Progress logging in Org-mode."
1673 :tag "Org Progress"
1674 :group 'org-time)
1676 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
1677 "List of TODO entry keyword sequences and their interpretation.
1678 \\<org-mode-map>This is a list of sequences.
1680 Each sequence starts with a symbol, either `sequence' or `type',
1681 indicating if the keywords should be interpreted as a sequence of
1682 action steps, or as different types of TODO items. The first
1683 keywords are states requiring action - these states will select a headline
1684 for inclusion into the global TODO list Org-mode produces. If one of
1685 the \"keywords\" is the vertical bat \"|\" the remaining keywords
1686 signify that no further action is necessary. If \"|\" is not found,
1687 the last keyword is treated as the only DONE state of the sequence.
1689 The command \\[org-todo] cycles an entry through these states, and one
1690 additional state where no keyword is present. For details about this
1691 cycling, see the manual.
1693 TODO keywords and interpretation can also be set on a per-file basis with
1694 the special #+SEQ_TODO and #+TYP_TODO lines.
1696 Each keyword can optionally specify a character for fast state selection
1697 \(in combination with the variable `org-use-fast-todo-selection')
1698 and specifiers for state change logging, using the same syntax
1699 that is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says
1700 that the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
1701 indicates to record a time stamp each time this state is selected.
1702 \"WAIT(w@)\" says that the user should in addition be prompted for a
1703 note, and \"WAIT(w@/@)\" says that a note should be taken both when
1704 entering and when leaving this state.
1706 For backward compatibility, this variable may also be just a list
1707 of keywords - in this case the interptetation (sequence or type) will be
1708 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
1709 :group 'org-todo
1710 :group 'org-keywords
1711 :type '(choice
1712 (repeat :tag "Old syntax, just keywords"
1713 (string :tag "Keyword"))
1714 (repeat :tag "New syntax"
1715 (cons
1716 (choice
1717 :tag "Interpretation"
1718 (const :tag "Sequence (cycling hits every state)" sequence)
1719 (const :tag "Type (cycling directly to DONE)" type))
1720 (repeat
1721 (string :tag "Keyword"))))))
1723 (defvar org-todo-keywords-1 nil
1724 "All TODO and DONE keywords active in a buffer.")
1725 (make-variable-buffer-local 'org-todo-keywords-1)
1726 (defvar org-todo-keywords-for-agenda nil)
1727 (defvar org-done-keywords-for-agenda nil)
1728 (defvar org-not-done-keywords nil)
1729 (make-variable-buffer-local 'org-not-done-keywords)
1730 (defvar org-done-keywords nil)
1731 (make-variable-buffer-local 'org-done-keywords)
1732 (defvar org-todo-heads nil)
1733 (make-variable-buffer-local 'org-todo-heads)
1734 (defvar org-todo-sets nil)
1735 (make-variable-buffer-local 'org-todo-sets)
1736 (defvar org-todo-log-states nil)
1737 (make-variable-buffer-local 'org-todo-log-states)
1738 (defvar org-todo-kwd-alist nil)
1739 (make-variable-buffer-local 'org-todo-kwd-alist)
1740 (defvar org-todo-key-alist nil)
1741 (make-variable-buffer-local 'org-todo-key-alist)
1742 (defvar org-todo-key-trigger nil)
1743 (make-variable-buffer-local 'org-todo-key-trigger)
1745 (defcustom org-todo-interpretation 'sequence
1746 "Controls how TODO keywords are interpreted.
1747 This variable is in principle obsolete and is only used for
1748 backward compatibility, if the interpretation of todo keywords is
1749 not given already in `org-todo-keywords'. See that variable for
1750 more information."
1751 :group 'org-todo
1752 :group 'org-keywords
1753 :type '(choice (const sequence)
1754 (const type)))
1756 (defcustom org-use-fast-todo-selection 'prefix
1757 "Non-nil means, use the fast todo selection scheme with C-c C-t.
1758 This variable describes if and under what circumstances the cycling
1759 mechanism for TODO keywords will be replaced by a single-key, direct
1760 selection scheme.
1762 When nil, fast selection is never used.
1764 When the symbol `prefix', it will be used when `org-todo' is called with
1765 a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and `C-u t'
1766 in an agenda buffer.
1768 When t, fast selection is used by default. In this case, the prefix
1769 argument forces cycling instead.
1771 In all cases, the special interface is only used if access keys have actually
1772 been assigned by the user, i.e. if keywords in the configuration are followed
1773 by a letter in parenthesis, like TODO(t)."
1774 :group 'org-todo
1775 :type '(choice
1776 (const :tag "Never" nil)
1777 (const :tag "By default" t)
1778 (const :tag "Only with C-u C-c C-t" prefix)))
1780 (defcustom org-after-todo-state-change-hook nil
1781 "Hook which is run after the state of a TODO item was changed.
1782 The new state (a string with a TODO keyword, or nil) is available in the
1783 Lisp variable `state'."
1784 :group 'org-todo
1785 :type 'hook)
1787 (defcustom org-log-done nil
1788 "Non-nil means, record a CLOSED timestamp when moving an entry to DONE.
1789 When equal to the list (done), also prompt for a closing note.
1790 This can also be configured on a per-file basis by adding one of
1791 the following lines anywhere in the buffer:
1793 #+STARTUP: logdone
1794 #+STARTUP: lognotedone
1795 #+STARTUP: nologdone"
1796 :group 'org-todo
1797 :group 'org-progress
1798 :type '(choice
1799 (const :tag "No logging" nil)
1800 (const :tag "Record CLOSED timestamp" time)
1801 (const :tag "Record CLOSED timestamp with closing note." note)))
1803 ;; Normalize old uses of org-log-done.
1804 (cond
1805 ((eq org-log-done t) (setq org-log-done 'time))
1806 ((and (listp org-log-done) (memq 'done org-log-done))
1807 (setq org-log-done 'note)))
1809 ;; FIXME: document
1810 (defcustom org-log-note-clock-out nil
1811 "Non-nil means, recored a note when clocking out of an item.
1812 This can also be configured on a per-file basis by adding one of
1813 the following lines anywhere in the buffer:
1815 #+STARTUP: lognoteclock-out
1816 #+STARTUP: nolognoteclock-out"
1817 :group 'org-todo
1818 :group 'org-progress
1819 :type 'boolean)
1821 (defcustom org-log-done-with-time t
1822 "Non-nil means, the CLOSED time stamp will contain date and time.
1823 When nil, only the date will be recorded."
1824 :group 'org-progress
1825 :type 'boolean)
1827 (defcustom org-log-note-headings
1828 '((done . "CLOSING NOTE %t")
1829 (state . "State %-12s %t")
1830 (clock-out . ""))
1831 "Headings for notes added when clocking out or closing TODO items.
1832 The value is an alist, with the car being a symbol indicating the note
1833 context, and the cdr is the heading to be used. The heading may also be the
1834 empty string.
1835 %t in the heading will be replaced by a time stamp.
1836 %s will be replaced by the new TODO state, in double quotes.
1837 %u will be replaced by the user name.
1838 %U will be replaced by the full user name."
1839 :group 'org-todo
1840 :group 'org-progress
1841 :type '(list :greedy t
1842 (cons (const :tag "Heading when closing an item" done) string)
1843 (cons (const :tag
1844 "Heading when changing todo state (todo sequence only)"
1845 state) string)
1846 (cons (const :tag "Heading when clocking out" clock-out) string)))
1848 (defcustom org-log-states-order-reversed t
1849 "Non-nil means, the latest state change note will be directly after heading.
1850 When nil, the notes will be orderer according to time."
1851 :group 'org-todo
1852 :group 'org-progress
1853 :type 'boolean)
1855 (defcustom org-log-repeat 'time
1856 "Non-nil means, record moving through the DONE state when triggering repeat.
1857 An auto-repeating tasks is immediately switched back to TODO when marked
1858 done. If you are not logging state changes (by adding \"@\" or \"!\" to
1859 the TODO keyword definition, or recording a cloing note by setting
1860 `org-log-done', there will be no record of the task moving trhough DONE.
1861 This variable forces taking a note anyway. Possible values are:
1863 nil Don't force a record
1864 time Record a time stamp
1865 note Record a note
1867 This option can also be set with on a per-file-basis with
1869 #+STARTUP: logrepeat
1870 #+STARTUP: lognoterepeat
1871 #+STARTUP: nologrepeat
1873 You can have local logging settings for a subtree by setting the LOGGING
1874 property to one or more of these keywords."
1875 :group 'org-todo
1876 :group 'org-progress
1877 :type '(choice
1878 (const :tag "Don't force a record" nil)
1879 (const :tag "Force recording the DONE state" time)
1880 (const :tag "Force recording a note with the DONE state" note)))
1882 (defcustom org-clock-into-drawer 2
1883 "Should clocking info be wrapped into a drawer?
1884 When t, clocking info will always be inserted into a :CLOCK: drawer.
1885 If necessary, the drawer will be created.
1886 When nil, the drawer will not be created, but used when present.
1887 When an integer and the number of clocking entries in an item
1888 reaches or exceeds this number, a drawer will be created."
1889 :group 'org-todo
1890 :group 'org-progress
1891 :type '(choice
1892 (const :tag "Always" t)
1893 (const :tag "Only when drawer exists" nil)
1894 (integer :tag "When at least N clock entries")))
1896 (defcustom org-clock-out-when-done t
1897 "When t, the clock will be stopped when the relevant entry is marked DONE.
1898 Nil means, clock will keep running until stopped explicitly with
1899 `C-c C-x C-o', or until the clock is started in a different item."
1900 :group 'org-progress
1901 :type 'boolean)
1903 (defcustom org-clock-in-switch-to-state nil
1904 "Set task to a special todo state while clocking it.
1905 The value should be the state to which the entry should be switched."
1906 :group 'org-progress
1907 :group 'org-todo
1908 :type '(choice
1909 (const :tag "Don't force a state" nil)
1910 (string :tag "State")))
1912 (defgroup org-priorities nil
1913 "Priorities in Org-mode."
1914 :tag "Org Priorities"
1915 :group 'org-todo)
1917 (defcustom org-highest-priority ?A
1918 "The highest priority of TODO items. A character like ?A, ?B etc.
1919 Must have a smaller ASCII number than `org-lowest-priority'."
1920 :group 'org-priorities
1921 :type 'character)
1923 (defcustom org-lowest-priority ?C
1924 "The lowest priority of TODO items. A character like ?A, ?B etc.
1925 Must have a larger ASCII number than `org-highest-priority'."
1926 :group 'org-priorities
1927 :type 'character)
1929 (defcustom org-default-priority ?B
1930 "The default priority of TODO items.
1931 This is the priority an item get if no explicit priority is given."
1932 :group 'org-priorities
1933 :type 'character)
1935 (defcustom org-priority-start-cycle-with-default t
1936 "Non-nil means, start with default priority when starting to cycle.
1937 When this is nil, the first step in the cycle will be (depending on the
1938 command used) one higher or lower that the default priority."
1939 :group 'org-priorities
1940 :type 'boolean)
1942 (defgroup org-time nil
1943 "Options concerning time stamps and deadlines in Org-mode."
1944 :tag "Org Time"
1945 :group 'org)
1947 (defcustom org-insert-labeled-timestamps-at-point nil
1948 "Non-nil means, SCHEDULED and DEADLINE timestamps are inserted at point.
1949 When nil, these labeled time stamps are forces into the second line of an
1950 entry, just after the headline. When scheduling from the global TODO list,
1951 the time stamp will always be forced into the second line."
1952 :group 'org-time
1953 :type 'boolean)
1955 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
1956 "Formats for `format-time-string' which are used for time stamps.
1957 It is not recommended to change this constant.")
1959 (defcustom org-time-stamp-rounding-minutes 0
1960 "Number of minutes to round time stamps to upon insertion.
1961 When zero, insert the time unmodified. Useful rounding numbers
1962 should be factors of 60, so for example 5, 10, 15.
1963 When this is not zero, you can still force an exact time-stamp by using
1964 a double prefix argument to a time-stamp command like `C-c .' or `C-c !'."
1965 :group 'org-time
1966 :type 'integer)
1968 (defcustom org-display-custom-times nil
1969 "Non-nil means, overlay custom formats over all time stamps.
1970 The formats are defined through the variable `org-time-stamp-custom-formats'.
1971 To turn this on on a per-file basis, insert anywhere in the file:
1972 #+STARTUP: customtime"
1973 :group 'org-time
1974 :set 'set-default
1975 :type 'sexp)
1976 (make-variable-buffer-local 'org-display-custom-times)
1978 (defcustom org-time-stamp-custom-formats
1979 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
1980 "Custom formats for time stamps. See `format-time-string' for the syntax.
1981 These are overlayed over the default ISO format if the variable
1982 `org-display-custom-times' is set. Time like %H:%M should be at the
1983 end of the second format."
1984 :group 'org-time
1985 :type 'sexp)
1987 (defun org-time-stamp-format (&optional long inactive)
1988 "Get the right format for a time string."
1989 (let ((f (if long (cdr org-time-stamp-formats)
1990 (car org-time-stamp-formats))))
1991 (if inactive
1992 (concat "[" (substring f 1 -1) "]")
1993 f)))
1995 (defcustom org-read-date-prefer-future t
1996 "Non-nil means, assume future for incomplete date input from user.
1997 This affects the following situations:
1998 1. The user gives a day, but no month.
1999 For example, if today is the 15th, and you enter \"3\", Org-mode will
2000 read this as the third of *next* month. However, if you enter \"17\",
2001 it will be considered as *this* month.
2002 2. The user gives a month but not a year.
2003 For example, if it is april and you enter \"feb 2\", this will be read
2004 as feb 2, *next* year. \"May 5\", however, will be this year.
2006 When this option is nil, the current month and year will always be used
2007 as defaults."
2008 :group 'org-time
2009 :type 'boolean)
2011 (defcustom org-read-date-display-live t
2012 "Non-nil means, display current interpretation of date prompt live.
2013 This display will be in an overlay, in the minibuffer."
2014 :group 'org-time
2015 :type 'boolean)
2017 (defcustom org-read-date-popup-calendar t
2018 "Non-nil means, pop up a calendar when prompting for a date.
2019 In the calendar, the date can be selected with mouse-1. However, the
2020 minibuffer will also be active, and you can simply enter the date as well.
2021 When nil, only the minibuffer will be available."
2022 :group 'org-time
2023 :type 'boolean)
2024 (if (fboundp 'defvaralias)
2025 (defvaralias 'org-popup-calendar-for-date-prompt
2026 'org-read-date-popup-calendar))
2028 (defcustom org-extend-today-until 0
2029 "The hour when your day really ends.
2030 This has influence for the following applications:
2031 - When switching the agenda to \"today\". It it is still earlier than
2032 the time given here, the day recognized as TODAY is actually yesterday.
2033 - When a date is read from the user and it is still before the time given
2034 here, the current date and time will be assumed to be yesterday, 23:59.
2036 FIXME:
2037 IMPORTANT: This is still a very experimental feature, it may disappear
2038 again or it may be extended to mean more things."
2039 :group 'org-time
2040 :type 'number)
2042 (defcustom org-edit-timestamp-down-means-later nil
2043 "Non-nil means, S-down will increase the time in a time stamp.
2044 When nil, S-up will increase."
2045 :group 'org-time
2046 :type 'boolean)
2048 (defcustom org-calendar-follow-timestamp-change t
2049 "Non-nil means, make the calendar window follow timestamp changes.
2050 When a timestamp is modified and the calendar window is visible, it will be
2051 moved to the new date."
2052 :group 'org-time
2053 :type 'boolean)
2055 (defcustom org-clock-heading-function nil
2056 "When non-nil, should be a function to create `org-clock-heading'.
2057 This is the string shown in the mode line when a clock is running.
2058 The function is called with point at the beginning of the headline."
2059 :group 'org-time ; FIXME: Should we have a separate group????
2060 :type 'function)
2062 (defgroup org-tags nil
2063 "Options concerning tags in Org-mode."
2064 :tag "Org Tags"
2065 :group 'org)
2067 (defcustom org-tag-alist nil
2068 "List of tags allowed in Org-mode files.
2069 When this list is nil, Org-mode will base TAG input on what is already in the
2070 buffer.
2071 The value of this variable is an alist, the car of each entry must be a
2072 keyword as a string, the cdr may be a character that is used to select
2073 that tag through the fast-tag-selection interface.
2074 See the manual for details."
2075 :group 'org-tags
2076 :type '(repeat
2077 (choice
2078 (cons (string :tag "Tag name")
2079 (character :tag "Access char"))
2080 (const :tag "Start radio group" (:startgroup))
2081 (const :tag "End radio group" (:endgroup)))))
2083 (defcustom org-use-fast-tag-selection 'auto
2084 "Non-nil means, use fast tag selection scheme.
2085 This is a special interface to select and deselect tags with single keys.
2086 When nil, fast selection is never used.
2087 When the symbol `auto', fast selection is used if and only if selection
2088 characters for tags have been configured, either through the variable
2089 `org-tag-alist' or through a #+TAGS line in the buffer.
2090 When t, fast selection is always used and selection keys are assigned
2091 automatically if necessary."
2092 :group 'org-tags
2093 :type '(choice
2094 (const :tag "Always" t)
2095 (const :tag "Never" nil)
2096 (const :tag "When selection characters are configured" 'auto)))
2098 (defcustom org-fast-tag-selection-single-key nil
2099 "Non-nil means, fast tag selection exits after first change.
2100 When nil, you have to press RET to exit it.
2101 During fast tag selection, you can toggle this flag with `C-c'.
2102 This variable can also have the value `expert'. In this case, the window
2103 displaying the tags menu is not even shown, until you press C-c again."
2104 :group 'org-tags
2105 :type '(choice
2106 (const :tag "No" nil)
2107 (const :tag "Yes" t)
2108 (const :tag "Expert" expert)))
2110 (defvar org-fast-tag-selection-include-todo nil
2111 "Non-nil means, fast tags selection interface will also offer TODO states.
2112 This is an undocumented feature, you should not rely on it.")
2114 (defcustom org-tags-column -80
2115 "The column to which tags should be indented in a headline.
2116 If this number is positive, it specifies the column. If it is negative,
2117 it means that the tags should be flushright to that column. For example,
2118 -80 works well for a normal 80 character screen."
2119 :group 'org-tags
2120 :type 'integer)
2122 (defcustom org-auto-align-tags t
2123 "Non-nil means, realign tags after pro/demotion of TODO state change.
2124 These operations change the length of a headline and therefore shift
2125 the tags around. With this options turned on, after each such operation
2126 the tags are again aligned to `org-tags-column'."
2127 :group 'org-tags
2128 :type 'boolean)
2130 (defcustom org-use-tag-inheritance t
2131 "Non-nil means, tags in levels apply also for sublevels.
2132 When nil, only the tags directly given in a specific line apply there.
2133 If you turn off this option, you very likely want to turn on the
2134 companion option `org-tags-match-list-sublevels'."
2135 :group 'org-tags
2136 :type 'boolean)
2138 (defcustom org-tags-match-list-sublevels nil
2139 "Non-nil means list also sublevels of headlines matching tag search.
2140 Because of tag inheritance (see variable `org-use-tag-inheritance'),
2141 the sublevels of a headline matching a tag search often also match
2142 the same search. Listing all of them can create very long lists.
2143 Setting this variable to nil causes subtrees of a match to be skipped.
2144 This option is off by default, because inheritance in on. If you turn
2145 inheritance off, you very likely want to turn this option on.
2147 As a special case, if the tag search is restricted to TODO items, the
2148 value of this variable is ignored and sublevels are always checked, to
2149 make sure all corresponding TODO items find their way into the list."
2150 :group 'org-tags
2151 :type 'boolean)
2153 (defvar org-tags-history nil
2154 "History of minibuffer reads for tags.")
2155 (defvar org-last-tags-completion-table nil
2156 "The last used completion table for tags.")
2157 (defvar org-after-tags-change-hook nil
2158 "Hook that is run after the tags in a line have changed.")
2160 (defgroup org-properties nil
2161 "Options concerning properties in Org-mode."
2162 :tag "Org Properties"
2163 :group 'org)
2165 (defcustom org-property-format "%-10s %s"
2166 "How property key/value pairs should be formatted by `indent-line'.
2167 When `indent-line' hits a property definition, it will format the line
2168 according to this format, mainly to make sure that the values are
2169 lined-up with respect to each other."
2170 :group 'org-properties
2171 :type 'string)
2173 (defcustom org-use-property-inheritance nil
2174 "Non-nil means, properties apply also for sublevels.
2175 This setting is only relevant during property searches, not when querying
2176 an entry with `org-entry-get'. To retrieve a property with inheritance,
2177 you need to call `org-entry-get' with the inheritance flag.
2178 Turning this on can cause significant overhead when doing a search, so
2179 this is turned off by default.
2180 When nil, only the properties directly given in the current entry count.
2181 The value may also be a list of properties that shouldhave inheritance.
2183 However, note that some special properties use inheritance under special
2184 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
2185 and the properties ending in \"_ALL\" when they are used as descriptor
2186 for valid values of a property."
2187 :group 'org-properties
2188 :type '(choice
2189 (const :tag "Not" nil)
2190 (const :tag "Always" nil)
2191 (repeat :tag "Specific properties" (string :tag "Property"))))
2193 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
2194 "The default column format, if no other format has been defined.
2195 This variable can be set on the per-file basis by inserting a line
2197 #+COLUMNS: %25ITEM ....."
2198 :group 'org-properties
2199 :type 'string)
2201 (defcustom org-global-properties nil
2202 "List of property/value pairs that can be inherited by any entry.
2203 You can set buffer-local values for this by adding lines like
2205 #+PROPERTY: NAME VALUE"
2206 :group 'org-properties
2207 :type '(repeat
2208 (cons (string :tag "Property")
2209 (string :tag "Value"))))
2211 (defvar org-local-properties nil
2212 "List of property/value pairs that can be inherited by any entry.
2213 Valid for the current buffer.
2214 This variable is populated from #+PROPERTY lines.")
2216 (defgroup org-agenda nil
2217 "Options concerning agenda views in Org-mode."
2218 :tag "Org Agenda"
2219 :group 'org)
2221 (defvar org-category nil
2222 "Variable used by org files to set a category for agenda display.
2223 Such files should use a file variable to set it, for example
2225 # -*- mode: org; org-category: \"ELisp\"
2227 or contain a special line
2229 #+CATEGORY: ELisp
2231 If the file does not specify a category, then file's base name
2232 is used instead.")
2233 (make-variable-buffer-local 'org-category)
2235 (defcustom org-agenda-files nil
2236 "The files to be used for agenda display.
2237 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
2238 \\[org-remove-file]. You can also use customize to edit the list.
2240 If an entry is a directory, all files in that directory that are matched by
2241 `org-agenda-file-regexp' will be part of the file list.
2243 If the value of the variable is not a list but a single file name, then
2244 the list of agenda files is actually stored and maintained in that file, one
2245 agenda file per line."
2246 :group 'org-agenda
2247 :type '(choice
2248 (repeat :tag "List of files and directories" file)
2249 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
2251 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
2252 "Regular expression to match files for `org-agenda-files'.
2253 If any element in the list in that variable contains a directory instead
2254 of a normal file, all files in that directory that are matched by this
2255 regular expression will be included."
2256 :group 'org-agenda
2257 :type 'regexp)
2259 (defcustom org-agenda-skip-unavailable-files nil
2260 "t means to just skip non-reachable files in `org-agenda-files'.
2261 Nil means to remove them, after a query, from the list."
2262 :group 'org-agenda
2263 :type 'boolean)
2265 (defcustom org-agenda-text-search-extra-files nil
2266 "List of extra files to be searched by text search commands.
2267 These files will be search in addition to the agenda files bu the
2268 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
2269 Note that these files will only be searched for text search commands,
2270 not for the other agenda views like todo lists, tag earches or the weekly
2271 agenda. This variable is intended to list notes and possibly archive files
2272 that should also be searched by these two commands."
2273 :group 'org-agenda
2274 :type '(repeat file))
2276 (if (fboundp 'defvaralias)
2277 (defvaralias 'org-agenda-multi-occur-extra-files
2278 'org-agenda-text-search-extra-files))
2280 (defcustom org-agenda-confirm-kill 1
2281 "When set, remote killing from the agenda buffer needs confirmation.
2282 When t, a confirmation is always needed. When a number N, confirmation is
2283 only needed when the text to be killed contains more than N non-white lines."
2284 :group 'org-agenda
2285 :type '(choice
2286 (const :tag "Never" nil)
2287 (const :tag "Always" t)
2288 (number :tag "When more than N lines")))
2290 (defcustom org-calendar-to-agenda-key [?c]
2291 "The key to be installed in `calendar-mode-map' for switching to the agenda.
2292 The command `org-calendar-goto-agenda' will be bound to this key. The
2293 default is the character `c' because then `c' can be used to switch back and
2294 forth between agenda and calendar."
2295 :group 'org-agenda
2296 :type 'sexp)
2298 (defcustom org-agenda-compact-blocks nil
2299 "Non-nil means, make the block agenda more compact.
2300 This is done by leaving out unnecessary lines."
2301 :group 'org-agenda
2302 :type nil)
2304 (defgroup org-agenda-export nil
2305 "Options concerning exporting agenda views in Org-mode."
2306 :tag "Org Agenda Export"
2307 :group 'org-agenda)
2309 (defcustom org-agenda-with-colors t
2310 "Non-nil means, use colors in agenda views."
2311 :group 'org-agenda-export
2312 :type 'boolean)
2314 (defcustom org-agenda-exporter-settings nil
2315 "Alist of variable/value pairs that should be active during agenda export.
2316 This is a good place to set uptions for ps-print and for htmlize."
2317 :group 'org-agenda-export
2318 :type '(repeat
2319 (list
2320 (variable)
2321 (sexp :tag "Value"))))
2323 (defcustom org-agenda-export-html-style ""
2324 "The style specification for exported HTML Agenda files.
2325 If this variable contains a string, it will replace the default <style>
2326 section as produced by `htmlize'.
2327 Since there are different ways of setting style information, this variable
2328 needs to contain the full HTML structure to provide a style, including the
2329 surrounding HTML tags. The style specifications should include definitions
2330 the fonts used by the agenda, here is an example:
2332 <style type=\"text/css\">
2333 p { font-weight: normal; color: gray; }
2334 .org-agenda-structure {
2335 font-size: 110%;
2336 color: #003399;
2337 font-weight: 600;
2339 .org-todo {
2340 color: #cc6666;Week-agenda:
2341 font-weight: bold;
2343 .org-done {
2344 color: #339933;
2346 .title { text-align: center; }
2347 .todo, .deadline { color: red; }
2348 .done { color: green; }
2349 </style>
2351 or, if you want to keep the style in a file,
2353 <link rel=\"stylesheet\" type=\"text/css\" href=\"mystyles.css\">
2355 As the value of this option simply gets inserted into the HTML <head> header,
2356 you can \"misuse\" it to also add other text to the header. However,
2357 <style>...</style> is required, if not present the variable will be ignored."
2358 :group 'org-agenda-export
2359 :group 'org-export-html
2360 :type 'string)
2362 (defgroup org-agenda-custom-commands nil
2363 "Options concerning agenda views in Org-mode."
2364 :tag "Org Agenda Custom Commands"
2365 :group 'org-agenda)
2367 (defcustom org-agenda-custom-commands nil
2368 "Custom commands for the agenda.
2369 These commands will be offered on the splash screen displayed by the
2370 agenda dispatcher \\[org-agenda]. Each entry is a list like this:
2372 (key desc type match options files)
2374 key The key (one or more characters as a string) to be associated
2375 with the command.
2376 desc A description of the commend, when omitted or nil, a default
2377 description is built using MATCH.
2378 type The command type, any of the following symbols:
2379 agenda The daily/weekly agenda.
2380 todo Entries with a specific TODO keyword, in all agenda files.
2381 search Entries containing search words entry or headline.
2382 tags Tags/Property/TODO match in all agenda files.
2383 tags-todo Tags/P/T match in all agenda files, TODO entries only.
2384 todo-tree Sparse tree of specific TODO keyword in *current* file.
2385 tags-tree Sparse tree with all tags matches in *current* file.
2386 occur-tree Occur sparse tree for *current* file.
2387 ... A user-defined function.
2388 match What to search for:
2389 - a single keyword for TODO keyword searches
2390 - a tags match expression for tags searches
2391 - a regular expression for occur searches
2392 options A list of option settings, similar to that in a let form, so like
2393 this: ((opt1 val1) (opt2 val2) ...)
2394 files A list of files file to write the produced agenda buffer to
2395 with the command `org-store-agenda-views'.
2396 If a file name ends in \".html\", an HTML version of the buffer
2397 is written out. If it ends in \".ps\", a postscript version is
2398 produced. Otherwide, only the plain text is written to the file.
2400 You can also define a set of commands, to create a composite agenda buffer.
2401 In this case, an entry looks like this:
2403 (key desc (cmd1 cmd2 ...) general-options file)
2405 where
2407 desc A description string to be displayed in the dispatcher menu.
2408 cmd An agenda command, similar to the above. However, tree commands
2409 are no allowed, but instead you can get agenda and global todo list.
2410 So valid commands for a set are:
2411 (agenda)
2412 (alltodo)
2413 (stuck)
2414 (todo \"match\" options files)
2415 (search \"match\" options files)
2416 (tags \"match\" options files)
2417 (tags-todo \"match\" options files)
2419 Each command can carry a list of options, and another set of options can be
2420 given for the whole set of commands. Individual command options take
2421 precedence over the general options.
2423 When using several characters as key to a command, the first characters
2424 are prefix commands. For the dispatcher to display useful information, you
2425 should provide a description for the prefix, like
2427 (setq org-agenda-custom-commands
2428 '((\"h\" . \"HOME + Name tag searches\") ; describe prefix \"h\"
2429 (\"hl\" tags \"+HOME+Lisa\")
2430 (\"hp\" tags \"+HOME+Peter\")
2431 (\"hk\" tags \"+HOME+Kim\")))"
2432 :group 'org-agenda-custom-commands
2433 :type '(repeat
2434 (choice :value ("a" "" tags "" nil)
2435 (list :tag "Single command"
2436 (string :tag "Access Key(s) ")
2437 (option (string :tag "Description"))
2438 (choice
2439 (const :tag "Agenda" agenda)
2440 (const :tag "TODO list" alltodo)
2441 (const :tag "Search words" search)
2442 (const :tag "Stuck projects" stuck)
2443 (const :tag "Tags search (all agenda files)" tags)
2444 (const :tag "Tags search of TODO entries (all agenda files)" tags-todo)
2445 (const :tag "TODO keyword search (all agenda files)" todo)
2446 (const :tag "Tags sparse tree (current buffer)" tags-tree)
2447 (const :tag "TODO keyword tree (current buffer)" todo-tree)
2448 (const :tag "Occur tree (current buffer)" occur-tree)
2449 (sexp :tag "Other, user-defined function"))
2450 (string :tag "Match")
2451 (repeat :tag "Local options"
2452 (list (variable :tag "Option") (sexp :tag "Value")))
2453 (option (repeat :tag "Export" (file :tag "Export to"))))
2454 (list :tag "Command series, all agenda files"
2455 (string :tag "Access Key(s)")
2456 (string :tag "Description ")
2457 (repeat
2458 (choice
2459 (const :tag "Agenda" (agenda))
2460 (const :tag "TODO list" (alltodo))
2461 (list :tag "Search words"
2462 (const :format "" search)
2463 (string :tag "Match")
2464 (repeat :tag "Local options"
2465 (list (variable :tag "Option")
2466 (sexp :tag "Value"))))
2467 (const :tag "Stuck projects" (stuck))
2468 (list :tag "Tags search"
2469 (const :format "" tags)
2470 (string :tag "Match")
2471 (repeat :tag "Local options"
2472 (list (variable :tag "Option")
2473 (sexp :tag "Value"))))
2475 (list :tag "Tags search, TODO entries only"
2476 (const :format "" tags-todo)
2477 (string :tag "Match")
2478 (repeat :tag "Local options"
2479 (list (variable :tag "Option")
2480 (sexp :tag "Value"))))
2482 (list :tag "TODO keyword search"
2483 (const :format "" todo)
2484 (string :tag "Match")
2485 (repeat :tag "Local options"
2486 (list (variable :tag "Option")
2487 (sexp :tag "Value"))))
2489 (list :tag "Other, user-defined function"
2490 (symbol :tag "function")
2491 (string :tag "Match")
2492 (repeat :tag "Local options"
2493 (list (variable :tag "Option")
2494 (sexp :tag "Value"))))))
2496 (repeat :tag "General options"
2497 (list (variable :tag "Option")
2498 (sexp :tag "Value")))
2499 (option (repeat :tag "Export" (file :tag "Export to"))))
2500 (cons :tag "Prefix key documentation"
2501 (string :tag "Access Key(s)")
2502 (string :tag "Description ")))))
2504 (defcustom org-agenda-query-register ?o
2505 "The register holding the current query string.
2506 The prupose of this is that if you construct a query string interactively,
2507 you can then use it to define a custom command."
2508 :group 'org-agenda-custom-commands
2509 :type 'character)
2511 (defcustom org-stuck-projects
2512 '("+LEVEL=2/-DONE" ("TODO" "NEXT" "NEXTACTION") nil "")
2513 "How to identify stuck projects.
2514 This is a list of four items:
2515 1. A tags/todo matcher string that is used to identify a project.
2516 The entire tree below a headline matched by this is considered one project.
2517 2. A list of TODO keywords identifying non-stuck projects.
2518 If the project subtree contains any headline with one of these todo
2519 keywords, the project is considered to be not stuck. If you specify
2520 \"*\" as a keyword, any TODO keyword will mark the project unstuck.
2521 3. A list of tags identifying non-stuck projects.
2522 If the project subtree contains any headline with one of these tags,
2523 the project is considered to be not stuck. If you specify \"*\" as
2524 a tag, any tag will mark the project unstuck.
2525 4. An arbitrary regular expression matching non-stuck projects.
2527 After defining this variable, you may use \\[org-agenda-list-stuck-projects]
2528 or `C-c a #' to produce the list."
2529 :group 'org-agenda-custom-commands
2530 :type '(list
2531 (string :tag "Tags/TODO match to identify a project")
2532 (repeat :tag "Projects are *not* stuck if they have an entry with TODO keyword any of" (string))
2533 (repeat :tag "Projects are *not* stuck if they have an entry with TAG being any of" (string))
2534 (regexp :tag "Projects are *not* stuck if this regexp matches\ninside the subtree")))
2537 (defgroup org-agenda-skip nil
2538 "Options concerning skipping parts of agenda files."
2539 :tag "Org Agenda Skip"
2540 :group 'org-agenda)
2542 (defcustom org-agenda-todo-list-sublevels t
2543 "Non-nil means, check also the sublevels of a TODO entry for TODO entries.
2544 When nil, the sublevels of a TODO entry are not checked, resulting in
2545 potentially much shorter TODO lists."
2546 :group 'org-agenda-skip
2547 :group 'org-todo
2548 :type 'boolean)
2550 (defcustom org-agenda-todo-ignore-with-date nil
2551 "Non-nil means, don't show entries with a date in the global todo list.
2552 You can use this if you prefer to mark mere appointments with a TODO keyword,
2553 but don't want them to show up in the TODO list.
2554 When this is set, it also covers deadlines and scheduled items, the settings
2555 of `org-agenda-todo-ignore-scheduled' and `org-agenda-todo-ignore-deadlines'
2556 will be ignored."
2557 :group 'org-agenda-skip
2558 :group 'org-todo
2559 :type 'boolean)
2561 (defcustom org-agenda-todo-ignore-scheduled nil
2562 "Non-nil means, don't show scheduled entries in the global todo list.
2563 The idea behind this is that by scheduling it, you have already taken care
2564 of this item.
2565 See also `org-agenda-todo-ignore-with-date'."
2566 :group 'org-agenda-skip
2567 :group 'org-todo
2568 :type 'boolean)
2570 (defcustom org-agenda-todo-ignore-deadlines nil
2571 "Non-nil means, don't show near deadline entries in the global todo list.
2572 Near means closer than `org-deadline-warning-days' days.
2573 The idea behind this is that such items will appear in the agenda anyway.
2574 See also `org-agenda-todo-ignore-with-date'."
2575 :group 'org-agenda-skip
2576 :group 'org-todo
2577 :type 'boolean)
2579 (defcustom org-agenda-skip-scheduled-if-done nil
2580 "Non-nil means don't show scheduled items in agenda when they are done.
2581 This is relevant for the daily/weekly agenda, not for the TODO list. And
2582 it applies only to the actual date of the scheduling. Warnings about
2583 an item with a past scheduling dates are always turned off when the item
2584 is DONE."
2585 :group 'org-agenda-skip
2586 :type 'boolean)
2588 (defcustom org-agenda-skip-deadline-if-done nil
2589 "Non-nil means don't show deadines when the corresponding item is done.
2590 When nil, the deadline is still shown and should give you a happy feeling.
2591 This is relevant for the daily/weekly agenda. And it applied only to the
2592 actualy date of the deadline. Warnings about approching and past-due
2593 deadlines are always turned off when the item is DONE."
2594 :group 'org-agenda-skip
2595 :type 'boolean)
2597 (defcustom org-agenda-skip-timestamp-if-done nil
2598 "Non-nil means don't select item by timestamp or -range if it is DONE."
2599 :group 'org-agenda-skip
2600 :type 'boolean)
2602 (defcustom org-timeline-show-empty-dates 3
2603 "Non-nil means, `org-timeline' also shows dates without an entry.
2604 When nil, only the days which actually have entries are shown.
2605 When t, all days between the first and the last date are shown.
2606 When an integer, show also empty dates, but if there is a gap of more than
2607 N days, just insert a special line indicating the size of the gap."
2608 :group 'org-agenda-skip
2609 :type '(choice
2610 (const :tag "None" nil)
2611 (const :tag "All" t)
2612 (number :tag "at most")))
2615 (defgroup org-agenda-startup nil
2616 "Options concerning initial settings in the Agenda in Org Mode."
2617 :tag "Org Agenda Startup"
2618 :group 'org-agenda)
2620 (defcustom org-finalize-agenda-hook nil
2621 "Hook run just before displaying an agenda buffer."
2622 :group 'org-agenda-startup
2623 :type 'hook)
2625 (defcustom org-agenda-mouse-1-follows-link nil
2626 "Non-nil means, mouse-1 on a link will follow the link in the agenda.
2627 A longer mouse click will still set point. Does not wortk on XEmacs.
2628 Needs to be set before org.el is loaded."
2629 :group 'org-agenda-startup
2630 :type 'boolean)
2632 (defcustom org-agenda-start-with-follow-mode nil
2633 "The initial value of follow-mode in a newly created agenda window."
2634 :group 'org-agenda-startup
2635 :type 'boolean)
2637 (defgroup org-agenda-windows nil
2638 "Options concerning the windows used by the Agenda in Org Mode."
2639 :tag "Org Agenda Windows"
2640 :group 'org-agenda)
2642 (defcustom org-agenda-window-setup 'reorganize-frame
2643 "How the agenda buffer should be displayed.
2644 Possible values for this option are:
2646 current-window Show agenda in the current window, keeping all other windows.
2647 other-frame Use `switch-to-buffer-other-frame' to display agenda.
2648 other-window Use `switch-to-buffer-other-window' to display agenda.
2649 reorganize-frame Show only two windows on the current frame, the current
2650 window and the agenda.
2651 See also the variable `org-agenda-restore-windows-after-quit'."
2652 :group 'org-agenda-windows
2653 :type '(choice
2654 (const current-window)
2655 (const other-frame)
2656 (const other-window)
2657 (const reorganize-frame)))
2659 (defcustom org-agenda-window-frame-fractions '(0.5 . 0.75)
2660 "The min and max height of the agenda window as a fraction of frame height.
2661 The value of the variable is a cons cell with two numbers between 0 and 1.
2662 It only matters if `org-agenda-window-setup' is `reorganize-frame'."
2663 :group 'org-agenda-windows
2664 :type '(cons (number :tag "Minimum") (number :tag "Maximum")))
2666 (defcustom org-agenda-restore-windows-after-quit nil
2667 "Non-nil means, restore window configuration open exiting agenda.
2668 Before the window configuration is changed for displaying the agenda,
2669 the current status is recorded. When the agenda is exited with
2670 `q' or `x' and this option is set, the old state is restored. If
2671 `org-agenda-window-setup' is `other-frame', the value of this
2672 option will be ignored.."
2673 :group 'org-agenda-windows
2674 :type 'boolean)
2676 (defcustom org-indirect-buffer-display 'other-window
2677 "How should indirect tree buffers be displayed?
2678 This applies to indirect buffers created with the commands
2679 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
2680 Valid values are:
2681 current-window Display in the current window
2682 other-window Just display in another window.
2683 dedicated-frame Create one new frame, and re-use it each time.
2684 new-frame Make a new frame each time. Note that in this case
2685 previously-made indirect buffers are kept, and you need to
2686 kill these buffers yourself."
2687 :group 'org-structure
2688 :group 'org-agenda-windows
2689 :type '(choice
2690 (const :tag "In current window" current-window)
2691 (const :tag "In current frame, other window" other-window)
2692 (const :tag "Each time a new frame" new-frame)
2693 (const :tag "One dedicated frame" dedicated-frame)))
2695 (defgroup org-agenda-daily/weekly nil
2696 "Options concerning the daily/weekly agenda."
2697 :tag "Org Agenda Daily/Weekly"
2698 :group 'org-agenda)
2700 (defcustom org-agenda-ndays 7
2701 "Number of days to include in overview display.
2702 Should be 1 or 7."
2703 :group 'org-agenda-daily/weekly
2704 :type 'number)
2706 (defcustom org-agenda-start-on-weekday 1
2707 "Non-nil means, start the overview always on the specified weekday.
2708 0 denotes Sunday, 1 denotes Monday etc.
2709 When nil, always start on the current day."
2710 :group 'org-agenda-daily/weekly
2711 :type '(choice (const :tag "Today" nil)
2712 (number :tag "Weekday No.")))
2714 (defcustom org-agenda-show-all-dates t
2715 "Non-nil means, `org-agenda' shows every day in the selected range.
2716 When nil, only the days which actually have entries are shown."
2717 :group 'org-agenda-daily/weekly
2718 :type 'boolean)
2720 (defcustom org-agenda-format-date 'org-agenda-format-date-aligned
2721 "Format string for displaying dates in the agenda.
2722 Used by the daily/weekly agenda and by the timeline. This should be
2723 a format string understood by `format-time-string', or a function returning
2724 the formatted date as a string. The function must take a single argument,
2725 a calendar-style date list like (month day year)."
2726 :group 'org-agenda-daily/weekly
2727 :type '(choice
2728 (string :tag "Format string")
2729 (function :tag "Function")))
2731 (defun org-agenda-format-date-aligned (date)
2732 "Format a date string for display in the daily/weekly agenda, or timeline.
2733 This function makes sure that dates are aligned for easy reading."
2734 (format "%-9s %2d %s %4d"
2735 (calendar-day-name date)
2736 (extract-calendar-day date)
2737 (calendar-month-name (extract-calendar-month date))
2738 (extract-calendar-year date)))
2740 (defcustom org-agenda-include-diary nil
2741 "If non-nil, include in the agenda entries from the Emacs Calendar's diary."
2742 :group 'org-agenda-daily/weekly
2743 :type 'boolean)
2745 (defcustom org-agenda-include-all-todo nil
2746 "Set means weekly/daily agenda will always contain all TODO entries.
2747 The TODO entries will be listed at the top of the agenda, before
2748 the entries for specific days."
2749 :group 'org-agenda-daily/weekly
2750 :type 'boolean)
2752 (defcustom org-agenda-repeating-timestamp-show-all t
2753 "Non-nil means, show all occurences of a repeating stamp in the agenda.
2754 When nil, only one occurence is shown, either today or the
2755 nearest into the future."
2756 :group 'org-agenda-daily/weekly
2757 :type 'boolean)
2759 (defcustom org-deadline-warning-days 14
2760 "No. of days before expiration during which a deadline becomes active.
2761 This variable governs the display in sparse trees and in the agenda.
2762 When 0 or negative, it means use this number (the absolute value of it)
2763 even if a deadline has a different individual lead time specified."
2764 :group 'org-time
2765 :group 'org-agenda-daily/weekly
2766 :type 'number)
2768 (defcustom org-scheduled-past-days 10000
2769 "No. of days to continue listing scheduled items that are not marked DONE.
2770 When an item is scheduled on a date, it shows up in the agenda on this
2771 day and will be listed until it is marked done for the number of days
2772 given here."
2773 :group 'org-agenda-daily/weekly
2774 :type 'number)
2776 (defgroup org-agenda-time-grid nil
2777 "Options concerning the time grid in the Org-mode Agenda."
2778 :tag "Org Agenda Time Grid"
2779 :group 'org-agenda)
2781 (defcustom org-agenda-use-time-grid t
2782 "Non-nil means, show a time grid in the agenda schedule.
2783 A time grid is a set of lines for specific times (like every two hours between
2784 8:00 and 20:00). The items scheduled for a day at specific times are
2785 sorted in between these lines.
2786 For details about when the grid will be shown, and what it will look like, see
2787 the variable `org-agenda-time-grid'."
2788 :group 'org-agenda-time-grid
2789 :type 'boolean)
2791 (defcustom org-agenda-time-grid
2792 '((daily today require-timed)
2793 "----------------"
2794 (800 1000 1200 1400 1600 1800 2000))
2796 "The settings for time grid for agenda display.
2797 This is a list of three items. The first item is again a list. It contains
2798 symbols specifying conditions when the grid should be displayed:
2800 daily if the agenda shows a single day
2801 weekly if the agenda shows an entire week
2802 today show grid on current date, independent of daily/weekly display
2803 require-timed show grid only if at least one item has a time specification
2805 The second item is a string which will be places behing the grid time.
2807 The third item is a list of integers, indicating the times that should have
2808 a grid line."
2809 :group 'org-agenda-time-grid
2810 :type
2811 '(list
2812 (set :greedy t :tag "Grid Display Options"
2813 (const :tag "Show grid in single day agenda display" daily)
2814 (const :tag "Show grid in weekly agenda display" weekly)
2815 (const :tag "Always show grid for today" today)
2816 (const :tag "Show grid only if any timed entries are present"
2817 require-timed)
2818 (const :tag "Skip grid times already present in an entry"
2819 remove-match))
2820 (string :tag "Grid String")
2821 (repeat :tag "Grid Times" (integer :tag "Time"))))
2823 (defgroup org-agenda-sorting nil
2824 "Options concerning sorting in the Org-mode Agenda."
2825 :tag "Org Agenda Sorting"
2826 :group 'org-agenda)
2828 (defconst org-sorting-choice
2829 '(choice
2830 (const time-up) (const time-down)
2831 (const category-keep) (const category-up) (const category-down)
2832 (const tag-down) (const tag-up)
2833 (const priority-up) (const priority-down))
2834 "Sorting choices.")
2836 (defcustom org-agenda-sorting-strategy
2837 '((agenda time-up category-keep priority-down)
2838 (todo category-keep priority-down)
2839 (tags category-keep priority-down)
2840 (search category-keep))
2841 "Sorting structure for the agenda items of a single day.
2842 This is a list of symbols which will be used in sequence to determine
2843 if an entry should be listed before another entry. The following
2844 symbols are recognized:
2846 time-up Put entries with time-of-day indications first, early first
2847 time-down Put entries with time-of-day indications first, late first
2848 category-keep Keep the default order of categories, corresponding to the
2849 sequence in `org-agenda-files'.
2850 category-up Sort alphabetically by category, A-Z.
2851 category-down Sort alphabetically by category, Z-A.
2852 tag-up Sort alphabetically by last tag, A-Z.
2853 tag-down Sort alphabetically by last tag, Z-A.
2854 priority-up Sort numerically by priority, high priority last.
2855 priority-down Sort numerically by priority, high priority first.
2857 The different possibilities will be tried in sequence, and testing stops
2858 if one comparison returns a \"not-equal\". For example, the default
2859 '(time-up category-keep priority-down)
2860 means: Pull out all entries having a specified time of day and sort them,
2861 in order to make a time schedule for the current day the first thing in the
2862 agenda listing for the day. Of the entries without a time indication, keep
2863 the grouped in categories, don't sort the categories, but keep them in
2864 the sequence given in `org-agenda-files'. Within each category sort by
2865 priority.
2867 Leaving out `category-keep' would mean that items will be sorted across
2868 categories by priority.
2870 Instead of a single list, this can also be a set of list for specific
2871 contents, with a context symbol in the car of the list, any of
2872 `agenda', `todo', `tags' for the corresponding agenda views."
2873 :group 'org-agenda-sorting
2874 :type `(choice
2875 (repeat :tag "General" ,org-sorting-choice)
2876 (list :tag "Individually"
2877 (cons (const :tag "Strategy for Weekly/Daily agenda" agenda)
2878 (repeat ,org-sorting-choice))
2879 (cons (const :tag "Strategy for TODO lists" todo)
2880 (repeat ,org-sorting-choice))
2881 (cons (const :tag "Strategy for Tags matches" tags)
2882 (repeat ,org-sorting-choice)))))
2884 (defcustom org-sort-agenda-notime-is-late t
2885 "Non-nil means, items without time are considered late.
2886 This is only relevant for sorting. When t, items which have no explicit
2887 time like 15:30 will be considered as 99:01, i.e. later than any items which
2888 do have a time. When nil, the default time is before 0:00. You can use this
2889 option to decide if the schedule for today should come before or after timeless
2890 agenda entries."
2891 :group 'org-agenda-sorting
2892 :type 'boolean)
2894 (defgroup org-agenda-line-format nil
2895 "Options concerning the entry prefix in the Org-mode agenda display."
2896 :tag "Org Agenda Line Format"
2897 :group 'org-agenda)
2899 (defcustom org-agenda-prefix-format
2900 '((agenda . " %-12:c%?-12t% s")
2901 (timeline . " % s")
2902 (todo . " %-12:c")
2903 (tags . " %-12:c")
2904 (search . " %-12:c"))
2905 "Format specifications for the prefix of items in the agenda views.
2906 An alist with four entries, for the different agenda types. The keys to the
2907 sublists are `agenda', `timeline', `todo', and `tags'. The values
2908 are format strings.
2909 This format works similar to a printf format, with the following meaning:
2911 %c the category of the item, \"Diary\" for entries from the diary, or
2912 as given by the CATEGORY keyword or derived from the file name.
2913 %T the *last* tag of the item. Last because inherited tags come
2914 first in the list.
2915 %t the time-of-day specification if one applies to the entry, in the
2916 format HH:MM
2917 %s Scheduling/Deadline information, a short string
2919 All specifiers work basically like the standard `%s' of printf, but may
2920 contain two additional characters: A question mark just after the `%' and
2921 a whitespace/punctuation character just before the final letter.
2923 If the first character after `%' is a question mark, the entire field
2924 will only be included if the corresponding value applies to the
2925 current entry. This is useful for fields which should have fixed
2926 width when present, but zero width when absent. For example,
2927 \"%?-12t\" will result in a 12 character time field if a time of the
2928 day is specified, but will completely disappear in entries which do
2929 not contain a time.
2931 If there is punctuation or whitespace character just before the final
2932 format letter, this character will be appended to the field value if
2933 the value is not empty. For example, the format \"%-12:c\" leads to
2934 \"Diary: \" if the category is \"Diary\". If the category were be
2935 empty, no additional colon would be interted.
2937 The default value of this option is \" %-12:c%?-12t% s\", meaning:
2938 - Indent the line with two space characters
2939 - Give the category in a 12 chars wide field, padded with whitespace on
2940 the right (because of `-'). Append a colon if there is a category
2941 (because of `:').
2942 - If there is a time-of-day, put it into a 12 chars wide field. If no
2943 time, don't put in an empty field, just skip it (because of '?').
2944 - Finally, put the scheduling information and append a whitespace.
2946 As another example, if you don't want the time-of-day of entries in
2947 the prefix, you could use:
2949 (setq org-agenda-prefix-format \" %-11:c% s\")
2951 See also the variables `org-agenda-remove-times-when-in-prefix' and
2952 `org-agenda-remove-tags'."
2953 :type '(choice
2954 (string :tag "General format")
2955 (list :greedy t :tag "View dependent"
2956 (cons (const agenda) (string :tag "Format"))
2957 (cons (const timeline) (string :tag "Format"))
2958 (cons (const todo) (string :tag "Format"))
2959 (cons (const tags) (string :tag "Format"))
2960 (cons (const search) (string :tag "Format"))))
2961 :group 'org-agenda-line-format)
2963 (defvar org-prefix-format-compiled nil
2964 "The compiled version of the most recently used prefix format.
2965 See the variable `org-agenda-prefix-format'.")
2967 (defcustom org-agenda-todo-keyword-format "%-1s"
2968 "Format for the TODO keyword in agenda lines.
2969 Set this to something like \"%-12s\" if you want all TODO keywords
2970 to occupy a fixed space in the agenda display."
2971 :group 'org-agenda-line-format
2972 :type 'string)
2974 (defcustom org-agenda-scheduled-leaders '("Scheduled: " "Sched.%2dx: ")
2975 "Text preceeding scheduled items in the agenda view.
2976 This is a list with two strings. The first applies when the item is
2977 scheduled on the current day. The second applies when it has been scheduled
2978 previously, it may contain a %d to capture how many days ago the item was
2979 scheduled."
2980 :group 'org-agenda-line-format
2981 :type '(list
2982 (string :tag "Scheduled today ")
2983 (string :tag "Scheduled previously")))
2985 (defcustom org-agenda-deadline-leaders '("Deadline: " "In %3d d.: ")
2986 "Text preceeding deadline items in the agenda view.
2987 This is a list with two strings. The first applies when the item has its
2988 deadline on the current day. The second applies when it is in the past or
2989 in the future, it may contain %d to capture how many days away the deadline
2990 is (was)."
2991 :group 'org-agenda-line-format
2992 :type '(list
2993 (string :tag "Deadline today ")
2994 (string :tag "Deadline relative")))
2996 (defcustom org-agenda-remove-times-when-in-prefix t
2997 "Non-nil means, remove duplicate time specifications in agenda items.
2998 When the format `org-agenda-prefix-format' contains a `%t' specifier, a
2999 time-of-day specification in a headline or diary entry is extracted and
3000 placed into the prefix. If this option is non-nil, the original specification
3001 \(a timestamp or -range, or just a plain time(range) specification like
3002 11:30-4pm) will be removed for agenda display. This makes the agenda less
3003 cluttered.
3004 The option can be t or nil. It may also be the symbol `beg', indicating
3005 that the time should only be removed what it is located at the beginning of
3006 the headline/diary entry."
3007 :group 'org-agenda-line-format
3008 :type '(choice
3009 (const :tag "Always" t)
3010 (const :tag "Never" nil)
3011 (const :tag "When at beginning of entry" beg)))
3014 (defcustom org-agenda-default-appointment-duration nil
3015 "Default duration for appointments that only have a starting time.
3016 When nil, no duration is specified in such cases.
3017 When non-nil, this must be the number of minutes, e.g. 60 for one hour."
3018 :group 'org-agenda-line-format
3019 :type '(choice
3020 (integer :tag "Minutes")
3021 (const :tag "No default duration")))
3024 (defcustom org-agenda-remove-tags nil
3025 "Non-nil means, remove the tags from the headline copy in the agenda.
3026 When this is the symbol `prefix', only remove tags when
3027 `org-agenda-prefix-format' contains a `%T' specifier."
3028 :group 'org-agenda-line-format
3029 :type '(choice
3030 (const :tag "Always" t)
3031 (const :tag "Never" nil)
3032 (const :tag "When prefix format contains %T" prefix)))
3034 (if (fboundp 'defvaralias)
3035 (defvaralias 'org-agenda-remove-tags-when-in-prefix
3036 'org-agenda-remove-tags))
3038 (defcustom org-agenda-tags-column -80
3039 "Shift tags in agenda items to this column.
3040 If this number is positive, it specifies the column. If it is negative,
3041 it means that the tags should be flushright to that column. For example,
3042 -80 works well for a normal 80 character screen."
3043 :group 'org-agenda-line-format
3044 :type 'integer)
3046 (if (fboundp 'defvaralias)
3047 (defvaralias 'org-agenda-align-tags-to-column 'org-agenda-tags-column))
3049 (defcustom org-agenda-fontify-priorities t
3050 "Non-nil means, highlight low and high priorities in agenda.
3051 When t, the highest priority entries are bold, lowest priority italic.
3052 This may also be an association list of priority faces. The face may be
3053 a names face, or a list like `(:background \"Red\")'."
3054 :group 'org-agenda-line-format
3055 :type '(choice
3056 (const :tag "Never" nil)
3057 (const :tag "Defaults" t)
3058 (repeat :tag "Specify"
3059 (list (character :tag "Priority" :value ?A)
3060 (sexp :tag "face")))))
3062 (defgroup org-latex nil
3063 "Options for embedding LaTeX code into Org-mode"
3064 :tag "Org LaTeX"
3065 :group 'org)
3067 (defcustom org-format-latex-options
3068 '(:foreground default :background default :scale 1.0
3069 :html-foreground "Black" :html-background "Transparent" :html-scale 1.0
3070 :matchers ("begin" "$" "$$" "\\(" "\\["))
3071 "Options for creating images from LaTeX fragments.
3072 This is a property list with the following properties:
3073 :foreground the foreground color for images embedded in emacs, e.g. \"Black\".
3074 `default' means use the forground of the default face.
3075 :background the background color, or \"Transparent\".
3076 `default' means use the background of the default face.
3077 :scale a scaling factor for the size of the images
3078 :html-foreground, :html-background, :html-scale
3079 The same numbers for HTML export.
3080 :matchers a list indicating which matchers should be used to
3081 find LaTeX fragments. Valid members of this list are:
3082 \"begin\" find environments
3083 \"$\" find math expressions surrounded by $...$
3084 \"$$\" find math expressions surrounded by $$....$$
3085 \"\\(\" find math expressions surrounded by \\(...\\)
3086 \"\\ [\" find math expressions surrounded by \\ [...\\]"
3087 :group 'org-latex
3088 :type 'plist)
3090 (defcustom org-format-latex-header "\\documentclass{article}
3091 \\usepackage{fullpage} % do not remove
3092 \\usepackage{amssymb}
3093 \\usepackage[usenames]{color}
3094 \\usepackage{amsmath}
3095 \\usepackage{latexsym}
3096 \\usepackage[mathscr]{eucal}
3097 \\pagestyle{empty} % do not remove"
3098 "The document header used for processing LaTeX fragments."
3099 :group 'org-latex
3100 :type 'string)
3102 (defgroup org-export nil
3103 "Options for exporting org-listings."
3104 :tag "Org Export"
3105 :group 'org)
3107 (defgroup org-export-general nil
3108 "General options for exporting Org-mode files."
3109 :tag "Org Export General"
3110 :group 'org-export)
3112 ;; FIXME
3113 (defvar org-export-publishing-directory nil)
3115 (defcustom org-export-with-special-strings t
3116 "Non-nil means, interpret \"\-\", \"--\" and \"---\" for export.
3117 When this option is turned on, these strings will be exported as:
3119 Org HTML LaTeX
3120 -----+----------+--------
3121 \\- &shy; \\-
3122 -- &ndash; --
3123 --- &mdash; ---
3124 ... &hellip; \ldots
3126 This option can also be set with the +OPTIONS line, e.g. \"-:nil\"."
3127 :group 'org-export-translation
3128 :type 'boolean)
3130 (defcustom org-export-language-setup
3131 '(("en" "Author" "Date" "Table of Contents")
3132 ("cs" "Autor" "Datum" "Obsah")
3133 ("da" "Ophavsmand" "Dato" "Indhold")
3134 ("de" "Autor" "Datum" "Inhaltsverzeichnis")
3135 ("es" "Autor" "Fecha" "\xcdndice")
3136 ("fr" "Auteur" "Date" "Table des mati\xe8res")
3137 ("it" "Autore" "Data" "Indice")
3138 ("nl" "Auteur" "Datum" "Inhoudsopgave")
3139 ("nn" "Forfattar" "Dato" "Innhold") ;; nn = Norsk (nynorsk)
3140 ("sv" "F\xf6rfattarens" "Datum" "Inneh\xe5ll"))
3141 "Terms used in export text, translated to different languages.
3142 Use the variable `org-export-default-language' to set the language,
3143 or use the +OPTION lines for a per-file setting."
3144 :group 'org-export-general
3145 :type '(repeat
3146 (list
3147 (string :tag "HTML language tag")
3148 (string :tag "Author")
3149 (string :tag "Date")
3150 (string :tag "Table of Contents"))))
3152 (defcustom org-export-default-language "en"
3153 "The default language of HTML export, as a string.
3154 This should have an association in `org-export-language-setup'."
3155 :group 'org-export-general
3156 :type 'string)
3158 (defcustom org-export-skip-text-before-1st-heading t
3159 "Non-nil means, skip all text before the first headline when exporting.
3160 When nil, that text is exported as well."
3161 :group 'org-export-general
3162 :type 'boolean)
3164 (defcustom org-export-headline-levels 3
3165 "The last level which is still exported as a headline.
3166 Inferior levels will produce itemize lists when exported.
3167 Note that a numeric prefix argument to an exporter function overrides
3168 this setting.
3170 This option can also be set with the +OPTIONS line, e.g. \"H:2\"."
3171 :group 'org-export-general
3172 :type 'number)
3174 (defcustom org-export-with-section-numbers t
3175 "Non-nil means, add section numbers to headlines when exporting.
3177 This option can also be set with the +OPTIONS line, e.g. \"num:t\"."
3178 :group 'org-export-general
3179 :type 'boolean)
3181 (defcustom org-export-with-toc t
3182 "Non-nil means, create a table of contents in exported files.
3183 The TOC contains headlines with levels up to`org-export-headline-levels'.
3184 When an integer, include levels up to N in the toc, this may then be
3185 different from `org-export-headline-levels', but it will not be allowed
3186 to be larger than the number of headline levels.
3187 When nil, no table of contents is made.
3189 Headlines which contain any TODO items will be marked with \"(*)\" in
3190 ASCII export, and with red color in HTML output, if the option
3191 `org-export-mark-todo-in-toc' is set.
3193 In HTML output, the TOC will be clickable.
3195 This option can also be set with the +OPTIONS line, e.g. \"toc:nil\"
3196 or \"toc:3\"."
3197 :group 'org-export-general
3198 :type '(choice
3199 (const :tag "No Table of Contents" nil)
3200 (const :tag "Full Table of Contents" t)
3201 (integer :tag "TOC to level")))
3203 (defcustom org-export-mark-todo-in-toc nil
3204 "Non-nil means, mark TOC lines that contain any open TODO items."
3205 :group 'org-export-general
3206 :type 'boolean)
3208 (defcustom org-export-preserve-breaks nil
3209 "Non-nil means, preserve all line breaks when exporting.
3210 Normally, in HTML output paragraphs will be reformatted. In ASCII
3211 export, line breaks will always be preserved, regardless of this variable.
3213 This option can also be set with the +OPTIONS line, e.g. \"\\n:t\"."
3214 :group 'org-export-general
3215 :type 'boolean)
3217 (defcustom org-export-with-archived-trees 'headline
3218 "Whether subtrees with the ARCHIVE tag should be exported.
3219 This can have three different values
3220 nil Do not export, pretend this tree is not present
3221 t Do export the entire tree
3222 headline Only export the headline, but skip the tree below it."
3223 :group 'org-export-general
3224 :group 'org-archive
3225 :type '(choice
3226 (const :tag "not at all" nil)
3227 (const :tag "headline only" 'headline)
3228 (const :tag "entirely" t)))
3230 (defcustom org-export-author-info t
3231 "Non-nil means, insert author name and email into the exported file.
3233 This option can also be set with the +OPTIONS line,
3234 e.g. \"author-info:nil\"."
3235 :group 'org-export-general
3236 :type 'boolean)
3238 (defcustom org-export-time-stamp-file t
3239 "Non-nil means, insert a time stamp into the exported file.
3240 The time stamp shows when the file was created.
3242 This option can also be set with the +OPTIONS line,
3243 e.g. \"timestamp:nil\"."
3244 :group 'org-export-general
3245 :type 'boolean)
3247 (defcustom org-export-with-timestamps t
3248 "If nil, do not export time stamps and associated keywords."
3249 :group 'org-export-general
3250 :type 'boolean)
3252 (defcustom org-export-remove-timestamps-from-toc t
3253 "If nil, remove timestamps from the table of contents entries."
3254 :group 'org-export-general
3255 :type 'boolean)
3257 (defcustom org-export-with-tags 'not-in-toc
3258 "If nil, do not export tags, just remove them from headlines.
3259 If this is the symbol `not-in-toc', tags will be removed from table of
3260 contents entries, but still be shown in the headlines of the document.
3262 This option can also be set with the +OPTIONS line, e.g. \"tags:nil\"."
3263 :group 'org-export-general
3264 :type '(choice
3265 (const :tag "Off" nil)
3266 (const :tag "Not in TOC" not-in-toc)
3267 (const :tag "On" t)))
3269 (defcustom org-export-with-drawers nil
3270 "Non-nil means, export with drawers like the property drawer.
3271 When t, all drawers are exported. This may also be a list of
3272 drawer names to export."
3273 :group 'org-export-general
3274 :type '(choice
3275 (const :tag "All drawers" t)
3276 (const :tag "None" nil)
3277 (repeat :tag "Selected drawers"
3278 (string :tag "Drawer name"))))
3280 (defgroup org-export-translation nil
3281 "Options for translating special ascii sequences for the export backends."
3282 :tag "Org Export Translation"
3283 :group 'org-export)
3285 (defcustom org-export-with-emphasize t
3286 "Non-nil means, interpret *word*, /word/, and _word_ as emphasized text.
3287 If the export target supports emphasizing text, the word will be
3288 typeset in bold, italic, or underlined, respectively. Works only for
3289 single words, but you can say: I *really* *mean* *this*.
3290 Not all export backends support this.
3292 This option can also be set with the +OPTIONS line, e.g. \"*:nil\"."
3293 :group 'org-export-translation
3294 :type 'boolean)
3296 (defcustom org-export-with-footnotes t
3297 "If nil, export [1] as a footnote marker.
3298 Lines starting with [1] will be formatted as footnotes.
3300 This option can also be set with the +OPTIONS line, e.g. \"f:nil\"."
3301 :group 'org-export-translation
3302 :type 'boolean)
3304 (defcustom org-export-with-sub-superscripts t
3305 "Non-nil means, interpret \"_\" and \"^\" for export.
3306 When this option is turned on, you can use TeX-like syntax for sub- and
3307 superscripts. Several characters after \"_\" or \"^\" will be
3308 considered as a single item - so grouping with {} is normally not
3309 needed. For example, the following things will be parsed as single
3310 sub- or superscripts.
3312 10^24 or 10^tau several digits will be considered 1 item.
3313 10^-12 or 10^-tau a leading sign with digits or a word
3314 x^2-y^3 will be read as x^2 - y^3, because items are
3315 terminated by almost any nonword/nondigit char.
3316 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
3318 Still, ambiguity is possible - so when in doubt use {} to enclose the
3319 sub/superscript. If you set this variable to the symbol `{}',
3320 the braces are *required* in order to trigger interpretations as
3321 sub/superscript. This can be helpful in documents that need \"_\"
3322 frequently in plain text.
3324 Not all export backends support this, but HTML does.
3326 This option can also be set with the +OPTIONS line, e.g. \"^:nil\"."
3327 :group 'org-export-translation
3328 :type '(choice
3329 (const :tag "Always interpret" t)
3330 (const :tag "Only with braces" {})
3331 (const :tag "Never interpret" nil)))
3333 (defcustom org-export-with-special-strings t
3334 "Non-nil means, interpret \"\-\", \"--\" and \"---\" for export.
3335 When this option is turned on, these strings will be exported as:
3337 \\- : &shy;
3338 -- : &ndash;
3339 --- : &mdash;
3341 Not all export backends support this, but HTML does.
3343 This option can also be set with the +OPTIONS line, e.g. \"-:nil\"."
3344 :group 'org-export-translation
3345 :type 'boolean)
3347 (defcustom org-export-with-TeX-macros t
3348 "Non-nil means, interpret simple TeX-like macros when exporting.
3349 For example, HTML export converts \\alpha to &alpha; and \\AA to &Aring;.
3350 No only real TeX macros will work here, but the standard HTML entities
3351 for math can be used as macro names as well. For a list of supported
3352 names in HTML export, see the constant `org-html-entities'.
3353 Not all export backends support this.
3355 This option can also be set with the +OPTIONS line, e.g. \"TeX:nil\"."
3356 :group 'org-export-translation
3357 :group 'org-export-latex
3358 :type 'boolean)
3360 (defcustom org-export-with-LaTeX-fragments nil
3361 "Non-nil means, convert LaTeX fragments to images when exporting to HTML.
3362 When set, the exporter will find LaTeX environments if the \\begin line is
3363 the first non-white thing on a line. It will also find the math delimiters
3364 like $a=b$ and \\( a=b \\) for inline math, $$a=b$$ and \\[ a=b \\] for
3365 display math.
3367 This option can also be set with the +OPTIONS line, e.g. \"LaTeX:t\"."
3368 :group 'org-export-translation
3369 :group 'org-export-latex
3370 :type 'boolean)
3372 (defcustom org-export-with-fixed-width t
3373 "Non-nil means, lines starting with \":\" will be in fixed width font.
3374 This can be used to have pre-formatted text, fragments of code etc. For
3375 example:
3376 : ;; Some Lisp examples
3377 : (while (defc cnt)
3378 : (ding))
3379 will be looking just like this in also HTML. See also the QUOTE keyword.
3380 Not all export backends support this.
3382 This option can also be set with the +OPTIONS line, e.g. \"::nil\"."
3383 :group 'org-export-translation
3384 :type 'boolean)
3386 (defcustom org-match-sexp-depth 3
3387 "Number of stacked braces for sub/superscript matching.
3388 This has to be set before loading org.el to be effective."
3389 :group 'org-export-translation
3390 :type 'integer)
3392 (defgroup org-export-tables nil
3393 "Options for exporting tables in Org-mode."
3394 :tag "Org Export Tables"
3395 :group 'org-export)
3397 (defcustom org-export-with-tables t
3398 "If non-nil, lines starting with \"|\" define a table.
3399 For example:
3401 | Name | Address | Birthday |
3402 |-------------+----------+-----------|
3403 | Arthur Dent | England | 29.2.2100 |
3405 Not all export backends support this.
3407 This option can also be set with the +OPTIONS line, e.g. \"|:nil\"."
3408 :group 'org-export-tables
3409 :type 'boolean)
3411 (defcustom org-export-highlight-first-table-line t
3412 "Non-nil means, highlight the first table line.
3413 In HTML export, this means use <th> instead of <td>.
3414 In tables created with table.el, this applies to the first table line.
3415 In Org-mode tables, all lines before the first horizontal separator
3416 line will be formatted with <th> tags."
3417 :group 'org-export-tables
3418 :type 'boolean)
3420 (defcustom org-export-table-remove-special-lines t
3421 "Remove special lines and marking characters in calculating tables.
3422 This removes the special marking character column from tables that are set
3423 up for spreadsheet calculations. It also removes the entire lines
3424 marked with `!', `_', or `^'. The lines with `$' are kept, because
3425 the values of constants may be useful to have."
3426 :group 'org-export-tables
3427 :type 'boolean)
3429 (defcustom org-export-prefer-native-exporter-for-tables nil
3430 "Non-nil means, always export tables created with table.el natively.
3431 Natively means, use the HTML code generator in table.el.
3432 When nil, Org-mode's own HTML generator is used when possible (i.e. if
3433 the table does not use row- or column-spanning). This has the
3434 advantage, that the automatic HTML conversions for math symbols and
3435 sub/superscripts can be applied. Org-mode's HTML generator is also
3436 much faster."
3437 :group 'org-export-tables
3438 :type 'boolean)
3440 (defgroup org-export-ascii nil
3441 "Options specific for ASCII export of Org-mode files."
3442 :tag "Org Export ASCII"
3443 :group 'org-export)
3445 (defcustom org-export-ascii-underline '(?\$ ?\# ?^ ?\~ ?\= ?\-)
3446 "Characters for underlining headings in ASCII export.
3447 In the given sequence, these characters will be used for level 1, 2, ..."
3448 :group 'org-export-ascii
3449 :type '(repeat character))
3451 (defcustom org-export-ascii-bullets '(?* ?+ ?-)
3452 "Bullet characters for headlines converted to lists in ASCII export.
3453 The first character is used for the first lest level generated in this
3454 way, and so on. If there are more levels than characters given here,
3455 the list will be repeated.
3456 Note that plain lists will keep the same bullets as the have in the
3457 Org-mode file."
3458 :group 'org-export-ascii
3459 :type '(repeat character))
3461 (defgroup org-export-xml nil
3462 "Options specific for XML export of Org-mode files."
3463 :tag "Org Export XML"
3464 :group 'org-export)
3466 (defgroup org-export-html nil
3467 "Options specific for HTML export of Org-mode files."
3468 :tag "Org Export HTML"
3469 :group 'org-export)
3471 (defcustom org-export-html-coding-system nil
3473 :group 'org-export-html
3474 :type 'coding-system)
3476 (defcustom org-export-html-extension "html"
3477 "The extension for exported HTML files."
3478 :group 'org-export-html
3479 :type 'string)
3481 (defcustom org-export-html-style
3482 "<style type=\"text/css\">
3483 html {
3484 font-family: Times, serif;
3485 font-size: 12pt;
3487 .title { text-align: center; }
3488 .todo { color: red; }
3489 .done { color: green; }
3490 .timestamp { color: grey }
3491 .timestamp-kwd { color: CadetBlue }
3492 .tag { background-color:lightblue; font-weight:normal }
3493 .target { background-color: lavender; }
3494 pre {
3495 border: 1pt solid #AEBDCC;
3496 background-color: #F3F5F7;
3497 padding: 5pt;
3498 font-family: courier, monospace;
3500 table { border-collapse: collapse; }
3501 td, th {
3502 vertical-align: top;
3503 <!--border: 1pt solid #ADB9CC;-->
3505 </style>"
3506 "The default style specification for exported HTML files.
3507 Since there are different ways of setting style information, this variable
3508 needs to contain the full HTML structure to provide a style, including the
3509 surrounding HTML tags. The style specifications should include definitions
3510 for new classes todo, done, title, and deadline. For example, legal values
3511 would be:
3513 <style type=\"text/css\">
3514 p { font-weight: normal; color: gray; }
3515 h1 { color: black; }
3516 .title { text-align: center; }
3517 .todo, .deadline { color: red; }
3518 .done { color: green; }
3519 </style>
3521 or, if you want to keep the style in a file,
3523 <link rel=\"stylesheet\" type=\"text/css\" href=\"mystyles.css\">
3525 As the value of this option simply gets inserted into the HTML <head> header,
3526 you can \"misuse\" it to add arbitrary text to the header."
3527 :group 'org-export-html
3528 :type 'string)
3531 (defcustom org-export-html-title-format "<h1 class=\"title\">%s</h1>\n"
3532 "Format for typesetting the document title in HTML export."
3533 :group 'org-export-html
3534 :type 'string)
3536 (defcustom org-export-html-toplevel-hlevel 2
3537 "The <H> level for level 1 headings in HTML export."
3538 :group 'org-export-html
3539 :type 'string)
3541 (defcustom org-export-html-link-org-files-as-html t
3542 "Non-nil means, make file links to `file.org' point to `file.html'.
3543 When org-mode is exporting an org-mode file to HTML, links to
3544 non-html files are directly put into a href tag in HTML.
3545 However, links to other Org-mode files (recognized by the
3546 extension `.org.) should become links to the corresponding html
3547 file, assuming that the linked org-mode file will also be
3548 converted to HTML.
3549 When nil, the links still point to the plain `.org' file."
3550 :group 'org-export-html
3551 :type 'boolean)
3553 (defcustom org-export-html-inline-images 'maybe
3554 "Non-nil means, inline images into exported HTML pages.
3555 This is done using an <img> tag. When nil, an anchor with href is used to
3556 link to the image. If this option is `maybe', then images in links with
3557 an empty description will be inlined, while images with a description will
3558 be linked only."
3559 :group 'org-export-html
3560 :type '(choice (const :tag "Never" nil)
3561 (const :tag "Always" t)
3562 (const :tag "When there is no description" maybe)))
3564 ;; FIXME: rename
3565 (defcustom org-export-html-expand t
3566 "Non-nil means, for HTML export, treat @<...> as HTML tag.
3567 When nil, these tags will be exported as plain text and therefore
3568 not be interpreted by a browser.
3570 This option can also be set with the +OPTIONS line, e.g. \"@:nil\"."
3571 :group 'org-export-html
3572 :type 'boolean)
3574 (defcustom org-export-html-table-tag
3575 "<table border=\"2\" cellspacing=\"0\" cellpadding=\"6\" rules=\"groups\" frame=\"hsides\">"
3576 "The HTML tag that is used to start a table.
3577 This must be a <table> tag, but you may change the options like
3578 borders and spacing."
3579 :group 'org-export-html
3580 :type 'string)
3582 (defcustom org-export-table-header-tags '("<th>" . "</th>")
3583 "The opening tag for table header fields.
3584 This is customizable so that alignment options can be specified."
3585 :group 'org-export-tables
3586 :type '(cons (string :tag "Opening tag") (string :tag "Closing tag")))
3588 (defcustom org-export-table-data-tags '("<td>" . "</td>")
3589 "The opening tag for table data fields.
3590 This is customizable so that alignment options can be specified."
3591 :group 'org-export-tables
3592 :type '(cons (string :tag "Opening tag") (string :tag "Closing tag")))
3594 (defcustom org-export-html-with-timestamp nil
3595 "If non-nil, write `org-export-html-html-helper-timestamp'
3596 into the exported HTML text. Otherwise, the buffer will just be saved
3597 to a file."
3598 :group 'org-export-html
3599 :type 'boolean)
3601 (defcustom org-export-html-html-helper-timestamp
3602 "<br/><br/><hr><p><!-- hhmts start --> <!-- hhmts end --></p>\n"
3603 "The HTML tag used as timestamp delimiter for HTML-helper-mode."
3604 :group 'org-export-html
3605 :type 'string)
3607 (defgroup org-export-icalendar nil
3608 "Options specific for iCalendar export of Org-mode files."
3609 :tag "Org Export iCalendar"
3610 :group 'org-export)
3612 (defcustom org-combined-agenda-icalendar-file "~/org.ics"
3613 "The file name for the iCalendar file covering all agenda files.
3614 This file is created with the command \\[org-export-icalendar-all-agenda-files].
3615 The file name should be absolute, the file will be overwritten without warning."
3616 :group 'org-export-icalendar
3617 :type 'file)
3619 (defcustom org-icalendar-include-todo nil
3620 "Non-nil means, export to iCalendar files should also cover TODO items."
3621 :group 'org-export-icalendar
3622 :type '(choice
3623 (const :tag "None" nil)
3624 (const :tag "Unfinished" t)
3625 (const :tag "All" all)))
3627 (defcustom org-icalendar-include-sexps t
3628 "Non-nil means, export to iCalendar files should also cover sexp entries.
3629 These are entries like in the diary, but directly in an Org-mode file."
3630 :group 'org-export-icalendar
3631 :type 'boolean)
3633 (defcustom org-icalendar-include-body 100
3634 "Amount of text below headline to be included in iCalendar export.
3635 This is a number of characters that should maximally be included.
3636 Properties, scheduling and clocking lines will always be removed.
3637 The text will be inserted into the DESCRIPTION field."
3638 :group 'org-export-icalendar
3639 :type '(choice
3640 (const :tag "Nothing" nil)
3641 (const :tag "Everything" t)
3642 (integer :tag "Max characters")))
3644 (defcustom org-icalendar-combined-name "OrgMode"
3645 "Calendar name for the combined iCalendar representing all agenda files."
3646 :group 'org-export-icalendar
3647 :type 'string)
3649 (defgroup org-font-lock nil
3650 "Font-lock settings for highlighting in Org-mode."
3651 :tag "Org Font Lock"
3652 :group 'org)
3654 (defcustom org-level-color-stars-only nil
3655 "Non-nil means fontify only the stars in each headline.
3656 When nil, the entire headline is fontified.
3657 Changing it requires restart of `font-lock-mode' to become effective
3658 also in regions already fontified."
3659 :group 'org-font-lock
3660 :type 'boolean)
3662 (defcustom org-hide-leading-stars nil
3663 "Non-nil means, hide the first N-1 stars in a headline.
3664 This works by using the face `org-hide' for these stars. This
3665 face is white for a light background, and black for a dark
3666 background. You may have to customize the face `org-hide' to
3667 make this work.
3668 Changing it requires restart of `font-lock-mode' to become effective
3669 also in regions already fontified.
3670 You may also set this on a per-file basis by adding one of the following
3671 lines to the buffer:
3673 #+STARTUP: hidestars
3674 #+STARTUP: showstars"
3675 :group 'org-font-lock
3676 :type 'boolean)
3678 (defcustom org-fontify-done-headline nil
3679 "Non-nil means, change the face of a headline if it is marked DONE.
3680 Normally, only the TODO/DONE keyword indicates the state of a headline.
3681 When this is non-nil, the headline after the keyword is set to the
3682 `org-headline-done' as an additional indication."
3683 :group 'org-font-lock
3684 :type 'boolean)
3686 (defcustom org-fontify-emphasized-text t
3687 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
3688 Changing this variable requires a restart of Emacs to take effect."
3689 :group 'org-font-lock
3690 :type 'boolean)
3692 (defcustom org-highlight-latex-fragments-and-specials nil
3693 "Non-nil means, fontify what is treated specially by the exporters."
3694 :group 'org-font-lock
3695 :type 'boolean)
3697 (defcustom org-hide-emphasis-markers nil
3698 "Non-nil mean font-lock should hide the emphasis marker characters."
3699 :group 'org-font-lock
3700 :type 'boolean)
3702 (defvar org-emph-re nil
3703 "Regular expression for matching emphasis.")
3704 (defvar org-verbatim-re nil
3705 "Regular expression for matching verbatim text.")
3706 (defvar org-emphasis-regexp-components) ; defined just below
3707 (defvar org-emphasis-alist) ; defined just below
3708 (defun org-set-emph-re (var val)
3709 "Set variable and compute the emphasis regular expression."
3710 (set var val)
3711 (when (and (boundp 'org-emphasis-alist)
3712 (boundp 'org-emphasis-regexp-components)
3713 org-emphasis-alist org-emphasis-regexp-components)
3714 (let* ((e org-emphasis-regexp-components)
3715 (pre (car e))
3716 (post (nth 1 e))
3717 (border (nth 2 e))
3718 (body (nth 3 e))
3719 (nl (nth 4 e))
3720 (stacked (and nil (nth 5 e))) ; stacked is no longer allowed, forced to nil
3721 (body1 (concat body "*?"))
3722 (markers (mapconcat 'car org-emphasis-alist ""))
3723 (vmarkers (mapconcat
3724 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
3725 org-emphasis-alist "")))
3726 ;; make sure special characters appear at the right position in the class
3727 (if (string-match "\\^" markers)
3728 (setq markers (concat (replace-match "" t t markers) "^")))
3729 (if (string-match "-" markers)
3730 (setq markers (concat (replace-match "" t t markers) "-")))
3731 (if (string-match "\\^" vmarkers)
3732 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
3733 (if (string-match "-" vmarkers)
3734 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
3735 (if (> nl 0)
3736 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
3737 (int-to-string nl) "\\}")))
3738 ;; Make the regexp
3739 (setq org-emph-re
3740 (concat "\\([" pre (if (and nil stacked) markers) "]\\|^\\)"
3741 "\\("
3742 "\\([" markers "]\\)"
3743 "\\("
3744 "[^" border "]\\|"
3745 "[^" border (if (and nil stacked) markers) "]"
3746 body1
3747 "[^" border (if (and nil stacked) markers) "]"
3748 "\\)"
3749 "\\3\\)"
3750 "\\([" post (if (and nil stacked) markers) "]\\|$\\)"))
3751 (setq org-verbatim-re
3752 (concat "\\([" pre "]\\|^\\)"
3753 "\\("
3754 "\\([" vmarkers "]\\)"
3755 "\\("
3756 "[^" border "]\\|"
3757 "[^" border "]"
3758 body1
3759 "[^" border "]"
3760 "\\)"
3761 "\\3\\)"
3762 "\\([" post "]\\|$\\)")))))
3764 (defcustom org-emphasis-regexp-components
3765 '(" \t('\"" "- \t.,:?;'\")" " \t\r\n,\"'" "." 1)
3766 "Components used to build the regular expression for emphasis.
3767 This is a list with 6 entries. Terminology: In an emphasis string
3768 like \" *strong word* \", we call the initial space PREMATCH, the final
3769 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
3770 and \"trong wor\" is the body. The different components in this variable
3771 specify what is allowed/forbidden in each part:
3773 pre Chars allowed as prematch. Beginning of line will be allowed too.
3774 post Chars allowed as postmatch. End of line will be allowed too.
3775 border The chars *forbidden* as border characters.
3776 body-regexp A regexp like \".\" to match a body character. Don't use
3777 non-shy groups here, and don't allow newline here.
3778 newline The maximum number of newlines allowed in an emphasis exp.
3780 Use customize to modify this, or restart Emacs after changing it."
3781 :group 'org-font-lock
3782 :set 'org-set-emph-re
3783 :type '(list
3784 (sexp :tag "Allowed chars in pre ")
3785 (sexp :tag "Allowed chars in post ")
3786 (sexp :tag "Forbidden chars in border ")
3787 (sexp :tag "Regexp for body ")
3788 (integer :tag "number of newlines allowed")
3789 (option (boolean :tag "Stacking (DISABLED) "))))
3791 (defcustom org-emphasis-alist
3792 '(("*" bold "<b>" "</b>")
3793 ("/" italic "<i>" "</i>")
3794 ("_" underline "<u>" "</u>")
3795 ("=" org-code "<code>" "</code>" verbatim)
3796 ("~" org-verbatim "" "" verbatim)
3797 ("+" (:strike-through t) "<del>" "</del>")
3799 "Special syntax for emphasized text.
3800 Text starting and ending with a special character will be emphasized, for
3801 example *bold*, _underlined_ and /italic/. This variable sets the marker
3802 characters, the face to be used by font-lock for highlighting in Org-mode
3803 Emacs buffers, and the HTML tags to be used for this.
3804 Use customize to modify this, or restart Emacs after changing it."
3805 :group 'org-font-lock
3806 :set 'org-set-emph-re
3807 :type '(repeat
3808 (list
3809 (string :tag "Marker character")
3810 (choice
3811 (face :tag "Font-lock-face")
3812 (plist :tag "Face property list"))
3813 (string :tag "HTML start tag")
3814 (string :tag "HTML end tag")
3815 (option (const verbatim)))))
3817 ;;; The faces
3819 (defgroup org-faces nil
3820 "Faces in Org-mode."
3821 :tag "Org Faces"
3822 :group 'org-font-lock)
3824 (defun org-compatible-face (inherits specs)
3825 "Make a compatible face specification.
3826 If INHERITS is an existing face and if the Emacs version supports it,
3827 just inherit the face. If not, use SPECS to define the face.
3828 XEmacs and Emacs 21 do not know about the `min-colors' attribute.
3829 For them we convert a (min-colors 8) entry to a `tty' entry and move it
3830 to the top of the list. The `min-colors' attribute will be removed from
3831 any other entries, and any resulting duplicates will be removed entirely."
3832 (cond
3833 ((and inherits (facep inherits)
3834 (not (featurep 'xemacs)) (> emacs-major-version 22))
3835 ;; In Emacs 23, we use inheritance where possible.
3836 ;; We only do this in Emacs 23, because only there the outline
3837 ;; faces have been changed to the original org-mode-level-faces.
3838 (list (list t :inherit inherits)))
3839 ((or (featurep 'xemacs) (< emacs-major-version 22))
3840 ;; These do not understand the `min-colors' attribute.
3841 (let (r e a)
3842 (while (setq e (pop specs))
3843 (cond
3844 ((memq (car e) '(t default)) (push e r))
3845 ((setq a (member '(min-colors 8) (car e)))
3846 (nconc r (list (cons (cons '(type tty) (delq (car a) (car e)))
3847 (cdr e)))))
3848 ((setq a (assq 'min-colors (car e)))
3849 (setq e (cons (delq a (car e)) (cdr e)))
3850 (or (assoc (car e) r) (push e r)))
3851 (t (or (assoc (car e) r) (push e r)))))
3852 (nreverse r)))
3853 (t specs)))
3854 (put 'org-compatible-face 'lisp-indent-function 1)
3856 (defface org-hide
3857 '((((background light)) (:foreground "white"))
3858 (((background dark)) (:foreground "black")))
3859 "Face used to hide leading stars in headlines.
3860 The forground color of this face should be equal to the background
3861 color of the frame."
3862 :group 'org-faces)
3864 (defface org-level-1 ;; font-lock-function-name-face
3865 (org-compatible-face 'outline-1
3866 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
3867 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
3868 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
3869 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
3870 (((class color) (min-colors 8)) (:foreground "blue" :bold t))
3871 (t (:bold t))))
3872 "Face used for level 1 headlines."
3873 :group 'org-faces)
3875 (defface org-level-2 ;; font-lock-variable-name-face
3876 (org-compatible-face 'outline-2
3877 '((((class color) (min-colors 16) (background light)) (:foreground "DarkGoldenrod"))
3878 (((class color) (min-colors 16) (background dark)) (:foreground "LightGoldenrod"))
3879 (((class color) (min-colors 8) (background light)) (:foreground "yellow"))
3880 (((class color) (min-colors 8) (background dark)) (:foreground "yellow" :bold t))
3881 (t (:bold t))))
3882 "Face used for level 2 headlines."
3883 :group 'org-faces)
3885 (defface org-level-3 ;; font-lock-keyword-face
3886 (org-compatible-face 'outline-3
3887 '((((class color) (min-colors 88) (background light)) (:foreground "Purple"))
3888 (((class color) (min-colors 88) (background dark)) (:foreground "Cyan1"))
3889 (((class color) (min-colors 16) (background light)) (:foreground "Purple"))
3890 (((class color) (min-colors 16) (background dark)) (:foreground "Cyan"))
3891 (((class color) (min-colors 8) (background light)) (:foreground "purple" :bold t))
3892 (((class color) (min-colors 8) (background dark)) (:foreground "cyan" :bold t))
3893 (t (:bold t))))
3894 "Face used for level 3 headlines."
3895 :group 'org-faces)
3897 (defface org-level-4 ;; font-lock-comment-face
3898 (org-compatible-face 'outline-4
3899 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
3900 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
3901 (((class color) (min-colors 16) (background light)) (:foreground "red"))
3902 (((class color) (min-colors 16) (background dark)) (:foreground "red1"))
3903 (((class color) (min-colors 8) (background light)) (:foreground "red" :bold t))
3904 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
3905 (t (:bold t))))
3906 "Face used for level 4 headlines."
3907 :group 'org-faces)
3909 (defface org-level-5 ;; font-lock-type-face
3910 (org-compatible-face 'outline-5
3911 '((((class color) (min-colors 16) (background light)) (:foreground "ForestGreen"))
3912 (((class color) (min-colors 16) (background dark)) (:foreground "PaleGreen"))
3913 (((class color) (min-colors 8)) (:foreground "green"))))
3914 "Face used for level 5 headlines."
3915 :group 'org-faces)
3917 (defface org-level-6 ;; font-lock-constant-face
3918 (org-compatible-face 'outline-6
3919 '((((class color) (min-colors 16) (background light)) (:foreground "CadetBlue"))
3920 (((class color) (min-colors 16) (background dark)) (:foreground "Aquamarine"))
3921 (((class color) (min-colors 8)) (:foreground "magenta"))))
3922 "Face used for level 6 headlines."
3923 :group 'org-faces)
3925 (defface org-level-7 ;; font-lock-builtin-face
3926 (org-compatible-face 'outline-7
3927 '((((class color) (min-colors 16) (background light)) (:foreground "Orchid"))
3928 (((class color) (min-colors 16) (background dark)) (:foreground "LightSteelBlue"))
3929 (((class color) (min-colors 8)) (:foreground "blue"))))
3930 "Face used for level 7 headlines."
3931 :group 'org-faces)
3933 (defface org-level-8 ;; font-lock-string-face
3934 (org-compatible-face 'outline-8
3935 '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
3936 (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
3937 (((class color) (min-colors 8)) (:foreground "green"))))
3938 "Face used for level 8 headlines."
3939 :group 'org-faces)
3941 (defface org-special-keyword ;; font-lock-string-face
3942 (org-compatible-face nil
3943 '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
3944 (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
3945 (t (:italic t))))
3946 "Face used for special keywords."
3947 :group 'org-faces)
3949 (defface org-drawer ;; font-lock-function-name-face
3950 (org-compatible-face nil
3951 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
3952 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
3953 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
3954 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
3955 (((class color) (min-colors 8)) (:foreground "blue" :bold t))
3956 (t (:bold t))))
3957 "Face used for drawers."
3958 :group 'org-faces)
3960 (defface org-property-value nil
3961 "Face used for the value of a property."
3962 :group 'org-faces)
3964 (defface org-column
3965 (org-compatible-face nil
3966 '((((class color) (min-colors 16) (background light))
3967 (:background "grey90"))
3968 (((class color) (min-colors 16) (background dark))
3969 (:background "grey30"))
3970 (((class color) (min-colors 8))
3971 (:background "cyan" :foreground "black"))
3972 (t (:inverse-video t))))
3973 "Face for column display of entry properties."
3974 :group 'org-faces)
3976 (when (fboundp 'set-face-attribute)
3977 ;; Make sure that a fixed-width face is used when we have a column table.
3978 (set-face-attribute 'org-column nil
3979 :height (face-attribute 'default :height)
3980 :family (face-attribute 'default :family)))
3982 (defface org-warning
3983 (org-compatible-face 'font-lock-warning-face
3984 '((((class color) (min-colors 16) (background light)) (:foreground "Red1" :bold t))
3985 (((class color) (min-colors 16) (background dark)) (:foreground "Pink" :bold t))
3986 (((class color) (min-colors 8) (background light)) (:foreground "red" :bold t))
3987 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
3988 (t (:bold t))))
3989 "Face for deadlines and TODO keywords."
3990 :group 'org-faces)
3992 (defface org-archived ; similar to shadow
3993 (org-compatible-face 'shadow
3994 '((((class color grayscale) (min-colors 88) (background light))
3995 (:foreground "grey50"))
3996 (((class color grayscale) (min-colors 88) (background dark))
3997 (:foreground "grey70"))
3998 (((class color) (min-colors 8) (background light))
3999 (:foreground "green"))
4000 (((class color) (min-colors 8) (background dark))
4001 (:foreground "yellow"))))
4002 "Face for headline with the ARCHIVE tag."
4003 :group 'org-faces)
4005 (defface org-link
4006 '((((class color) (background light)) (:foreground "Purple" :underline t))
4007 (((class color) (background dark)) (:foreground "Cyan" :underline t))
4008 (t (:underline t)))
4009 "Face for links."
4010 :group 'org-faces)
4012 (defface org-ellipsis
4013 '((((class color) (background light)) (:foreground "DarkGoldenrod" :underline t))
4014 (((class color) (background dark)) (:foreground "LightGoldenrod" :underline t))
4015 (t (:strike-through t)))
4016 "Face for the ellipsis in folded text."
4017 :group 'org-faces)
4019 (defface org-target
4020 '((((class color) (background light)) (:underline t))
4021 (((class color) (background dark)) (:underline t))
4022 (t (:underline t)))
4023 "Face for links."
4024 :group 'org-faces)
4026 (defface org-date
4027 '((((class color) (background light)) (:foreground "Purple" :underline t))
4028 (((class color) (background dark)) (:foreground "Cyan" :underline t))
4029 (t (:underline t)))
4030 "Face for links."
4031 :group 'org-faces)
4033 (defface org-sexp-date
4034 '((((class color) (background light)) (:foreground "Purple"))
4035 (((class color) (background dark)) (:foreground "Cyan"))
4036 (t (:underline t)))
4037 "Face for links."
4038 :group 'org-faces)
4040 (defface org-tag
4041 '((t (:bold t)))
4042 "Face for tags."
4043 :group 'org-faces)
4045 (defface org-todo ; font-lock-warning-face
4046 (org-compatible-face nil
4047 '((((class color) (min-colors 16) (background light)) (:foreground "Red1" :bold t))
4048 (((class color) (min-colors 16) (background dark)) (:foreground "Pink" :bold t))
4049 (((class color) (min-colors 8) (background light)) (:foreground "red" :bold t))
4050 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
4051 (t (:inverse-video t :bold t))))
4052 "Face for TODO keywords."
4053 :group 'org-faces)
4055 (defface org-done ;; font-lock-type-face
4056 (org-compatible-face nil
4057 '((((class color) (min-colors 16) (background light)) (:foreground "ForestGreen" :bold t))
4058 (((class color) (min-colors 16) (background dark)) (:foreground "PaleGreen" :bold t))
4059 (((class color) (min-colors 8)) (:foreground "green"))
4060 (t (:bold t))))
4061 "Face used for todo keywords that indicate DONE items."
4062 :group 'org-faces)
4064 (defface org-headline-done ;; font-lock-string-face
4065 (org-compatible-face nil
4066 '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
4067 (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
4068 (((class color) (min-colors 8) (background light)) (:bold nil))))
4069 "Face used to indicate that a headline is DONE.
4070 This face is only used if `org-fontify-done-headline' is set. If applies
4071 to the part of the headline after the DONE keyword."
4072 :group 'org-faces)
4074 (defcustom org-todo-keyword-faces nil
4075 "Faces for specific TODO keywords.
4076 This is a list of cons cells, with TODO keywords in the car
4077 and faces in the cdr. The face can be a symbol, or a property
4078 list of attributes, like (:foreground \"blue\" :weight bold :underline t)."
4079 :group 'org-faces
4080 :group 'org-todo
4081 :type '(repeat
4082 (cons
4083 (string :tag "keyword")
4084 (sexp :tag "face"))))
4086 (defface org-table ;; font-lock-function-name-face
4087 (org-compatible-face nil
4088 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
4089 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
4090 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
4091 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
4092 (((class color) (min-colors 8) (background light)) (:foreground "blue"))
4093 (((class color) (min-colors 8) (background dark)))))
4094 "Face used for tables."
4095 :group 'org-faces)
4097 (defface org-formula
4098 (org-compatible-face nil
4099 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
4100 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
4101 (((class color) (min-colors 8) (background light)) (:foreground "red"))
4102 (((class color) (min-colors 8) (background dark)) (:foreground "red"))
4103 (t (:bold t :italic t))))
4104 "Face for formulas."
4105 :group 'org-faces)
4107 (defface org-code
4108 (org-compatible-face nil
4109 '((((class color grayscale) (min-colors 88) (background light))
4110 (:foreground "grey50"))
4111 (((class color grayscale) (min-colors 88) (background dark))
4112 (:foreground "grey70"))
4113 (((class color) (min-colors 8) (background light))
4114 (:foreground "green"))
4115 (((class color) (min-colors 8) (background dark))
4116 (:foreground "yellow"))))
4117 "Face for fixed-with text like code snippets."
4118 :group 'org-faces
4119 :version "22.1")
4121 (defface org-verbatim
4122 (org-compatible-face nil
4123 '((((class color grayscale) (min-colors 88) (background light))
4124 (:foreground "grey50" :underline t))
4125 (((class color grayscale) (min-colors 88) (background dark))
4126 (:foreground "grey70" :underline t))
4127 (((class color) (min-colors 8) (background light))
4128 (:foreground "green" :underline t))
4129 (((class color) (min-colors 8) (background dark))
4130 (:foreground "yellow" :underline t))))
4131 "Face for fixed-with text like code snippets."
4132 :group 'org-faces
4133 :version "22.1")
4135 (defface org-agenda-structure ;; font-lock-function-name-face
4136 (org-compatible-face nil
4137 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
4138 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
4139 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
4140 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
4141 (((class color) (min-colors 8)) (:foreground "blue" :bold t))
4142 (t (:bold t))))
4143 "Face used in agenda for captions and dates."
4144 :group 'org-faces)
4146 (defface org-scheduled-today
4147 (org-compatible-face nil
4148 '((((class color) (min-colors 88) (background light)) (:foreground "DarkGreen"))
4149 (((class color) (min-colors 88) (background dark)) (:foreground "PaleGreen"))
4150 (((class color) (min-colors 8)) (:foreground "green"))
4151 (t (:bold t :italic t))))
4152 "Face for items scheduled for a certain day."
4153 :group 'org-faces)
4155 (defface org-scheduled-previously
4156 (org-compatible-face nil
4157 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
4158 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
4159 (((class color) (min-colors 8) (background light)) (:foreground "red"))
4160 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
4161 (t (:bold t))))
4162 "Face for items scheduled previously, and not yet done."
4163 :group 'org-faces)
4165 (defface org-upcoming-deadline
4166 (org-compatible-face nil
4167 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
4168 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
4169 (((class color) (min-colors 8) (background light)) (:foreground "red"))
4170 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
4171 (t (:bold t))))
4172 "Face for items scheduled previously, and not yet done."
4173 :group 'org-faces)
4175 (defcustom org-agenda-deadline-faces
4176 '((1.0 . org-warning)
4177 (0.5 . org-upcoming-deadline)
4178 (0.0 . default))
4179 "Faces for showing deadlines in the agenda.
4180 This is a list of cons cells. The cdr of each cell is a face to be used,
4181 and it can also just be like '(:foreground \"yellow\").
4182 Each car is a fraction of the head-warning time that must have passed for
4183 this the face in the cdr to be used for display. The numbers must be
4184 given in descending order. The head-warning time is normally taken
4185 from `org-deadline-warning-days', but can also be specified in the deadline
4186 timestamp itself, like this:
4188 DEADLINE: <2007-08-13 Mon -8d>
4190 You may use d for days, w for weeks, m for months and y for years. Months
4191 and years will only be treated in an approximate fashion (30.4 days for a
4192 month and 365.24 days for a year)."
4193 :group 'org-faces
4194 :group 'org-agenda-daily/weekly
4195 :type '(repeat
4196 (cons
4197 (number :tag "Fraction of head-warning time passed")
4198 (sexp :tag "Face"))))
4200 ;; FIXME: this is not a good face yet.
4201 (defface org-agenda-restriction-lock
4202 (org-compatible-face nil
4203 '((((class color) (min-colors 88) (background light)) (:background "yellow1"))
4204 (((class color) (min-colors 88) (background dark)) (:background "skyblue4"))
4205 (((class color) (min-colors 16) (background light)) (:background "yellow1"))
4206 (((class color) (min-colors 16) (background dark)) (:background "skyblue4"))
4207 (((class color) (min-colors 8)) (:background "cyan" :foreground "black"))
4208 (t (:inverse-video t))))
4209 "Face for showing the agenda restriction lock."
4210 :group 'org-faces)
4212 (defface org-time-grid ;; font-lock-variable-name-face
4213 (org-compatible-face nil
4214 '((((class color) (min-colors 16) (background light)) (:foreground "DarkGoldenrod"))
4215 (((class color) (min-colors 16) (background dark)) (:foreground "LightGoldenrod"))
4216 (((class color) (min-colors 8)) (:foreground "yellow" :weight light))))
4217 "Face used for time grids."
4218 :group 'org-faces)
4220 (defconst org-level-faces
4221 '(org-level-1 org-level-2 org-level-3 org-level-4
4222 org-level-5 org-level-6 org-level-7 org-level-8
4225 (defcustom org-n-level-faces (length org-level-faces)
4226 "The number of different faces to be used for headlines.
4227 Org-mode defines 8 different headline faces, so this can be at most 8.
4228 If it is less than 8, the level-1 face gets re-used for level N+1 etc."
4229 :type 'number
4230 :group 'org-faces)
4232 ;;; Functions and variables from ther packages
4233 ;; Declared here to avoid compiler warnings
4235 (eval-and-compile
4236 (unless (fboundp 'declare-function)
4237 (defmacro declare-function (fn file &optional arglist fileonly))))
4239 ;; XEmacs only
4240 (defvar outline-mode-menu-heading)
4241 (defvar outline-mode-menu-show)
4242 (defvar outline-mode-menu-hide)
4243 (defvar zmacs-regions) ; XEmacs regions
4245 ;; Emacs only
4246 (defvar mark-active)
4248 ;; Various packages
4249 ;; FIXME: get the argument lists for the UNKNOWN stuff
4250 (declare-function add-to-diary-list "diary-lib"
4251 (date string specifier &optional marker globcolor literal))
4252 (declare-function table--at-cell-p "table" (position &optional object at-column))
4253 (declare-function Info-find-node "info" (filename nodename &optional no-going-back))
4254 (declare-function Info-goto-node "info" (nodename &optional fork))
4255 (declare-function bbdb "ext:bbdb-com" (string elidep))
4256 (declare-function bbdb-company "ext:bbdb-com" (string elidep))
4257 (declare-function bbdb-current-record "ext:bbdb-com" (&optional planning-on-modifying))
4258 (declare-function bbdb-name "ext:bbdb-com" (string elidep))
4259 (declare-function bbdb-record-getprop "ext:bbdb" (record property))
4260 (declare-function bbdb-record-name "ext:bbdb" (record))
4261 (declare-function bibtex-beginning-of-entry "bibtex" ())
4262 (declare-function bibtex-generate-autokey "bibtex" ())
4263 (declare-function bibtex-parse-entry "bibtex" (&optional content))
4264 (declare-function bibtex-url "bibtex" (&optional pos no-browse))
4265 (defvar calc-embedded-close-formula)
4266 (defvar calc-embedded-open-formula)
4267 (declare-function calendar-astro-date-string "cal-julian" (&optional date))
4268 (declare-function calendar-bahai-date-string "cal-bahai" (&optional date))
4269 (declare-function calendar-check-holidays "holidays" (date))
4270 (declare-function calendar-chinese-date-string "cal-china" (&optional date))
4271 (declare-function calendar-coptic-date-string "cal-coptic" (&optional date))
4272 (declare-function calendar-ethiopic-date-string "cal-coptic" (&optional date))
4273 (declare-function calendar-forward-day "cal-move" (arg))
4274 (declare-function calendar-french-date-string "cal-french" (&optional date))
4275 (declare-function calendar-goto-date "cal-move" (date))
4276 (declare-function calendar-goto-today "cal-move" ())
4277 (declare-function calendar-hebrew-date-string "cal-hebrew" (&optional date))
4278 (declare-function calendar-islamic-date-string "cal-islam" (&optional date))
4279 (declare-function calendar-iso-date-string "cal-iso" (&optional date))
4280 (declare-function calendar-julian-date-string "cal-julian" (&optional date))
4281 (declare-function calendar-mayan-date-string "cal-mayan" (&optional date))
4282 (declare-function calendar-persian-date-string "cal-persia" (&optional date))
4283 (defvar calendar-mode-map)
4284 (defvar original-date) ; dynamically scoped in calendar.el does scope this
4285 (declare-function cdlatex-tab "ext:cdlatex" ())
4286 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
4287 (declare-function elmo-folder-exists-p "ext:elmo" (folder) t)
4288 (declare-function elmo-message-entity-field "ext:elmo-msgdb" (entity field &optional type))
4289 (declare-function elmo-message-field "ext:elmo" (folder number field &optional type) t)
4290 (declare-function elmo-msgdb-overview-get-entity "ext:elmo" (&rest unknown) t)
4291 (defvar font-lock-unfontify-region-function)
4292 (declare-function gnus-article-show-summary "gnus-art" ())
4293 (declare-function gnus-summary-last-subject "gnus-sum" ())
4294 (defvar gnus-other-frame-object)
4295 (defvar gnus-group-name)
4296 (defvar gnus-article-current)
4297 (defvar Info-current-file)
4298 (defvar Info-current-node)
4299 (declare-function mh-display-msg "mh-show" (msg-num folder-name))
4300 (declare-function mh-find-path "mh-utils" ())
4301 (declare-function mh-get-header-field "mh-utils" (field))
4302 (declare-function mh-get-msg-num "mh-utils" (error-if-no-message))
4303 (declare-function mh-header-display "mh-show" ())
4304 (declare-function mh-index-previous-folder "mh-search" ())
4305 (declare-function mh-normalize-folder-name "mh-utils" (folder &optional empty-string-okay dont-remove-trailing-slash return-nil-if-folder-empty))
4306 (declare-function mh-search "mh-search" (folder search-regexp &optional redo-search-flag window-config))
4307 (declare-function mh-search-choose "mh-search" (&optional searcher))
4308 (declare-function mh-show "mh-show" (&optional message redisplay-flag))
4309 (declare-function mh-show-buffer-message-number "mh-comp" (&optional buffer))
4310 (declare-function mh-show-header-display "mh-show" t t)
4311 (declare-function mh-show-msg "mh-show" (msg))
4312 (declare-function mh-show-show "mh-show" t t)
4313 (declare-function mh-visit-folder "mh-folder" (folder &optional range index-data))
4314 (defvar mh-progs)
4315 (defvar mh-current-folder)
4316 (defvar mh-show-folder-buffer)
4317 (defvar mh-index-folder)
4318 (defvar mh-searcher)
4319 (declare-function org-export-latex-cleaned-string "org-export-latex" ())
4320 (declare-function parse-time-string "parse-time" (string))
4321 (declare-function remember "remember" (&optional initial))
4322 (declare-function remember-buffer-desc "remember" ())
4323 (declare-function remember-finalize "remember" ())
4324 (defvar remember-save-after-remembering)
4325 (defvar remember-data-file)
4326 (defvar remember-register)
4327 (defvar remember-buffer)
4328 (defvar remember-handler-functions)
4329 (defvar remember-annotation-functions)
4330 (declare-function rmail-narrow-to-non-pruned-header "rmail" ())
4331 (declare-function rmail-show-message "rmail" (&optional n no-summary))
4332 (declare-function rmail-what-message "rmail" ())
4333 (defvar rmail-current-message)
4334 (defvar texmathp-why)
4335 (declare-function vm-beginning-of-message "ext:vm-page" ())
4336 (declare-function vm-follow-summary-cursor "ext:vm-motion" ())
4337 (declare-function vm-get-header-contents "ext:vm-summary" (message header-name-regexp &optional clump-sep))
4338 (declare-function vm-isearch-narrow "ext:vm-search" ())
4339 (declare-function vm-isearch-update "ext:vm-search" ())
4340 (declare-function vm-select-folder-buffer "ext:vm-macro" ())
4341 (declare-function vm-su-message-id "ext:vm-summary" (m))
4342 (declare-function vm-su-subject "ext:vm-summary" (m))
4343 (declare-function vm-summarize "ext:vm-summary" (&optional display raise))
4344 (defvar vm-message-pointer)
4345 (defvar vm-folder-directory)
4346 (defvar w3m-current-url)
4347 (defvar w3m-current-title)
4348 ;; backward compatibility to old version of wl
4349 (declare-function wl-summary-buffer-msgdb "ext:wl-folder" (&rest unknown) t)
4350 (declare-function wl-folder-get-elmo-folder "ext:wl-folder" (entity &optional no-cache))
4351 (declare-function wl-summary-goto-folder-subr "ext:wl-summary" (&optional name scan-type other-window sticky interactive scoring force-exit))
4352 (declare-function wl-summary-jump-to-msg-by-message-id "ext:wl-summary" (&optional id))
4353 (declare-function wl-summary-line-from "ext:wl-summary" ())
4354 (declare-function wl-summary-line-subject "ext:wl-summary" ())
4355 (declare-function wl-summary-message-number "ext:wl-summary" ())
4356 (declare-function wl-summary-redisplay "ext:wl-summary" (&optional arg))
4357 (defvar wl-summary-buffer-elmo-folder)
4358 (defvar wl-summary-buffer-folder-name)
4359 (declare-function speedbar-line-directory "speedbar" (&optional depth))
4361 (defvar org-latex-regexps)
4362 (defvar constants-unit-system)
4364 ;;; Variables for pre-computed regular expressions, all buffer local
4366 (defvar org-drawer-regexp nil
4367 "Matches first line of a hidden block.")
4368 (make-variable-buffer-local 'org-drawer-regexp)
4369 (defvar org-todo-regexp nil
4370 "Matches any of the TODO state keywords.")
4371 (make-variable-buffer-local 'org-todo-regexp)
4372 (defvar org-not-done-regexp nil
4373 "Matches any of the TODO state keywords except the last one.")
4374 (make-variable-buffer-local 'org-not-done-regexp)
4375 (defvar org-todo-line-regexp nil
4376 "Matches a headline and puts TODO state into group 2 if present.")
4377 (make-variable-buffer-local 'org-todo-line-regexp)
4378 (defvar org-complex-heading-regexp nil
4379 "Matches a headline and puts everything into groups:
4380 group 1: the stars
4381 group 2: The todo keyword, maybe
4382 group 3: Priority cookie
4383 group 4: True headline
4384 group 5: Tags")
4385 (make-variable-buffer-local 'org-complex-heading-regexp)
4386 (defvar org-todo-line-tags-regexp nil
4387 "Matches a headline and puts TODO state into group 2 if present.
4388 Also put tags into group 4 if tags are present.")
4389 (make-variable-buffer-local 'org-todo-line-tags-regexp)
4390 (defvar org-nl-done-regexp nil
4391 "Matches newline followed by a headline with the DONE keyword.")
4392 (make-variable-buffer-local 'org-nl-done-regexp)
4393 (defvar org-looking-at-done-regexp nil
4394 "Matches the DONE keyword a point.")
4395 (make-variable-buffer-local 'org-looking-at-done-regexp)
4396 (defvar org-ds-keyword-length 12
4397 "Maximum length of the Deadline and SCHEDULED keywords.")
4398 (make-variable-buffer-local 'org-ds-keyword-length)
4399 (defvar org-deadline-regexp nil
4400 "Matches the DEADLINE keyword.")
4401 (make-variable-buffer-local 'org-deadline-regexp)
4402 (defvar org-deadline-time-regexp nil
4403 "Matches the DEADLINE keyword together with a time stamp.")
4404 (make-variable-buffer-local 'org-deadline-time-regexp)
4405 (defvar org-deadline-line-regexp nil
4406 "Matches the DEADLINE keyword and the rest of the line.")
4407 (make-variable-buffer-local 'org-deadline-line-regexp)
4408 (defvar org-scheduled-regexp nil
4409 "Matches the SCHEDULED keyword.")
4410 (make-variable-buffer-local 'org-scheduled-regexp)
4411 (defvar org-scheduled-time-regexp nil
4412 "Matches the SCHEDULED keyword together with a time stamp.")
4413 (make-variable-buffer-local 'org-scheduled-time-regexp)
4414 (defvar org-closed-time-regexp nil
4415 "Matches the CLOSED keyword together with a time stamp.")
4416 (make-variable-buffer-local 'org-closed-time-regexp)
4418 (defvar org-keyword-time-regexp nil
4419 "Matches any of the 4 keywords, together with the time stamp.")
4420 (make-variable-buffer-local 'org-keyword-time-regexp)
4421 (defvar org-keyword-time-not-clock-regexp nil
4422 "Matches any of the 3 keywords, together with the time stamp.")
4423 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
4424 (defvar org-maybe-keyword-time-regexp nil
4425 "Matches a timestamp, possibly preceeded by a keyword.")
4426 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
4427 (defvar org-planning-or-clock-line-re nil
4428 "Matches a line with planning or clock info.")
4429 (make-variable-buffer-local 'org-planning-or-clock-line-re)
4431 (defconst org-rm-props '(invisible t face t keymap t intangible t mouse-face t
4432 rear-nonsticky t mouse-map t fontified t)
4433 "Properties to remove when a string without properties is wanted.")
4435 (defsubst org-match-string-no-properties (num &optional string)
4436 (if (featurep 'xemacs)
4437 (let ((s (match-string num string)))
4438 (remove-text-properties 0 (length s) org-rm-props s)
4440 (match-string-no-properties num string)))
4442 (defsubst org-no-properties (s)
4443 (if (fboundp 'set-text-properties)
4444 (set-text-properties 0 (length s) nil s)
4445 (remove-text-properties 0 (length s) org-rm-props s))
4448 (defsubst org-get-alist-option (option key)
4449 (cond ((eq key t) t)
4450 ((eq option t) t)
4451 ((assoc key option) (cdr (assoc key option)))
4452 (t (cdr (assq 'default option)))))
4454 (defsubst org-inhibit-invisibility ()
4455 "Modified `buffer-invisibility-spec' for Emacs 21.
4456 Some ops with invisible text do not work correctly on Emacs 21. For these
4457 we turn off invisibility temporarily. Use this in a `let' form."
4458 (if (< emacs-major-version 22) nil buffer-invisibility-spec))
4460 (defsubst org-set-local (var value)
4461 "Make VAR local in current buffer and set it to VALUE."
4462 (set (make-variable-buffer-local var) value))
4464 (defsubst org-mode-p ()
4465 "Check if the current buffer is in Org-mode."
4466 (eq major-mode 'org-mode))
4468 (defsubst org-last (list)
4469 "Return the last element of LIST."
4470 (car (last list)))
4472 (defun org-let (list &rest body)
4473 (eval (cons 'let (cons list body))))
4474 (put 'org-let 'lisp-indent-function 1)
4476 (defun org-let2 (list1 list2 &rest body)
4477 (eval (cons 'let (cons list1 (list (cons 'let (cons list2 body)))))))
4478 (put 'org-let2 'lisp-indent-function 2)
4479 (defconst org-startup-options
4480 '(("fold" org-startup-folded t)
4481 ("overview" org-startup-folded t)
4482 ("nofold" org-startup-folded nil)
4483 ("showall" org-startup-folded nil)
4484 ("content" org-startup-folded content)
4485 ("hidestars" org-hide-leading-stars t)
4486 ("showstars" org-hide-leading-stars nil)
4487 ("odd" org-odd-levels-only t)
4488 ("oddeven" org-odd-levels-only nil)
4489 ("align" org-startup-align-all-tables t)
4490 ("noalign" org-startup-align-all-tables nil)
4491 ("customtime" org-display-custom-times t)
4492 ("logdone" org-log-done time)
4493 ("lognotedone" org-log-done note)
4494 ("nologdone" org-log-done nil)
4495 ("lognoteclock-out" org-log-note-clock-out t)
4496 ("nolognoteclock-out" org-log-note-clock-out nil)
4497 ("logrepeat" org-log-repeat state)
4498 ("lognoterepeat" org-log-repeat note)
4499 ("nologrepeat" org-log-repeat nil)
4500 ("constcgs" constants-unit-system cgs)
4501 ("constSI" constants-unit-system SI))
4502 "Variable associated with STARTUP options for org-mode.
4503 Each element is a list of three items: The startup options as written
4504 in the #+STARTUP line, the corresponding variable, and the value to
4505 set this variable to if the option is found. An optional forth element PUSH
4506 means to push this value onto the list in the variable.")
4508 (defun org-set-regexps-and-options ()
4509 "Precompute regular expressions for current buffer."
4510 (when (org-mode-p)
4511 (org-set-local 'org-todo-kwd-alist nil)
4512 (org-set-local 'org-todo-key-alist nil)
4513 (org-set-local 'org-todo-key-trigger nil)
4514 (org-set-local 'org-todo-keywords-1 nil)
4515 (org-set-local 'org-done-keywords nil)
4516 (org-set-local 'org-todo-heads nil)
4517 (org-set-local 'org-todo-sets nil)
4518 (org-set-local 'org-todo-log-states nil)
4519 (let ((re (org-make-options-regexp
4520 '("CATEGORY" "SEQ_TODO" "TYP_TODO" "TODO" "COLUMNS"
4521 "STARTUP" "ARCHIVE" "TAGS" "LINK" "PRIORITIES"
4522 "CONSTANTS" "PROPERTY" "DRAWERS")))
4523 (splitre "[ \t]+")
4524 kwds kws0 kwsa key log value cat arch tags const links hw dws
4525 tail sep kws1 prio props drawers)
4526 (save-excursion
4527 (save-restriction
4528 (widen)
4529 (goto-char (point-min))
4530 (while (re-search-forward re nil t)
4531 (setq key (match-string 1) value (org-match-string-no-properties 2))
4532 (cond
4533 ((equal key "CATEGORY")
4534 (if (string-match "[ \t]+$" value)
4535 (setq value (replace-match "" t t value)))
4536 (setq cat value))
4537 ((member key '("SEQ_TODO" "TODO"))
4538 (push (cons 'sequence (org-split-string value splitre)) kwds))
4539 ((equal key "TYP_TODO")
4540 (push (cons 'type (org-split-string value splitre)) kwds))
4541 ((equal key "TAGS")
4542 (setq tags (append tags (org-split-string value splitre))))
4543 ((equal key "COLUMNS")
4544 (org-set-local 'org-columns-default-format value))
4545 ((equal key "LINK")
4546 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
4547 (push (cons (match-string 1 value)
4548 (org-trim (match-string 2 value)))
4549 links)))
4550 ((equal key "PRIORITIES")
4551 (setq prio (org-split-string value " +")))
4552 ((equal key "PROPERTY")
4553 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4554 (push (cons (match-string 1 value) (match-string 2 value))
4555 props)))
4556 ((equal key "DRAWERS")
4557 (setq drawers (org-split-string value splitre)))
4558 ((equal key "CONSTANTS")
4559 (setq const (append const (org-split-string value splitre))))
4560 ((equal key "STARTUP")
4561 (let ((opts (org-split-string value splitre))
4562 l var val)
4563 (while (setq l (pop opts))
4564 (when (setq l (assoc l org-startup-options))
4565 (setq var (nth 1 l) val (nth 2 l))
4566 (if (not (nth 3 l))
4567 (set (make-local-variable var) val)
4568 (if (not (listp (symbol-value var)))
4569 (set (make-local-variable var) nil))
4570 (set (make-local-variable var) (symbol-value var))
4571 (add-to-list var val))))))
4572 ((equal key "ARCHIVE")
4573 (string-match " *$" value)
4574 (setq arch (replace-match "" t t value))
4575 (remove-text-properties 0 (length arch)
4576 '(face t fontified t) arch)))
4578 (when cat
4579 (org-set-local 'org-category (intern cat))
4580 (push (cons "CATEGORY" cat) props))
4581 (when prio
4582 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
4583 (setq prio (mapcar 'string-to-char prio))
4584 (org-set-local 'org-highest-priority (nth 0 prio))
4585 (org-set-local 'org-lowest-priority (nth 1 prio))
4586 (org-set-local 'org-default-priority (nth 2 prio)))
4587 (and props (org-set-local 'org-local-properties (nreverse props)))
4588 (and drawers (org-set-local 'org-drawers drawers))
4589 (and arch (org-set-local 'org-archive-location arch))
4590 (and links (setq org-link-abbrev-alist-local (nreverse links)))
4591 ;; Process the TODO keywords
4592 (unless kwds
4593 ;; Use the global values as if they had been given locally.
4594 (setq kwds (default-value 'org-todo-keywords))
4595 (if (stringp (car kwds))
4596 (setq kwds (list (cons org-todo-interpretation
4597 (default-value 'org-todo-keywords)))))
4598 (setq kwds (reverse kwds)))
4599 (setq kwds (nreverse kwds))
4600 (let (inter kws kw)
4601 (while (setq kws (pop kwds))
4602 (setq inter (pop kws) sep (member "|" kws)
4603 kws0 (delete "|" (copy-sequence kws))
4604 kwsa nil
4605 kws1 (mapcar
4606 (lambda (x)
4607 ;; 1 2
4608 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
4609 (progn
4610 (setq kw (match-string 1 x)
4611 key (and (match-end 2) (match-string 2 x))
4612 log (org-extract-log-state-settings x))
4613 (push (cons kw (and key (string-to-char key))) kwsa)
4614 (and log (push log org-todo-log-states))
4616 (error "Invalid TODO keyword %s" x)))
4617 kws0)
4618 kwsa (if kwsa (append '((:startgroup))
4619 (nreverse kwsa)
4620 '((:endgroup))))
4621 hw (car kws1)
4622 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
4623 tail (list inter hw (car dws) (org-last dws)))
4624 (add-to-list 'org-todo-heads hw 'append)
4625 (push kws1 org-todo-sets)
4626 (setq org-done-keywords (append org-done-keywords dws nil))
4627 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
4628 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
4629 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
4630 (setq org-todo-sets (nreverse org-todo-sets)
4631 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
4632 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
4633 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
4634 ;; Process the constants
4635 (when const
4636 (let (e cst)
4637 (while (setq e (pop const))
4638 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
4639 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
4640 (setq org-table-formula-constants-local cst)))
4642 ;; Process the tags.
4643 (when tags
4644 (let (e tgs)
4645 (while (setq e (pop tags))
4646 (cond
4647 ((equal e "{") (push '(:startgroup) tgs))
4648 ((equal e "}") (push '(:endgroup) tgs))
4649 ((string-match (org-re "^\\([[:alnum:]_@]+\\)(\\(.\\))$") e)
4650 (push (cons (match-string 1 e)
4651 (string-to-char (match-string 2 e)))
4652 tgs))
4653 (t (push (list e) tgs))))
4654 (org-set-local 'org-tag-alist nil)
4655 (while (setq e (pop tgs))
4656 (or (and (stringp (car e))
4657 (assoc (car e) org-tag-alist))
4658 (push e org-tag-alist))))))
4660 ;; Compute the regular expressions and other local variables
4661 (if (not org-done-keywords)
4662 (setq org-done-keywords (list (org-last org-todo-keywords-1))))
4663 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
4664 (length org-scheduled-string)))
4665 org-drawer-regexp
4666 (concat "^[ \t]*:\\("
4667 (mapconcat 'regexp-quote org-drawers "\\|")
4668 "\\):[ \t]*$")
4669 org-not-done-keywords
4670 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
4671 org-todo-regexp
4672 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords-1
4673 "\\|") "\\)\\>")
4674 org-not-done-regexp
4675 (concat "\\<\\("
4676 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
4677 "\\)\\>")
4678 org-todo-line-regexp
4679 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
4680 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4681 "\\)\\>\\)?[ \t]*\\(.*\\)")
4682 org-complex-heading-regexp
4683 (concat "^\\(\\*+\\)\\(?:[ \t]+\\("
4684 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4685 "\\)\\>\\)?\\(?:[ \t]*\\(\\[#.\\]\\)\\)?[ \t]*\\(.*?\\)"
4686 "\\(?:[ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
4687 org-nl-done-regexp
4688 (concat "\n\\*+[ \t]+"
4689 "\\(?:" (mapconcat 'regexp-quote org-done-keywords "\\|")
4690 "\\)" "\\>")
4691 org-todo-line-tags-regexp
4692 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
4693 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4694 (org-re
4695 "\\)\\>\\)? *\\(.*?\\([ \t]:[[:alnum:]:_@]+:[ \t]*\\)?$\\)"))
4696 org-looking-at-done-regexp
4697 (concat "^" "\\(?:"
4698 (mapconcat 'regexp-quote org-done-keywords "\\|") "\\)"
4699 "\\>")
4700 org-deadline-regexp (concat "\\<" org-deadline-string)
4701 org-deadline-time-regexp
4702 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
4703 org-deadline-line-regexp
4704 (concat "\\<\\(" org-deadline-string "\\).*")
4705 org-scheduled-regexp
4706 (concat "\\<" org-scheduled-string)
4707 org-scheduled-time-regexp
4708 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
4709 org-closed-time-regexp
4710 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
4711 org-keyword-time-regexp
4712 (concat "\\<\\(" org-scheduled-string
4713 "\\|" org-deadline-string
4714 "\\|" org-closed-string
4715 "\\|" org-clock-string "\\)"
4716 " *[[<]\\([^]>]+\\)[]>]")
4717 org-keyword-time-not-clock-regexp
4718 (concat "\\<\\(" org-scheduled-string
4719 "\\|" org-deadline-string
4720 "\\|" org-closed-string
4721 "\\)"
4722 " *[[<]\\([^]>]+\\)[]>]")
4723 org-maybe-keyword-time-regexp
4724 (concat "\\(\\<\\(" org-scheduled-string
4725 "\\|" org-deadline-string
4726 "\\|" org-closed-string
4727 "\\|" org-clock-string "\\)\\)?"
4728 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
4729 org-planning-or-clock-line-re
4730 (concat "\\(?:^[ \t]*\\(" org-scheduled-string
4731 "\\|" org-deadline-string
4732 "\\|" org-closed-string "\\|" org-clock-string
4733 "\\)\\>\\)")
4735 (org-compute-latex-and-specials-regexp)
4736 (org-set-font-lock-defaults)))
4738 (defun org-extract-log-state-settings (x)
4739 "Extract the log state setting from a TODO keyword string.
4740 This will extract info from a string like \"WAIT(w@/!)\"."
4741 (let (kw key log1 log2)
4742 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
4743 (setq kw (match-string 1 x)
4744 key (and (match-end 2) (match-string 2 x))
4745 log1 (and (match-end 3) (match-string 3 x))
4746 log2 (and (match-end 4) (match-string 4 x)))
4747 (and (or log1 log2)
4748 (list kw
4749 (and log1 (if (equal log1 "!") 'time 'note))
4750 (and log2 (if (equal log2 "!") 'time 'note)))))))
4752 (defun org-remove-keyword-keys (list)
4753 "Remove a pair of parenthesis at the end of each string in LIST."
4754 (mapcar (lambda (x)
4755 (if (string-match "(.*)$" x)
4756 (substring x 0 (match-beginning 0))
4758 list))
4760 ;; FIXME: this could be done much better, using second characters etc.
4761 (defun org-assign-fast-keys (alist)
4762 "Assign fast keys to a keyword-key alist.
4763 Respect keys that are already there."
4764 (let (new e k c c1 c2 (char ?a))
4765 (while (setq e (pop alist))
4766 (cond
4767 ((equal e '(:startgroup)) (push e new))
4768 ((equal e '(:endgroup)) (push e new))
4770 (setq k (car e) c2 nil)
4771 (if (cdr e)
4772 (setq c (cdr e))
4773 ;; automatically assign a character.
4774 (setq c1 (string-to-char
4775 (downcase (substring
4776 k (if (= (string-to-char k) ?@) 1 0)))))
4777 (if (or (rassoc c1 new) (rassoc c1 alist))
4778 (while (or (rassoc char new) (rassoc char alist))
4779 (setq char (1+ char)))
4780 (setq c2 c1))
4781 (setq c (or c2 char)))
4782 (push (cons k c) new))))
4783 (nreverse new)))
4785 ;;; Some variables ujsed in various places
4787 (defvar org-window-configuration nil
4788 "Used in various places to store a window configuration.")
4789 (defvar org-finish-function nil
4790 "Function to be called when `C-c C-c' is used.
4791 This is for getting out of special buffers like remember.")
4794 ;; FIXME: Occasionally check by commenting these, to make sure
4795 ;; no other functions uses these, forgetting to let-bind them.
4796 (defvar entry)
4797 (defvar state)
4798 (defvar last-state)
4799 (defvar date)
4800 (defvar description)
4802 ;; Defined somewhere in this file, but used before definition.
4803 (defvar orgtbl-mode-menu) ; defined when orgtbl mode get initialized
4804 (defvar org-agenda-buffer-name)
4805 (defvar org-agenda-undo-list)
4806 (defvar org-agenda-pending-undo-list)
4807 (defvar org-agenda-overriding-header)
4808 (defvar orgtbl-mode)
4809 (defvar org-html-entities)
4810 (defvar org-struct-menu)
4811 (defvar org-org-menu)
4812 (defvar org-tbl-menu)
4813 (defvar org-agenda-keymap)
4815 ;;;; Emacs/XEmacs compatibility
4817 ;; Overlay compatibility functions
4818 (defun org-make-overlay (beg end &optional buffer)
4819 (if (featurep 'xemacs)
4820 (make-extent beg end buffer)
4821 (make-overlay beg end buffer)))
4822 (defun org-delete-overlay (ovl)
4823 (if (featurep 'xemacs) (delete-extent ovl) (delete-overlay ovl)))
4824 (defun org-detach-overlay (ovl)
4825 (if (featurep 'xemacs) (detach-extent ovl) (delete-overlay ovl)))
4826 (defun org-move-overlay (ovl beg end &optional buffer)
4827 (if (featurep 'xemacs)
4828 (set-extent-endpoints ovl beg end (or buffer (current-buffer)))
4829 (move-overlay ovl beg end buffer)))
4830 (defun org-overlay-put (ovl prop value)
4831 (if (featurep 'xemacs)
4832 (set-extent-property ovl prop value)
4833 (overlay-put ovl prop value)))
4834 (defun org-overlay-display (ovl text &optional face evap)
4835 "Make overlay OVL display TEXT with face FACE."
4836 (if (featurep 'xemacs)
4837 (let ((gl (make-glyph text)))
4838 (and face (set-glyph-face gl face))
4839 (set-extent-property ovl 'invisible t)
4840 (set-extent-property ovl 'end-glyph gl))
4841 (overlay-put ovl 'display text)
4842 (if face (overlay-put ovl 'face face))
4843 (if evap (overlay-put ovl 'evaporate t))))
4844 (defun org-overlay-before-string (ovl text &optional face evap)
4845 "Make overlay OVL display TEXT with face FACE."
4846 (if (featurep 'xemacs)
4847 (let ((gl (make-glyph text)))
4848 (and face (set-glyph-face gl face))
4849 (set-extent-property ovl 'begin-glyph gl))
4850 (if face (org-add-props text nil 'face face))
4851 (overlay-put ovl 'before-string text)
4852 (if evap (overlay-put ovl 'evaporate t))))
4853 (defun org-overlay-get (ovl prop)
4854 (if (featurep 'xemacs)
4855 (extent-property ovl prop)
4856 (overlay-get ovl prop)))
4857 (defun org-overlays-at (pos)
4858 (if (featurep 'xemacs) (extents-at pos) (overlays-at pos)))
4859 (defun org-overlays-in (&optional start end)
4860 (if (featurep 'xemacs)
4861 (extent-list nil start end)
4862 (overlays-in start end)))
4863 (defun org-overlay-start (o)
4864 (if (featurep 'xemacs) (extent-start-position o) (overlay-start o)))
4865 (defun org-overlay-end (o)
4866 (if (featurep 'xemacs) (extent-end-position o) (overlay-end o)))
4867 (defun org-find-overlays (prop &optional pos delete)
4868 "Find all overlays specifying PROP at POS or point.
4869 If DELETE is non-nil, delete all those overlays."
4870 (let ((overlays (org-overlays-at (or pos (point))))
4871 ov found)
4872 (while (setq ov (pop overlays))
4873 (if (org-overlay-get ov prop)
4874 (if delete (org-delete-overlay ov) (push ov found))))
4875 found))
4877 ;; Region compatibility
4879 (defun org-add-hook (hook function &optional append local)
4880 "Add-hook, compatible with both Emacsen."
4881 (if (and local (featurep 'xemacs))
4882 (add-local-hook hook function append)
4883 (add-hook hook function append local)))
4885 (defvar org-ignore-region nil
4886 "To temporarily disable the active region.")
4888 (defun org-region-active-p ()
4889 "Is `transient-mark-mode' on and the region active?
4890 Works on both Emacs and XEmacs."
4891 (if org-ignore-region
4893 (if (featurep 'xemacs)
4894 (and zmacs-regions (region-active-p))
4895 (if (fboundp 'use-region-p)
4896 (use-region-p)
4897 (and transient-mark-mode mark-active))))) ; Emacs 22 and before
4899 ;; Invisibility compatibility
4901 (defun org-add-to-invisibility-spec (arg)
4902 "Add elements to `buffer-invisibility-spec'.
4903 See documentation for `buffer-invisibility-spec' for the kind of elements
4904 that can be added."
4905 (cond
4906 ((fboundp 'add-to-invisibility-spec)
4907 (add-to-invisibility-spec arg))
4908 ((or (null buffer-invisibility-spec) (eq buffer-invisibility-spec t))
4909 (setq buffer-invisibility-spec (list arg)))
4911 (setq buffer-invisibility-spec
4912 (cons arg buffer-invisibility-spec)))))
4914 (defun org-remove-from-invisibility-spec (arg)
4915 "Remove elements from `buffer-invisibility-spec'."
4916 (if (fboundp 'remove-from-invisibility-spec)
4917 (remove-from-invisibility-spec arg)
4918 (if (consp buffer-invisibility-spec)
4919 (setq buffer-invisibility-spec
4920 (delete arg buffer-invisibility-spec)))))
4922 (defun org-in-invisibility-spec-p (arg)
4923 "Is ARG a member of `buffer-invisibility-spec'?"
4924 (if (consp buffer-invisibility-spec)
4925 (member arg buffer-invisibility-spec)
4926 nil))
4928 ;;;; Define the Org-mode
4930 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
4931 (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."))
4934 ;; We use a before-change function to check if a table might need
4935 ;; an update.
4936 (defvar org-table-may-need-update t
4937 "Indicates that a table might need an update.
4938 This variable is set by `org-before-change-function'.
4939 `org-table-align' sets it back to nil.")
4940 (defvar org-mode-map)
4941 (defvar org-mode-hook nil)
4942 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4943 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
4944 (defvar org-table-buffer-is-an nil)
4945 (defconst org-outline-regexp "\\*+ ")
4947 ;;;###autoload
4948 (define-derived-mode org-mode outline-mode "Org"
4949 "Outline-based notes management and organizer, alias
4950 \"Carsten's outline-mode for keeping track of everything.\"
4952 Org-mode develops organizational tasks around a NOTES file which
4953 contains information about projects as plain text. Org-mode is
4954 implemented on top of outline-mode, which is ideal to keep the content
4955 of large files well structured. It supports ToDo items, deadlines and
4956 time stamps, which magically appear in the diary listing of the Emacs
4957 calendar. Tables are easily created with a built-in table editor.
4958 Plain text URL-like links connect to websites, emails (VM), Usenet
4959 messages (Gnus), BBDB entries, and any files related to the project.
4960 For printing and sharing of notes, an Org-mode file (or a part of it)
4961 can be exported as a structured ASCII or HTML file.
4963 The following commands are available:
4965 \\{org-mode-map}"
4967 ;; Get rid of Outline menus, they are not needed
4968 ;; Need to do this here because define-derived-mode sets up
4969 ;; the keymap so late. Still, it is a waste to call this each time
4970 ;; we switch another buffer into org-mode.
4971 (if (featurep 'xemacs)
4972 (when (boundp 'outline-mode-menu-heading)
4973 ;; Assume this is Greg's port, it used easymenu
4974 (easy-menu-remove outline-mode-menu-heading)
4975 (easy-menu-remove outline-mode-menu-show)
4976 (easy-menu-remove outline-mode-menu-hide))
4977 (define-key org-mode-map [menu-bar headings] 'undefined)
4978 (define-key org-mode-map [menu-bar hide] 'undefined)
4979 (define-key org-mode-map [menu-bar show] 'undefined))
4981 (easy-menu-add org-org-menu)
4982 (easy-menu-add org-tbl-menu)
4983 (org-install-agenda-files-menu)
4984 (if org-descriptive-links (org-add-to-invisibility-spec '(org-link)))
4985 (org-add-to-invisibility-spec '(org-cwidth))
4986 (when (featurep 'xemacs)
4987 (org-set-local 'line-move-ignore-invisible t))
4988 (org-set-local 'outline-regexp org-outline-regexp)
4989 (org-set-local 'outline-level 'org-outline-level)
4990 (when (and org-ellipsis
4991 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
4992 (fboundp 'make-glyph-code))
4993 (unless org-display-table
4994 (setq org-display-table (make-display-table)))
4995 (set-display-table-slot
4996 org-display-table 4
4997 (vconcat (mapcar
4998 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
4999 org-ellipsis)))
5000 (if (stringp org-ellipsis) org-ellipsis "..."))))
5001 (setq buffer-display-table org-display-table))
5002 (org-set-regexps-and-options)
5003 ;; Calc embedded
5004 (org-set-local 'calc-embedded-open-mode "# ")
5005 (modify-syntax-entry ?# "<")
5006 (modify-syntax-entry ?@ "w")
5007 (if org-startup-truncated (setq truncate-lines t))
5008 (org-set-local 'font-lock-unfontify-region-function
5009 'org-unfontify-region)
5010 ;; Activate before-change-function
5011 (org-set-local 'org-table-may-need-update t)
5012 (org-add-hook 'before-change-functions 'org-before-change-function nil
5013 'local)
5014 ;; Check for running clock before killing a buffer
5015 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
5016 ;; Paragraphs and auto-filling
5017 (org-set-autofill-regexps)
5018 (setq indent-line-function 'org-indent-line-function)
5019 (org-update-radio-target-regexp)
5021 ;; Comment characters
5022 ; (org-set-local 'comment-start "#") ;; FIXME: this breaks wrapping
5023 (org-set-local 'comment-padding " ")
5025 ;; Align options lines
5026 (org-set-local
5027 'align-mode-rules-list
5028 '((org-in-buffer-settings
5029 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5030 (modes . '(org-mode)))))
5032 ;; Imenu
5033 (org-set-local 'imenu-create-index-function
5034 'org-imenu-get-tree)
5036 ;; Make isearch reveal context
5037 (if (or (featurep 'xemacs)
5038 (not (boundp 'outline-isearch-open-invisible-function)))
5039 ;; Emacs 21 and XEmacs make use of the hook
5040 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
5041 ;; Emacs 22 deals with this through a special variable
5042 (org-set-local 'outline-isearch-open-invisible-function
5043 (lambda (&rest ignore) (org-show-context 'isearch))))
5045 ;; If empty file that did not turn on org-mode automatically, make it to.
5046 (if (and org-insert-mode-line-in-empty-file
5047 (interactive-p)
5048 (= (point-min) (point-max)))
5049 (insert "# -*- mode: org -*-\n\n"))
5051 (unless org-inhibit-startup
5052 (when org-startup-align-all-tables
5053 (let ((bmp (buffer-modified-p)))
5054 (org-table-map-tables 'org-table-align)
5055 (set-buffer-modified-p bmp)))
5056 (org-cycle-hide-drawers 'all)
5057 (cond
5058 ((eq org-startup-folded t)
5059 (org-cycle '(4)))
5060 ((eq org-startup-folded 'content)
5061 (let ((this-command 'org-cycle) (last-command 'org-cycle))
5062 (org-cycle '(4)) (org-cycle '(4)))))))
5064 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
5066 (defsubst org-call-with-arg (command arg)
5067 "Call COMMAND interactively, but pretend prefix are was ARG."
5068 (let ((current-prefix-arg arg)) (call-interactively command)))
5070 (defsubst org-current-line (&optional pos)
5071 (save-excursion
5072 (and pos (goto-char pos))
5073 ;; works also in narrowed buffer, because we start at 1, not point-min
5074 (+ (if (bolp) 1 0) (count-lines 1 (point)))))
5076 (defun org-current-time ()
5077 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
5078 (if (> org-time-stamp-rounding-minutes 0)
5079 (let ((r org-time-stamp-rounding-minutes)
5080 (time (decode-time)))
5081 (apply 'encode-time
5082 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5083 (nthcdr 2 time))))
5084 (current-time)))
5086 (defun org-add-props (string plist &rest props)
5087 "Add text properties to entire string, from beginning to end.
5088 PLIST may be a list of properties, PROPS are individual properties and values
5089 that will be added to PLIST. Returns the string that was modified."
5090 (add-text-properties
5091 0 (length string) (if props (append plist props) plist) string)
5092 string)
5093 (put 'org-add-props 'lisp-indent-function 2)
5096 ;;;; Font-Lock stuff, including the activators
5098 (defvar org-mouse-map (make-sparse-keymap))
5099 (org-defkey org-mouse-map
5100 (if (featurep 'xemacs) [button2] [mouse-2]) 'org-open-at-mouse)
5101 (org-defkey org-mouse-map
5102 (if (featurep 'xemacs) [button3] [mouse-3]) 'org-find-file-at-mouse)
5103 (when org-mouse-1-follows-link
5104 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5105 (when org-tab-follows-link
5106 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5107 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5108 (when org-return-follows-link
5109 (org-defkey org-mouse-map [(return)] 'org-open-at-point)
5110 (org-defkey org-mouse-map "\C-m" 'org-open-at-point))
5112 (require 'font-lock)
5114 (defconst org-non-link-chars "]\t\n\r<>")
5115 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news" "bbdb" "vm"
5116 "wl" "mhe" "rmail" "gnus" "shell" "info" "elisp" "message"))
5117 (defvar org-link-re-with-space nil
5118 "Matches a link with spaces, optional angular brackets around it.")
5119 (defvar org-link-re-with-space2 nil
5120 "Matches a link with spaces, optional angular brackets around it.")
5121 (defvar org-angle-link-re nil
5122 "Matches link with angular brackets, spaces are allowed.")
5123 (defvar org-plain-link-re nil
5124 "Matches plain link, without spaces.")
5125 (defvar org-bracket-link-regexp nil
5126 "Matches a link in double brackets.")
5127 (defvar org-bracket-link-analytic-regexp nil
5128 "Regular expression used to analyze links.
5129 Here is what the match groups contain after a match:
5130 1: http:
5131 2: http
5132 3: path
5133 4: [desc]
5134 5: desc")
5135 (defvar org-any-link-re nil
5136 "Regular expression matching any link.")
5138 (defun org-make-link-regexps ()
5139 "Update the link regular expressions.
5140 This should be called after the variable `org-link-types' has changed."
5141 (setq org-link-re-with-space
5142 (concat
5143 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
5144 "\\([^" org-non-link-chars " ]"
5145 "[^" org-non-link-chars "]*"
5146 "[^" org-non-link-chars " ]\\)>?")
5147 org-link-re-with-space2
5148 (concat
5149 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
5150 "\\([^" org-non-link-chars " ]"
5151 "[^]\t\n\r]*"
5152 "[^" org-non-link-chars " ]\\)>?")
5153 org-angle-link-re
5154 (concat
5155 "<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
5156 "\\([^" org-non-link-chars " ]"
5157 "[^" org-non-link-chars "]*"
5158 "\\)>")
5159 org-plain-link-re
5160 (concat
5161 "\\<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
5162 "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5163 org-bracket-link-regexp
5164 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5165 org-bracket-link-analytic-regexp
5166 (concat
5167 "\\[\\["
5168 "\\(\\(" (mapconcat 'identity org-link-types "\\|") "\\):\\)?"
5169 "\\([^]]+\\)"
5170 "\\]"
5171 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5172 "\\]")
5173 org-any-link-re
5174 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5175 org-angle-link-re "\\)\\|\\("
5176 org-plain-link-re "\\)")))
5178 (org-make-link-regexps)
5180 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)>"
5181 "Regular expression for fast time stamp matching.")
5182 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)[]>]"
5183 "Regular expression for fast time stamp matching.")
5184 (defconst org-ts-regexp0 "\\(\\([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 This one does not require the space after the date.")
5187 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) \\([^]0-9>\r\n]*\\)\\(\\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5188 "Regular expression matching time strings for analysis.")
5189 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
5190 "Regular expression matching time stamps, with groups.")
5191 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
5192 "Regular expression matching time stamps (also [..]), with groups.")
5193 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
5194 "Regular expression matching a time stamp range.")
5195 (defconst org-tr-regexp-both
5196 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
5197 "Regular expression matching a time stamp range.")
5198 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
5199 org-ts-regexp "\\)?")
5200 "Regular expression matching a time stamp or time stamp range.")
5201 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
5202 org-ts-regexp-both "\\)?")
5203 "Regular expression matching a time stamp or time stamp range.
5204 The time stamps may be either active or inactive.")
5206 (defvar org-emph-face nil)
5208 (defun org-do-emphasis-faces (limit)
5209 "Run through the buffer and add overlays to links."
5210 (let (rtn)
5211 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5212 (if (not (= (char-after (match-beginning 3))
5213 (char-after (match-beginning 4))))
5214 (progn
5215 (setq rtn t)
5216 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5217 'face
5218 (nth 1 (assoc (match-string 3)
5219 org-emphasis-alist)))
5220 (add-text-properties (match-beginning 2) (match-end 2)
5221 '(font-lock-multiline t))
5222 (when org-hide-emphasis-markers
5223 (add-text-properties (match-end 4) (match-beginning 5)
5224 '(invisible org-link))
5225 (add-text-properties (match-beginning 3) (match-end 3)
5226 '(invisible org-link)))))
5227 (backward-char 1))
5228 rtn))
5230 (defun org-emphasize (&optional char)
5231 "Insert or change an emphasis, i.e. a font like bold or italic.
5232 If there is an active region, change that region to a new emphasis.
5233 If there is no region, just insert the marker characters and position
5234 the cursor between them.
5235 CHAR should be either the marker character, or the first character of the
5236 HTML tag associated with that emphasis. If CHAR is a space, the means
5237 to remove the emphasis of the selected region.
5238 If char is not given (for example in an interactive call) it
5239 will be prompted for."
5240 (interactive)
5241 (let ((eal org-emphasis-alist) e det
5242 (erc org-emphasis-regexp-components)
5243 (prompt "")
5244 (string "") beg end move tag c s)
5245 (if (org-region-active-p)
5246 (setq beg (region-beginning) end (region-end)
5247 string (buffer-substring beg end))
5248 (setq move t))
5250 (while (setq e (pop eal))
5251 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
5252 c (aref tag 0))
5253 (push (cons c (string-to-char (car e))) det)
5254 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
5255 (substring tag 1)))))
5256 (unless char
5257 (message "%s" (concat "Emphasis marker or tag:" prompt))
5258 (setq char (read-char-exclusive)))
5259 (setq char (or (cdr (assoc char det)) char))
5260 (if (equal char ?\ )
5261 (setq s "" move nil)
5262 (unless (assoc (char-to-string char) org-emphasis-alist)
5263 (error "No such emphasis marker: \"%c\"" char))
5264 (setq s (char-to-string char)))
5265 (while (and (> (length string) 1)
5266 (equal (substring string 0 1) (substring string -1))
5267 (assoc (substring string 0 1) org-emphasis-alist))
5268 (setq string (substring string 1 -1)))
5269 (setq string (concat s string s))
5270 (if beg (delete-region beg end))
5271 (unless (or (bolp)
5272 (string-match (concat "[" (nth 0 erc) "\n]")
5273 (char-to-string (char-before (point)))))
5274 (insert " "))
5275 (unless (string-match (concat "[" (nth 1 erc) "\n]")
5276 (char-to-string (char-after (point))))
5277 (insert " ") (backward-char 1))
5278 (insert string)
5279 (and move (backward-char 1))))
5281 (defconst org-nonsticky-props
5282 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
5285 (defun org-activate-plain-links (limit)
5286 "Run through the buffer and add overlays to links."
5287 (catch 'exit
5288 (let (f)
5289 (while (re-search-forward org-plain-link-re limit t)
5290 (setq f (get-text-property (match-beginning 0) 'face))
5291 (if (or (eq f 'org-tag)
5292 (and (listp f) (memq 'org-tag f)))
5294 (add-text-properties (match-beginning 0) (match-end 0)
5295 (list 'mouse-face 'highlight
5296 'rear-nonsticky org-nonsticky-props
5297 'keymap org-mouse-map
5299 (throw 'exit t))))))
5301 (defun org-activate-code (limit)
5302 (if (re-search-forward "^[ \t]*\\(:.*\\)" limit t)
5303 (unless (get-text-property (match-beginning 1) 'face)
5304 (remove-text-properties (match-beginning 0) (match-end 0)
5305 '(display t invisible t intangible t))
5306 t)))
5308 (defun org-activate-angle-links (limit)
5309 "Run through the buffer and add overlays to links."
5310 (if (re-search-forward org-angle-link-re limit t)
5311 (progn
5312 (add-text-properties (match-beginning 0) (match-end 0)
5313 (list 'mouse-face 'highlight
5314 'rear-nonsticky org-nonsticky-props
5315 'keymap org-mouse-map
5317 t)))
5319 (defmacro org-maybe-intangible (props)
5320 "Add '(intangigble t) to PROPS if Emacs version is earlier than Emacs 22.
5321 In emacs 21, invisible text is not avoided by the command loop, so the
5322 intangible property is needed to make sure point skips this text.
5323 In Emacs 22, this is not necessary. The intangible text property has
5324 led to problems with flyspell. These problems are fixed in flyspell.el,
5325 but we still avoid setting the property in Emacs 22 and later.
5326 We use a macro so that the test can happen at compilation time."
5327 (if (< emacs-major-version 22)
5328 `(append '(intangible t) ,props)
5329 props))
5331 (defun org-activate-bracket-links (limit)
5332 "Run through the buffer and add overlays to bracketed links."
5333 (if (re-search-forward org-bracket-link-regexp limit t)
5334 (let* ((help (concat "LINK: "
5335 (org-match-string-no-properties 1)))
5336 ;; FIXME: above we should remove the escapes.
5337 ;; but that requires another match, protecting match data,
5338 ;; a lot of overhead for font-lock.
5339 (ip (org-maybe-intangible
5340 (list 'invisible 'org-link 'rear-nonsticky org-nonsticky-props
5341 'keymap org-mouse-map 'mouse-face 'highlight
5342 'font-lock-multiline t 'help-echo help)))
5343 (vp (list 'rear-nonsticky org-nonsticky-props
5344 'keymap org-mouse-map 'mouse-face 'highlight
5345 ' font-lock-multiline t 'help-echo help)))
5346 ;; We need to remove the invisible property here. Table narrowing
5347 ;; may have made some of this invisible.
5348 (remove-text-properties (match-beginning 0) (match-end 0)
5349 '(invisible nil))
5350 (if (match-end 3)
5351 (progn
5352 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
5353 (add-text-properties (match-beginning 3) (match-end 3) vp)
5354 (add-text-properties (match-end 3) (match-end 0) ip))
5355 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
5356 (add-text-properties (match-beginning 1) (match-end 1) vp)
5357 (add-text-properties (match-end 1) (match-end 0) ip))
5358 t)))
5360 (defun org-activate-dates (limit)
5361 "Run through the buffer and add overlays to dates."
5362 (if (re-search-forward org-tsr-regexp-both limit t)
5363 (progn
5364 (add-text-properties (match-beginning 0) (match-end 0)
5365 (list 'mouse-face 'highlight
5366 'rear-nonsticky org-nonsticky-props
5367 'keymap org-mouse-map))
5368 (when org-display-custom-times
5369 (if (match-end 3)
5370 (org-display-custom-time (match-beginning 3) (match-end 3)))
5371 (org-display-custom-time (match-beginning 1) (match-end 1)))
5372 t)))
5374 (defvar org-target-link-regexp nil
5375 "Regular expression matching radio targets in plain text.")
5376 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
5377 "Regular expression matching a link target.")
5378 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
5379 "Regular expression matching a radio target.")
5380 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
5381 "Regular expression matching any target.")
5383 (defun org-activate-target-links (limit)
5384 "Run through the buffer and add overlays to target matches."
5385 (when org-target-link-regexp
5386 (let ((case-fold-search t))
5387 (if (re-search-forward org-target-link-regexp limit t)
5388 (progn
5389 (add-text-properties (match-beginning 0) (match-end 0)
5390 (list 'mouse-face 'highlight
5391 'rear-nonsticky org-nonsticky-props
5392 'keymap org-mouse-map
5393 'help-echo "Radio target link"
5394 'org-linked-text t))
5395 t)))))
5397 (defun org-update-radio-target-regexp ()
5398 "Find all radio targets in this file and update the regular expression."
5399 (interactive)
5400 (when (memq 'radio org-activate-links)
5401 (setq org-target-link-regexp
5402 (org-make-target-link-regexp (org-all-targets 'radio)))
5403 (org-restart-font-lock)))
5405 (defun org-hide-wide-columns (limit)
5406 (let (s e)
5407 (setq s (text-property-any (point) (or limit (point-max))
5408 'org-cwidth t))
5409 (when s
5410 (setq e (next-single-property-change s 'org-cwidth))
5411 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
5412 (goto-char e)
5413 t)))
5415 (defvar org-latex-and-specials-regexp nil
5416 "Regular expression for highlighting export special stuff.")
5417 (defvar org-match-substring-regexp)
5418 (defvar org-match-substring-with-braces-regexp)
5419 (defvar org-export-html-special-string-regexps)
5421 (defun org-compute-latex-and-specials-regexp ()
5422 "Compute regular expression for stuff treated specially by exporters."
5423 (if (not org-highlight-latex-fragments-and-specials)
5424 (org-set-local 'org-latex-and-specials-regexp nil)
5425 (let*
5426 ((matchers (plist-get org-format-latex-options :matchers))
5427 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
5428 org-latex-regexps)))
5429 (options (org-combine-plists (org-default-export-plist)
5430 (org-infile-export-plist)))
5431 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
5432 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
5433 (org-export-with-TeX-macros (plist-get options :TeX-macros))
5434 (org-export-html-expand (plist-get options :expand-quoted-html))
5435 (org-export-with-special-strings (plist-get options :special-strings))
5436 (re-sub
5437 (cond
5438 ((equal org-export-with-sub-superscripts '{})
5439 (list org-match-substring-with-braces-regexp))
5440 (org-export-with-sub-superscripts
5441 (list org-match-substring-regexp))
5442 (t nil)))
5443 (re-latex
5444 (if org-export-with-LaTeX-fragments
5445 (mapcar (lambda (x) (nth 1 x)) latexs)))
5446 (re-macros
5447 (if org-export-with-TeX-macros
5448 (list (concat "\\\\"
5449 (regexp-opt
5450 (append (mapcar 'car org-html-entities)
5451 (if (boundp 'org-latex-entities)
5452 org-latex-entities nil))
5453 'words))) ; FIXME
5455 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
5456 (re-special (if org-export-with-special-strings
5457 (mapcar (lambda (x) (car x))
5458 org-export-html-special-string-regexps)))
5459 (re-rest
5460 (delq nil
5461 (list
5462 (if org-export-html-expand "@<[^>\n]+>")
5463 ))))
5464 (org-set-local
5465 'org-latex-and-specials-regexp
5466 (mapconcat 'identity (append re-latex re-sub re-macros re-special
5467 re-rest) "\\|")))))
5469 (defface org-latex-and-export-specials
5470 (let ((font (cond ((assq :inherit custom-face-attributes)
5471 '(:inherit underline))
5472 (t '(:underline t)))))
5473 `((((class grayscale) (background light))
5474 (:foreground "DimGray" ,@font))
5475 (((class grayscale) (background dark))
5476 (:foreground "LightGray" ,@font))
5477 (((class color) (background light))
5478 (:foreground "SaddleBrown"))
5479 (((class color) (background dark))
5480 (:foreground "burlywood"))
5481 (t (,@font))))
5482 "Face used to highlight math latex and other special exporter stuff."
5483 :group 'org-faces)
5485 (defun org-do-latex-and-special-faces (limit)
5486 "Run through the buffer and add overlays to links."
5487 (when org-latex-and-specials-regexp
5488 (let (rtn d)
5489 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
5490 limit t))
5491 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
5492 'face))
5493 '(org-code org-verbatim underline)))
5494 (progn
5495 (setq rtn t
5496 d (cond ((member (char-after (1+ (match-beginning 0)))
5497 '(?_ ?^)) 1)
5498 (t 0)))
5499 (font-lock-prepend-text-property
5500 (+ d (match-beginning 0)) (match-end 0)
5501 'face 'org-latex-and-export-specials)
5502 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
5503 '(font-lock-multiline t)))))
5504 rtn)))
5506 (defun org-restart-font-lock ()
5507 "Restart font-lock-mode, to force refontification."
5508 (when (and (boundp 'font-lock-mode) font-lock-mode)
5509 (font-lock-mode -1)
5510 (font-lock-mode 1)))
5512 (defun org-all-targets (&optional radio)
5513 "Return a list of all targets in this file.
5514 With optional argument RADIO, only find radio targets."
5515 (let ((re (if radio org-radio-target-regexp org-target-regexp))
5516 rtn)
5517 (save-excursion
5518 (goto-char (point-min))
5519 (while (re-search-forward re nil t)
5520 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
5521 rtn)))
5523 (defun org-make-target-link-regexp (targets)
5524 "Make regular expression matching all strings in TARGETS.
5525 The regular expression finds the targets also if there is a line break
5526 between words."
5527 (and targets
5528 (concat
5529 "\\<\\("
5530 (mapconcat
5531 (lambda (x)
5532 (while (string-match " +" x)
5533 (setq x (replace-match "\\s-+" t t x)))
5535 targets
5536 "\\|")
5537 "\\)\\>")))
5539 (defun org-activate-tags (limit)
5540 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \r\n]") limit t)
5541 (progn
5542 (add-text-properties (match-beginning 1) (match-end 1)
5543 (list 'mouse-face 'highlight
5544 'rear-nonsticky org-nonsticky-props
5545 'keymap org-mouse-map))
5546 t)))
5548 (defun org-outline-level ()
5549 (save-excursion
5550 (looking-at outline-regexp)
5551 (if (match-beginning 1)
5552 (+ (org-get-string-indentation (match-string 1)) 1000)
5553 (1- (- (match-end 0) (match-beginning 0))))))
5555 (defvar org-font-lock-keywords nil)
5557 (defconst org-property-re (org-re "^[ \t]*\\(:\\([[:alnum:]_]+\\):\\)[ \t]*\\(\\S-.*\\)")
5558 "Regular expression matching a property line.")
5560 (defun org-set-font-lock-defaults ()
5561 (let* ((em org-fontify-emphasized-text)
5562 (lk org-activate-links)
5563 (org-font-lock-extra-keywords
5564 (list
5565 ;; Headlines
5566 '("^\\(\\**\\)\\(\\* \\)\\(.*\\)" (1 (org-get-level-face 1))
5567 (2 (org-get-level-face 2)) (3 (org-get-level-face 3)))
5568 ;; Table lines
5569 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
5570 (1 'org-table t))
5571 ;; Table internals
5572 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
5573 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
5574 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
5575 ;; Drawers
5576 (list org-drawer-regexp '(0 'org-special-keyword t))
5577 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
5578 ;; Properties
5579 (list org-property-re
5580 '(1 'org-special-keyword t)
5581 '(3 'org-property-value t))
5582 (if org-format-transports-properties-p
5583 '("| *\\(<[0-9]+>\\) *" (1 'org-formula t)))
5584 ;; Links
5585 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
5586 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
5587 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
5588 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
5589 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
5590 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
5591 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
5592 '(org-hide-wide-columns (0 nil append))
5593 ;; TODO lines
5594 (list (concat "^\\*+[ \t]+" org-todo-regexp)
5595 '(1 (org-get-todo-face 1) t))
5596 ;; DONE
5597 (if org-fontify-done-headline
5598 (list (concat "^[*]+ +\\<\\("
5599 (mapconcat 'regexp-quote org-done-keywords "\\|")
5600 "\\)\\(.*\\)")
5601 '(2 'org-headline-done t))
5602 nil)
5603 ;; Priorities
5604 (list (concat "\\[#[A-Z0-9]\\]") '(0 'org-special-keyword t))
5605 ;; Special keywords
5606 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
5607 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
5608 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
5609 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
5610 ;; Emphasis
5611 (if em
5612 (if (featurep 'xemacs)
5613 '(org-do-emphasis-faces (0 nil append))
5614 '(org-do-emphasis-faces)))
5615 ;; Checkboxes
5616 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)"
5617 2 'bold prepend)
5618 (if org-provide-checkbox-statistics
5619 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
5620 (0 (org-get-checkbox-statistics-face) t)))
5621 (list (concat "^\\*+ \\(.*:" org-archive-tag ":.*\\)")
5622 '(1 'org-archived prepend))
5623 ;; Specials
5624 '(org-do-latex-and-special-faces)
5625 ;; Code
5626 '(org-activate-code (1 'org-code t))
5627 ;; COMMENT
5628 (list (concat "^\\*+[ \t]+\\<\\(" org-comment-string
5629 "\\|" org-quote-string "\\)\\>")
5630 '(1 'org-special-keyword t))
5631 '("^#.*" (0 'font-lock-comment-face t))
5633 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
5634 ;; Now set the full font-lock-keywords
5635 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
5636 (org-set-local 'font-lock-defaults
5637 '(org-font-lock-keywords t nil nil backward-paragraph))
5638 (kill-local-variable 'font-lock-keywords) nil))
5640 (defvar org-m nil)
5641 (defvar org-l nil)
5642 (defvar org-f nil)
5643 (defun org-get-level-face (n)
5644 "Get the right face for match N in font-lock matching of healdines."
5645 (setq org-l (- (match-end 2) (match-beginning 1) 1))
5646 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
5647 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
5648 (cond
5649 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
5650 ((eq n 2) org-f)
5651 (t (if org-level-color-stars-only nil org-f))))
5653 (defun org-get-todo-face (kwd)
5654 "Get the right face for a TODO keyword KWD.
5655 If KWD is a number, get the corresponding match group."
5656 (if (numberp kwd) (setq kwd (match-string kwd)))
5657 (or (cdr (assoc kwd org-todo-keyword-faces))
5658 (and (member kwd org-done-keywords) 'org-done)
5659 'org-todo))
5661 (defun org-unfontify-region (beg end &optional maybe_loudly)
5662 "Remove fontification and activation overlays from links."
5663 (font-lock-default-unfontify-region beg end)
5664 (let* ((buffer-undo-list t)
5665 (inhibit-read-only t) (inhibit-point-motion-hooks t)
5666 (inhibit-modification-hooks t)
5667 deactivate-mark buffer-file-name buffer-file-truename)
5668 (remove-text-properties beg end
5669 '(mouse-face t keymap t org-linked-text t
5670 invisible t intangible t))))
5672 ;;;; Visibility cycling, including org-goto and indirect buffer
5674 ;;; Cycling
5676 (defvar org-cycle-global-status nil)
5677 (make-variable-buffer-local 'org-cycle-global-status)
5678 (defvar org-cycle-subtree-status nil)
5679 (make-variable-buffer-local 'org-cycle-subtree-status)
5681 ;;;###autoload
5682 (defun org-cycle (&optional arg)
5683 "Visibility cycling for Org-mode.
5685 - When this function is called with a prefix argument, rotate the entire
5686 buffer through 3 states (global cycling)
5687 1. OVERVIEW: Show only top-level headlines.
5688 2. CONTENTS: Show all headlines of all levels, but no body text.
5689 3. SHOW ALL: Show everything.
5691 - When point is at the beginning of a headline, rotate the subtree started
5692 by this line through 3 different states (local cycling)
5693 1. FOLDED: Only the main headline is shown.
5694 2. CHILDREN: The main headline and the direct children are shown.
5695 From this state, you can move to one of the children
5696 and zoom in further.
5697 3. SUBTREE: Show the entire subtree, including body text.
5699 - When there is a numeric prefix, go up to a heading with level ARG, do
5700 a `show-subtree' and return to the previous cursor position. If ARG
5701 is negative, go up that many levels.
5703 - When point is not at the beginning of a headline, execute
5704 `indent-relative', like TAB normally does. See the option
5705 `org-cycle-emulate-tab' for details.
5707 - Special case: if point is at the beginning of the buffer and there is
5708 no headline in line 1, this function will act as if called with prefix arg.
5709 But only if also the variable `org-cycle-global-at-bob' is t."
5710 (interactive "P")
5711 (let* ((outline-regexp
5712 (if (and (org-mode-p) org-cycle-include-plain-lists)
5713 "\\(?:\\*+ \\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) \\)"
5714 outline-regexp))
5715 (bob-special (and org-cycle-global-at-bob (bobp)
5716 (not (looking-at outline-regexp))))
5717 (org-cycle-hook
5718 (if bob-special
5719 (delq 'org-optimize-window-after-visibility-change
5720 (copy-sequence org-cycle-hook))
5721 org-cycle-hook))
5722 (pos (point)))
5724 (if (or bob-special (equal arg '(4)))
5725 ;; special case: use global cycling
5726 (setq arg t))
5728 (cond
5730 ((org-at-table-p 'any)
5731 ;; Enter the table or move to the next field in the table
5732 (or (org-table-recognize-table.el)
5733 (progn
5734 (if arg (org-table-edit-field t)
5735 (org-table-justify-field-maybe)
5736 (call-interactively 'org-table-next-field)))))
5738 ((eq arg t) ;; Global cycling
5740 (cond
5741 ((and (eq last-command this-command)
5742 (eq org-cycle-global-status 'overview))
5743 ;; We just created the overview - now do table of contents
5744 ;; This can be slow in very large buffers, so indicate action
5745 (message "CONTENTS...")
5746 (org-content)
5747 (message "CONTENTS...done")
5748 (setq org-cycle-global-status 'contents)
5749 (run-hook-with-args 'org-cycle-hook 'contents))
5751 ((and (eq last-command this-command)
5752 (eq org-cycle-global-status 'contents))
5753 ;; We just showed the table of contents - now show everything
5754 (show-all)
5755 (message "SHOW ALL")
5756 (setq org-cycle-global-status 'all)
5757 (run-hook-with-args 'org-cycle-hook 'all))
5760 ;; Default action: go to overview
5761 (org-overview)
5762 (message "OVERVIEW")
5763 (setq org-cycle-global-status 'overview)
5764 (run-hook-with-args 'org-cycle-hook 'overview))))
5766 ((and org-drawers org-drawer-regexp
5767 (save-excursion
5768 (beginning-of-line 1)
5769 (looking-at org-drawer-regexp)))
5770 ;; Toggle block visibility
5771 (org-flag-drawer
5772 (not (get-char-property (match-end 0) 'invisible))))
5774 ((integerp arg)
5775 ;; Show-subtree, ARG levels up from here.
5776 (save-excursion
5777 (org-back-to-heading)
5778 (outline-up-heading (if (< arg 0) (- arg)
5779 (- (funcall outline-level) arg)))
5780 (org-show-subtree)))
5782 ((and (save-excursion (beginning-of-line 1) (looking-at outline-regexp))
5783 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
5784 ;; At a heading: rotate between three different views
5785 (org-back-to-heading)
5786 (let ((goal-column 0) eoh eol eos)
5787 ;; First, some boundaries
5788 (save-excursion
5789 (org-back-to-heading)
5790 (save-excursion
5791 (beginning-of-line 2)
5792 (while (and (not (eobp)) ;; this is like `next-line'
5793 (get-char-property (1- (point)) 'invisible))
5794 (beginning-of-line 2)) (setq eol (point)))
5795 (outline-end-of-heading) (setq eoh (point))
5796 (org-end-of-subtree t)
5797 (unless (eobp)
5798 (skip-chars-forward " \t\n")
5799 (beginning-of-line 1) ; in case this is an item
5801 (setq eos (1- (point))))
5802 ;; Find out what to do next and set `this-command'
5803 (cond
5804 ((= eos eoh)
5805 ;; Nothing is hidden behind this heading
5806 (message "EMPTY ENTRY")
5807 (setq org-cycle-subtree-status nil)
5808 (save-excursion
5809 (goto-char eos)
5810 (outline-next-heading)
5811 (if (org-invisible-p) (org-flag-heading nil))))
5812 ((or (>= eol eos)
5813 (not (string-match "\\S-" (buffer-substring eol eos))))
5814 ;; Entire subtree is hidden in one line: open it
5815 (org-show-entry)
5816 (show-children)
5817 (message "CHILDREN")
5818 (save-excursion
5819 (goto-char eos)
5820 (outline-next-heading)
5821 (if (org-invisible-p) (org-flag-heading nil)))
5822 (setq org-cycle-subtree-status 'children)
5823 (run-hook-with-args 'org-cycle-hook 'children))
5824 ((and (eq last-command this-command)
5825 (eq org-cycle-subtree-status 'children))
5826 ;; We just showed the children, now show everything.
5827 (org-show-subtree)
5828 (message "SUBTREE")
5829 (setq org-cycle-subtree-status 'subtree)
5830 (run-hook-with-args 'org-cycle-hook 'subtree))
5832 ;; Default action: hide the subtree.
5833 (hide-subtree)
5834 (message "FOLDED")
5835 (setq org-cycle-subtree-status 'folded)
5836 (run-hook-with-args 'org-cycle-hook 'folded)))))
5838 ;; TAB emulation
5839 (buffer-read-only (org-back-to-heading))
5841 ((org-try-cdlatex-tab))
5843 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
5844 (or (not (bolp))
5845 (not (looking-at outline-regexp))))
5846 (call-interactively (global-key-binding "\t")))
5848 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
5849 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
5850 (or (and (eq org-cycle-emulate-tab 'white)
5851 (= (match-end 0) (point-at-eol)))
5852 (and (eq org-cycle-emulate-tab 'whitestart)
5853 (>= (match-end 0) pos))))
5855 (eq org-cycle-emulate-tab t))
5856 ; (if (and (looking-at "[ \n\r\t]")
5857 ; (string-match "^[ \t]*$" (buffer-substring
5858 ; (point-at-bol) (point))))
5859 ; (progn
5860 ; (beginning-of-line 1)
5861 ; (and (looking-at "[ \t]+") (replace-match ""))))
5862 (call-interactively (global-key-binding "\t")))
5864 (t (save-excursion
5865 (org-back-to-heading)
5866 (org-cycle))))))
5868 ;;;###autoload
5869 (defun org-global-cycle (&optional arg)
5870 "Cycle the global visibility. For details see `org-cycle'."
5871 (interactive "P")
5872 (let ((org-cycle-include-plain-lists
5873 (if (org-mode-p) org-cycle-include-plain-lists nil)))
5874 (if (integerp arg)
5875 (progn
5876 (show-all)
5877 (hide-sublevels arg)
5878 (setq org-cycle-global-status 'contents))
5879 (org-cycle '(4)))))
5881 (defun org-overview ()
5882 "Switch to overview mode, shoing only top-level headlines.
5883 Really, this shows all headlines with level equal or greater than the level
5884 of the first headline in the buffer. This is important, because if the
5885 first headline is not level one, then (hide-sublevels 1) gives confusing
5886 results."
5887 (interactive)
5888 (let ((level (save-excursion
5889 (goto-char (point-min))
5890 (if (re-search-forward (concat "^" outline-regexp) nil t)
5891 (progn
5892 (goto-char (match-beginning 0))
5893 (funcall outline-level))))))
5894 (and level (hide-sublevels level))))
5896 (defun org-content (&optional arg)
5897 "Show all headlines in the buffer, like a table of contents.
5898 With numerical argument N, show content up to level N."
5899 (interactive "P")
5900 (save-excursion
5901 ;; Visit all headings and show their offspring
5902 (and (integerp arg) (org-overview))
5903 (goto-char (point-max))
5904 (catch 'exit
5905 (while (and (progn (condition-case nil
5906 (outline-previous-visible-heading 1)
5907 (error (goto-char (point-min))))
5909 (looking-at outline-regexp))
5910 (if (integerp arg)
5911 (show-children (1- arg))
5912 (show-branches))
5913 (if (bobp) (throw 'exit nil))))))
5916 (defun org-optimize-window-after-visibility-change (state)
5917 "Adjust the window after a change in outline visibility.
5918 This function is the default value of the hook `org-cycle-hook'."
5919 (when (get-buffer-window (current-buffer))
5920 (cond
5921 ; ((eq state 'overview) (org-first-headline-recenter 1))
5922 ; ((eq state 'overview) (org-beginning-of-line))
5923 ((eq state 'content) nil)
5924 ((eq state 'all) nil)
5925 ((eq state 'folded) nil)
5926 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
5927 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
5929 (defun org-compact-display-after-subtree-move ()
5930 (let (beg end)
5931 (save-excursion
5932 (if (org-up-heading-safe)
5933 (progn
5934 (hide-subtree)
5935 (show-entry)
5936 (show-children)
5937 (org-cycle-show-empty-lines 'children)
5938 (org-cycle-hide-drawers 'children))
5939 (org-overview)))))
5941 (defun org-cycle-show-empty-lines (state)
5942 "Show empty lines above all visible headlines.
5943 The region to be covered depends on STATE when called through
5944 `org-cycle-hook'. Lisp program can use t for STATE to get the
5945 entire buffer covered. Note that an empty line is only shown if there
5946 are at least `org-cycle-separator-lines' empty lines before the headeline."
5947 (when (> org-cycle-separator-lines 0)
5948 (save-excursion
5949 (let* ((n org-cycle-separator-lines)
5950 (re (cond
5951 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
5952 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
5953 (t (let ((ns (number-to-string (- n 2))))
5954 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
5955 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
5956 beg end)
5957 (cond
5958 ((memq state '(overview contents t))
5959 (setq beg (point-min) end (point-max)))
5960 ((memq state '(children folded))
5961 (setq beg (point) end (progn (org-end-of-subtree t t)
5962 (beginning-of-line 2)
5963 (point)))))
5964 (when beg
5965 (goto-char beg)
5966 (while (re-search-forward re end t)
5967 (if (not (get-char-property (match-end 1) 'invisible))
5968 (outline-flag-region
5969 (match-beginning 1) (match-end 1) nil)))))))
5970 ;; Never hide empty lines at the end of the file.
5971 (save-excursion
5972 (goto-char (point-max))
5973 (outline-previous-heading)
5974 (outline-end-of-heading)
5975 (if (and (looking-at "[ \t\n]+")
5976 (= (match-end 0) (point-max)))
5977 (outline-flag-region (point) (match-end 0) nil))))
5979 (defun org-subtree-end-visible-p ()
5980 "Is the end of the current subtree visible?"
5981 (pos-visible-in-window-p
5982 (save-excursion (org-end-of-subtree t) (point))))
5984 (defun org-first-headline-recenter (&optional N)
5985 "Move cursor to the first headline and recenter the headline.
5986 Optional argument N means, put the headline into the Nth line of the window."
5987 (goto-char (point-min))
5988 (when (re-search-forward (concat "^\\(" outline-regexp "\\)") nil t)
5989 (beginning-of-line)
5990 (recenter (prefix-numeric-value N))))
5992 ;;; Org-goto
5994 (defvar org-goto-window-configuration nil)
5995 (defvar org-goto-marker nil)
5996 (defvar org-goto-map
5997 (let ((map (make-sparse-keymap)))
5998 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
5999 (while (setq cmd (pop cmds))
6000 (substitute-key-definition cmd cmd map global-map)))
6001 (suppress-keymap map)
6002 (org-defkey map "\C-m" 'org-goto-ret)
6003 (org-defkey map [(return)] 'org-goto-ret)
6004 (org-defkey map [(left)] 'org-goto-left)
6005 (org-defkey map [(right)] 'org-goto-right)
6006 (org-defkey map [(control ?g)] 'org-goto-quit)
6007 (org-defkey map "\C-i" 'org-cycle)
6008 (org-defkey map [(tab)] 'org-cycle)
6009 (org-defkey map [(down)] 'outline-next-visible-heading)
6010 (org-defkey map [(up)] 'outline-previous-visible-heading)
6011 (if org-goto-auto-isearch
6012 (if (fboundp 'define-key-after)
6013 (define-key-after map [t] 'org-goto-local-auto-isearch)
6014 nil)
6015 (org-defkey map "q" 'org-goto-quit)
6016 (org-defkey map "n" 'outline-next-visible-heading)
6017 (org-defkey map "p" 'outline-previous-visible-heading)
6018 (org-defkey map "f" 'outline-forward-same-level)
6019 (org-defkey map "b" 'outline-backward-same-level)
6020 (org-defkey map "u" 'outline-up-heading))
6021 (org-defkey map "/" 'org-occur)
6022 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
6023 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
6024 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
6025 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
6026 (org-defkey map "\C-c\C-u" 'outline-up-heading)
6027 map))
6029 (defconst org-goto-help
6030 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
6031 RET=jump to location [Q]uit and return to previous location
6032 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
6034 (defvar org-goto-start-pos) ; dynamically scoped parameter
6036 (defun org-goto (&optional alternative-interface)
6037 "Look up a different location in the current file, keeping current visibility.
6039 When you want look-up or go to a different location in a document, the
6040 fastest way is often to fold the entire buffer and then dive into the tree.
6041 This method has the disadvantage, that the previous location will be folded,
6042 which may not be what you want.
6044 This command works around this by showing a copy of the current buffer
6045 in an indirect buffer, in overview mode. You can dive into the tree in
6046 that copy, use org-occur and incremental search to find a location.
6047 When pressing RET or `Q', the command returns to the original buffer in
6048 which the visibility is still unchanged. After RET is will also jump to
6049 the location selected in the indirect buffer and expose the
6050 the headline hierarchy above."
6051 (interactive "P")
6052 (let* ((org-refile-targets '((nil . (:maxlevel . 10))))
6053 (org-refile-use-outline-path t)
6054 (interface
6055 (if (not alternative-interface)
6056 org-goto-interface
6057 (if (eq org-goto-interface 'outline)
6058 'outline-path-completion
6059 'outline)))
6060 (org-goto-start-pos (point))
6061 (selected-point
6062 (if (eq interface 'outline)
6063 (car (org-get-location (current-buffer) org-goto-help))
6064 (nth 3 (org-refile-get-location "Goto: ")))))
6065 (if selected-point
6066 (progn
6067 (org-mark-ring-push org-goto-start-pos)
6068 (goto-char selected-point)
6069 (if (or (org-invisible-p) (org-invisible-p2))
6070 (org-show-context 'org-goto)))
6071 (message "Quit"))))
6073 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
6074 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
6075 (defvar org-goto-local-auto-isearch-map) ; defined below
6077 (defun org-get-location (buf help)
6078 "Let the user select a location in the Org-mode buffer BUF.
6079 This function uses a recursive edit. It returns the selected position
6080 or nil."
6081 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
6082 (isearch-hide-immediately nil)
6083 (isearch-search-fun-function
6084 (lambda () 'org-goto-local-search-forward-headings))
6085 (org-goto-selected-point org-goto-exit-command))
6086 (save-excursion
6087 (save-window-excursion
6088 (delete-other-windows)
6089 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
6090 (switch-to-buffer
6091 (condition-case nil
6092 (make-indirect-buffer (current-buffer) "*org-goto*")
6093 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
6094 (with-output-to-temp-buffer "*Help*"
6095 (princ help))
6096 (shrink-window-if-larger-than-buffer (get-buffer-window "*Help*"))
6097 (setq buffer-read-only nil)
6098 (let ((org-startup-truncated t)
6099 (org-startup-folded nil)
6100 (org-startup-align-all-tables nil))
6101 (org-mode)
6102 (org-overview))
6103 (setq buffer-read-only t)
6104 (if (and (boundp 'org-goto-start-pos)
6105 (integer-or-marker-p org-goto-start-pos))
6106 (let ((org-show-hierarchy-above t)
6107 (org-show-siblings t)
6108 (org-show-following-heading t))
6109 (goto-char org-goto-start-pos)
6110 (and (org-invisible-p) (org-show-context)))
6111 (goto-char (point-min)))
6112 (org-beginning-of-line)
6113 (message "Select location and press RET")
6114 (use-local-map org-goto-map)
6115 (recursive-edit)
6117 (kill-buffer "*org-goto*")
6118 (cons org-goto-selected-point org-goto-exit-command)))
6120 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
6121 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
6122 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
6123 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
6125 (defun org-goto-local-search-forward-headings (string bound noerror)
6126 "Search and make sure that anu matches are in headlines."
6127 (catch 'return
6128 (while (search-forward string bound noerror)
6129 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
6130 (and (member :headline context)
6131 (not (member :tags context))))
6132 (throw 'return (point))))))
6134 (defun org-goto-local-auto-isearch ()
6135 "Start isearch."
6136 (interactive)
6137 (goto-char (point-min))
6138 (let ((keys (this-command-keys)))
6139 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
6140 (isearch-mode t)
6141 (isearch-process-search-char (string-to-char keys)))))
6143 (defun org-goto-ret (&optional arg)
6144 "Finish `org-goto' by going to the new location."
6145 (interactive "P")
6146 (setq org-goto-selected-point (point)
6147 org-goto-exit-command 'return)
6148 (throw 'exit nil))
6150 (defun org-goto-left ()
6151 "Finish `org-goto' by going to the new location."
6152 (interactive)
6153 (if (org-on-heading-p)
6154 (progn
6155 (beginning-of-line 1)
6156 (setq org-goto-selected-point (point)
6157 org-goto-exit-command 'left)
6158 (throw 'exit nil))
6159 (error "Not on a heading")))
6161 (defun org-goto-right ()
6162 "Finish `org-goto' by going to the new location."
6163 (interactive)
6164 (if (org-on-heading-p)
6165 (progn
6166 (setq org-goto-selected-point (point)
6167 org-goto-exit-command 'right)
6168 (throw 'exit nil))
6169 (error "Not on a heading")))
6171 (defun org-goto-quit ()
6172 "Finish `org-goto' without cursor motion."
6173 (interactive)
6174 (setq org-goto-selected-point nil)
6175 (setq org-goto-exit-command 'quit)
6176 (throw 'exit nil))
6178 ;;; Indirect buffer display of subtrees
6180 (defvar org-indirect-dedicated-frame nil
6181 "This is the frame being used for indirect tree display.")
6182 (defvar org-last-indirect-buffer nil)
6184 (defun org-tree-to-indirect-buffer (&optional arg)
6185 "Create indirect buffer and narrow it to current subtree.
6186 With numerical prefix ARG, go up to this level and then take that tree.
6187 If ARG is negative, go up that many levels.
6188 If `org-indirect-buffer-display' is not `new-frame', the command removes the
6189 indirect buffer previously made with this command, to avoid proliferation of
6190 indirect buffers. However, when you call the command with a `C-u' prefix, or
6191 when `org-indirect-buffer-display' is `new-frame', the last buffer
6192 is kept so that you can work with several indirect buffers at the same time.
6193 If `org-indirect-buffer-display' is `dedicated-frame', the C-u prefix also
6194 requests that a new frame be made for the new buffer, so that the dedicated
6195 frame is not changed."
6196 (interactive "P")
6197 (let ((cbuf (current-buffer))
6198 (cwin (selected-window))
6199 (pos (point))
6200 beg end level heading ibuf)
6201 (save-excursion
6202 (org-back-to-heading t)
6203 (when (numberp arg)
6204 (setq level (org-outline-level))
6205 (if (< arg 0) (setq arg (+ level arg)))
6206 (while (> (setq level (org-outline-level)) arg)
6207 (outline-up-heading 1 t)))
6208 (setq beg (point)
6209 heading (org-get-heading))
6210 (org-end-of-subtree t) (setq end (point)))
6211 (if (and (buffer-live-p org-last-indirect-buffer)
6212 (not (eq org-indirect-buffer-display 'new-frame))
6213 (not arg))
6214 (kill-buffer org-last-indirect-buffer))
6215 (setq ibuf (org-get-indirect-buffer cbuf)
6216 org-last-indirect-buffer ibuf)
6217 (cond
6218 ((or (eq org-indirect-buffer-display 'new-frame)
6219 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
6220 (select-frame (make-frame))
6221 (delete-other-windows)
6222 (switch-to-buffer ibuf)
6223 (org-set-frame-title heading))
6224 ((eq org-indirect-buffer-display 'dedicated-frame)
6225 (raise-frame
6226 (select-frame (or (and org-indirect-dedicated-frame
6227 (frame-live-p org-indirect-dedicated-frame)
6228 org-indirect-dedicated-frame)
6229 (setq org-indirect-dedicated-frame (make-frame)))))
6230 (delete-other-windows)
6231 (switch-to-buffer ibuf)
6232 (org-set-frame-title (concat "Indirect: " heading)))
6233 ((eq org-indirect-buffer-display 'current-window)
6234 (switch-to-buffer ibuf))
6235 ((eq org-indirect-buffer-display 'other-window)
6236 (pop-to-buffer ibuf))
6237 (t (error "Invalid value.")))
6238 (if (featurep 'xemacs)
6239 (save-excursion (org-mode) (turn-on-font-lock)))
6240 (narrow-to-region beg end)
6241 (show-all)
6242 (goto-char pos)
6243 (and (window-live-p cwin) (select-window cwin))))
6245 (defun org-get-indirect-buffer (&optional buffer)
6246 (setq buffer (or buffer (current-buffer)))
6247 (let ((n 1) (base (buffer-name buffer)) bname)
6248 (while (buffer-live-p
6249 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
6250 (setq n (1+ n)))
6251 (condition-case nil
6252 (make-indirect-buffer buffer bname 'clone)
6253 (error (make-indirect-buffer buffer bname)))))
6255 (defun org-set-frame-title (title)
6256 "Set the title of the current frame to the string TITLE."
6257 ;; FIXME: how to name a single frame in XEmacs???
6258 (unless (featurep 'xemacs)
6259 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
6261 ;;;; Structure editing
6263 ;;; Inserting headlines
6265 (defun org-insert-heading (&optional force-heading)
6266 "Insert a new heading or item with same depth at point.
6267 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
6268 If point is at the beginning of a headline, insert a sibling before the
6269 current headline. If point is not at the beginning, do not split the line,
6270 but create the new hedline after the current line."
6271 (interactive "P")
6272 (if (= (buffer-size) 0)
6273 (insert "\n* ")
6274 (when (or force-heading (not (org-insert-item)))
6275 (let* ((head (save-excursion
6276 (condition-case nil
6277 (progn
6278 (org-back-to-heading)
6279 (match-string 0))
6280 (error "*"))))
6281 (blank (cdr (assq 'heading org-blank-before-new-entry)))
6282 pos)
6283 (cond
6284 ((and (org-on-heading-p) (bolp)
6285 (or (bobp)
6286 (save-excursion (backward-char 1) (not (org-invisible-p)))))
6287 ;; insert before the current line
6288 (open-line (if blank 2 1)))
6289 ((and (bolp)
6290 (or (bobp)
6291 (save-excursion
6292 (backward-char 1) (not (org-invisible-p)))))
6293 ;; insert right here
6294 nil)
6296 ; ;; in the middle of the line
6297 ; (org-show-entry)
6298 ; (if (org-get-alist-option org-M-RET-may-split-line 'headline)
6299 ; (if (and
6300 ; (org-on-heading-p)
6301 ; (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \r\n]"))
6302 ; ;; protect the tags
6303 ;; (let ((tags (match-string 2)) pos)
6304 ; (delete-region (match-beginning 1) (match-end 1))
6305 ; (setq pos (point-at-bol))
6306 ; (newline (if blank 2 1))
6307 ; (save-excursion
6308 ; (goto-char pos)
6309 ; (end-of-line 1)
6310 ; (insert " " tags)
6311 ; (org-set-tags nil 'align)))
6312 ; (newline (if blank 2 1)))
6313 ; (newline (if blank 2 1))))
6316 ;; in the middle of the line
6317 (org-show-entry)
6318 (let ((split
6319 (org-get-alist-option org-M-RET-may-split-line 'headline))
6320 tags pos)
6321 (if (org-on-heading-p)
6322 (progn
6323 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
6324 (setq tags (and (match-end 2) (match-string 2)))
6325 (and (match-end 1)
6326 (delete-region (match-beginning 1) (match-end 1)))
6327 (setq pos (point-at-bol))
6328 (or split (end-of-line 1))
6329 (delete-horizontal-space)
6330 (newline (if blank 2 1))
6331 (when tags
6332 (save-excursion
6333 (goto-char pos)
6334 (end-of-line 1)
6335 (insert " " tags)
6336 (org-set-tags nil 'align))))
6337 (or split (end-of-line 1))
6338 (newline (if blank 2 1))))))
6339 (insert head) (just-one-space)
6340 (setq pos (point))
6341 (end-of-line 1)
6342 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
6343 (run-hooks 'org-insert-heading-hook)))))
6345 (defun org-insert-heading-after-current ()
6346 "Insert a new heading with same level as current, after current subtree."
6347 (interactive)
6348 (org-back-to-heading)
6349 (org-insert-heading)
6350 (org-move-subtree-down)
6351 (end-of-line 1))
6353 (defun org-insert-todo-heading (arg)
6354 "Insert a new heading with the same level and TODO state as current heading.
6355 If the heading has no TODO state, or if the state is DONE, use the first
6356 state (TODO by default). Also with prefix arg, force first state."
6357 (interactive "P")
6358 (when (not (org-insert-item 'checkbox))
6359 (org-insert-heading)
6360 (save-excursion
6361 (org-back-to-heading)
6362 (outline-previous-heading)
6363 (looking-at org-todo-line-regexp))
6364 (if (or arg
6365 (not (match-beginning 2))
6366 (member (match-string 2) org-done-keywords))
6367 (insert (car org-todo-keywords-1) " ")
6368 (insert (match-string 2) " "))))
6370 (defun org-insert-subheading (arg)
6371 "Insert a new subheading and demote it.
6372 Works for outline headings and for plain lists alike."
6373 (interactive "P")
6374 (org-insert-heading arg)
6375 (cond
6376 ((org-on-heading-p) (org-do-demote))
6377 ((org-at-item-p) (org-indent-item 1))))
6379 (defun org-insert-todo-subheading (arg)
6380 "Insert a new subheading with TODO keyword or checkbox and demote it.
6381 Works for outline headings and for plain lists alike."
6382 (interactive "P")
6383 (org-insert-todo-heading arg)
6384 (cond
6385 ((org-on-heading-p) (org-do-demote))
6386 ((org-at-item-p) (org-indent-item 1))))
6388 ;;; Promotion and Demotion
6390 (defun org-promote-subtree ()
6391 "Promote the entire subtree.
6392 See also `org-promote'."
6393 (interactive)
6394 (save-excursion
6395 (org-map-tree 'org-promote))
6396 (org-fix-position-after-promote))
6398 (defun org-demote-subtree ()
6399 "Demote the entire subtree. See `org-demote'.
6400 See also `org-promote'."
6401 (interactive)
6402 (save-excursion
6403 (org-map-tree 'org-demote))
6404 (org-fix-position-after-promote))
6407 (defun org-do-promote ()
6408 "Promote the current heading higher up the tree.
6409 If the region is active in `transient-mark-mode', promote all headings
6410 in the region."
6411 (interactive)
6412 (save-excursion
6413 (if (org-region-active-p)
6414 (org-map-region 'org-promote (region-beginning) (region-end))
6415 (org-promote)))
6416 (org-fix-position-after-promote))
6418 (defun org-do-demote ()
6419 "Demote the current heading lower down the tree.
6420 If the region is active in `transient-mark-mode', demote all headings
6421 in the region."
6422 (interactive)
6423 (save-excursion
6424 (if (org-region-active-p)
6425 (org-map-region 'org-demote (region-beginning) (region-end))
6426 (org-demote)))
6427 (org-fix-position-after-promote))
6429 (defun org-fix-position-after-promote ()
6430 "Make sure that after pro/demotion cursor position is right."
6431 (let ((pos (point)))
6432 (when (save-excursion
6433 (beginning-of-line 1)
6434 (looking-at org-todo-line-regexp)
6435 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
6436 (cond ((eobp) (insert " "))
6437 ((eolp) (insert " "))
6438 ((equal (char-after) ?\ ) (forward-char 1))))))
6440 (defun org-reduced-level (l)
6441 (if org-odd-levels-only (1+ (floor (/ l 2))) l))
6443 (defun org-get-legal-level (level &optional change)
6444 "Rectify a level change under the influence of `org-odd-levels-only'
6445 LEVEL is a current level, CHANGE is by how much the level should be
6446 modified. Even if CHANGE is nil, LEVEL may be returned modified because
6447 even level numbers will become the next higher odd number."
6448 (if org-odd-levels-only
6449 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
6450 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
6451 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
6452 (max 1 (+ level change))))
6454 (defun org-promote ()
6455 "Promote the current heading higher up the tree.
6456 If the region is active in `transient-mark-mode', promote all headings
6457 in the region."
6458 (org-back-to-heading t)
6459 (let* ((level (save-match-data (funcall outline-level)))
6460 (up-head (concat (make-string (org-get-legal-level level -1) ?*) " "))
6461 (diff (abs (- level (length up-head) -1))))
6462 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
6463 (replace-match up-head nil t)
6464 ;; Fixup tag positioning
6465 (and org-auto-align-tags (org-set-tags nil t))
6466 (if org-adapt-indentation (org-fixup-indentation (- diff)))))
6468 (defun org-demote ()
6469 "Demote the current heading lower down the tree.
6470 If the region is active in `transient-mark-mode', demote all headings
6471 in the region."
6472 (org-back-to-heading t)
6473 (let* ((level (save-match-data (funcall outline-level)))
6474 (down-head (concat (make-string (org-get-legal-level level 1) ?*) " "))
6475 (diff (abs (- level (length down-head) -1))))
6476 (replace-match down-head nil t)
6477 ;; Fixup tag positioning
6478 (and org-auto-align-tags (org-set-tags nil t))
6479 (if org-adapt-indentation (org-fixup-indentation diff))))
6481 (defun org-map-tree (fun)
6482 "Call FUN for every heading underneath the current one."
6483 (org-back-to-heading)
6484 (let ((level (funcall outline-level)))
6485 (save-excursion
6486 (funcall fun)
6487 (while (and (progn
6488 (outline-next-heading)
6489 (> (funcall outline-level) level))
6490 (not (eobp)))
6491 (funcall fun)))))
6493 (defun org-map-region (fun beg end)
6494 "Call FUN for every heading between BEG and END."
6495 (let ((org-ignore-region t))
6496 (save-excursion
6497 (setq end (copy-marker end))
6498 (goto-char beg)
6499 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
6500 (< (point) end))
6501 (funcall fun))
6502 (while (and (progn
6503 (outline-next-heading)
6504 (< (point) end))
6505 (not (eobp)))
6506 (funcall fun)))))
6508 (defun org-fixup-indentation (diff)
6509 "Change the indentation in the current entry by DIFF
6510 However, if any line in the current entry has no indentation, or if it
6511 would end up with no indentation after the change, nothing at all is done."
6512 (save-excursion
6513 (let ((end (save-excursion (outline-next-heading)
6514 (point-marker)))
6515 (prohibit (if (> diff 0)
6516 "^\\S-"
6517 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
6518 col)
6519 (unless (save-excursion (end-of-line 1)
6520 (re-search-forward prohibit end t))
6521 (while (and (< (point) end)
6522 (re-search-forward "^[ \t]+" end t))
6523 (goto-char (match-end 0))
6524 (setq col (current-column))
6525 (if (< diff 0) (replace-match ""))
6526 (indent-to (+ diff col))))
6527 (move-marker end nil))))
6529 (defun org-convert-to-odd-levels ()
6530 "Convert an org-mode file with all levels allowed to one with odd levels.
6531 This will leave level 1 alone, convert level 2 to level 3, level 3 to
6532 level 5 etc."
6533 (interactive)
6534 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
6535 (let ((org-odd-levels-only nil) n)
6536 (save-excursion
6537 (goto-char (point-min))
6538 (while (re-search-forward "^\\*\\*+ " nil t)
6539 (setq n (- (length (match-string 0)) 2))
6540 (while (>= (setq n (1- n)) 0)
6541 (org-demote))
6542 (end-of-line 1))))))
6545 (defun org-convert-to-oddeven-levels ()
6546 "Convert an org-mode file with only odd levels to one with odd and even levels.
6547 This promotes level 3 to level 2, level 5 to level 3 etc. If the file contains a
6548 section with an even level, conversion would destroy the structure of the file. An error
6549 is signaled in this case."
6550 (interactive)
6551 (goto-char (point-min))
6552 ;; First check if there are no even levels
6553 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
6554 (org-show-context t)
6555 (error "Not all levels are odd in this file. Conversion not possible."))
6556 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
6557 (let ((org-odd-levels-only nil) n)
6558 (save-excursion
6559 (goto-char (point-min))
6560 (while (re-search-forward "^\\*\\*+ " nil t)
6561 (setq n (/ (1- (length (match-string 0))) 2))
6562 (while (>= (setq n (1- n)) 0)
6563 (org-promote))
6564 (end-of-line 1))))))
6566 (defun org-tr-level (n)
6567 "Make N odd if required."
6568 (if org-odd-levels-only (1+ (/ n 2)) n))
6570 ;;; Vertical tree motion, cutting and pasting of subtrees
6572 (defun org-move-subtree-up (&optional arg)
6573 "Move the current subtree up past ARG headlines of the same level."
6574 (interactive "p")
6575 (org-move-subtree-down (- (prefix-numeric-value arg))))
6577 (defun org-move-subtree-down (&optional arg)
6578 "Move the current subtree down past ARG headlines of the same level."
6579 (interactive "p")
6580 (setq arg (prefix-numeric-value arg))
6581 (let ((movfunc (if (> arg 0) 'outline-get-next-sibling
6582 'outline-get-last-sibling))
6583 (ins-point (make-marker))
6584 (cnt (abs arg))
6585 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
6586 ;; Select the tree
6587 (org-back-to-heading)
6588 (setq beg0 (point))
6589 (save-excursion
6590 (setq ne-beg (org-back-over-empty-lines))
6591 (setq beg (point)))
6592 (save-match-data
6593 (save-excursion (outline-end-of-heading)
6594 (setq folded (org-invisible-p)))
6595 (outline-end-of-subtree))
6596 (outline-next-heading)
6597 (setq ne-end (org-back-over-empty-lines))
6598 (setq end (point))
6599 (goto-char beg0)
6600 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
6601 ;; include less whitespace
6602 (save-excursion
6603 (goto-char beg)
6604 (forward-line (- ne-beg ne-end))
6605 (setq beg (point))))
6606 ;; Find insertion point, with error handling
6607 (while (> cnt 0)
6608 (or (and (funcall movfunc) (looking-at outline-regexp))
6609 (progn (goto-char beg0)
6610 (error "Cannot move past superior level or buffer limit")))
6611 (setq cnt (1- cnt)))
6612 (if (> arg 0)
6613 ;; Moving forward - still need to move over subtree
6614 (progn (org-end-of-subtree t t)
6615 (save-excursion
6616 (org-back-over-empty-lines)
6617 (or (bolp) (newline)))))
6618 (setq ne-ins (org-back-over-empty-lines))
6619 (move-marker ins-point (point))
6620 (setq txt (buffer-substring beg end))
6621 (delete-region beg end)
6622 (outline-flag-region (1- beg) beg nil)
6623 (outline-flag-region (1- (point)) (point) nil)
6624 (insert txt)
6625 (or (bolp) (insert "\n"))
6626 (setq ins-end (point))
6627 (goto-char ins-point)
6628 (org-skip-whitespace)
6629 (when (and (< arg 0)
6630 (org-first-sibling-p)
6631 (> ne-ins ne-beg))
6632 ;; Move whitespace back to beginning
6633 (save-excursion
6634 (goto-char ins-end)
6635 (let ((kill-whole-line t))
6636 (kill-line (- ne-ins ne-beg)) (point)))
6637 (insert (make-string (- ne-ins ne-beg) ?\n)))
6638 (move-marker ins-point nil)
6639 (org-compact-display-after-subtree-move)
6640 (unless folded
6641 (org-show-entry)
6642 (show-children)
6643 (org-cycle-hide-drawers 'children))))
6645 (defvar org-subtree-clip ""
6646 "Clipboard for cut and paste of subtrees.
6647 This is actually only a copy of the kill, because we use the normal kill
6648 ring. We need it to check if the kill was created by `org-copy-subtree'.")
6650 (defvar org-subtree-clip-folded nil
6651 "Was the last copied subtree folded?
6652 This is used to fold the tree back after pasting.")
6654 (defun org-cut-subtree (&optional n)
6655 "Cut the current subtree into the clipboard.
6656 With prefix arg N, cut this many sequential subtrees.
6657 This is a short-hand for marking the subtree and then cutting it."
6658 (interactive "p")
6659 (org-copy-subtree n 'cut))
6661 (defun org-copy-subtree (&optional n cut)
6662 "Cut the current subtree into the clipboard.
6663 With prefix arg N, cut this many sequential subtrees.
6664 This is a short-hand for marking the subtree and then copying it.
6665 If CUT is non-nil, actually cut the subtree."
6666 (interactive "p")
6667 (let (beg end folded (beg0 (point)))
6668 (if (interactive-p)
6669 (org-back-to-heading nil) ; take what looks like a subtree
6670 (org-back-to-heading t)) ; take what is really there
6671 (org-back-over-empty-lines)
6672 (setq beg (point))
6673 (skip-chars-forward " \t\r\n")
6674 (save-match-data
6675 (save-excursion (outline-end-of-heading)
6676 (setq folded (org-invisible-p)))
6677 (condition-case nil
6678 (outline-forward-same-level (1- n))
6679 (error nil))
6680 (org-end-of-subtree t t))
6681 (org-back-over-empty-lines)
6682 (setq end (point))
6683 (goto-char beg0)
6684 (when (> end beg)
6685 (setq org-subtree-clip-folded folded)
6686 (if cut (kill-region beg end) (copy-region-as-kill beg end))
6687 (setq org-subtree-clip (current-kill 0))
6688 (message "%s: Subtree(s) with %d characters"
6689 (if cut "Cut" "Copied")
6690 (length org-subtree-clip)))))
6692 (defun org-paste-subtree (&optional level tree)
6693 "Paste the clipboard as a subtree, with modification of headline level.
6694 The entire subtree is promoted or demoted in order to match a new headline
6695 level. By default, the new level is derived from the visible headings
6696 before and after the insertion point, and taken to be the inferior headline
6697 level of the two. So if the previous visible heading is level 3 and the
6698 next is level 4 (or vice versa), level 4 will be used for insertion.
6699 This makes sure that the subtree remains an independent subtree and does
6700 not swallow low level entries.
6702 You can also force a different level, either by using a numeric prefix
6703 argument, or by inserting the heading marker by hand. For example, if the
6704 cursor is after \"*****\", then the tree will be shifted to level 5.
6706 If you want to insert the tree as is, just use \\[yank].
6708 If optional TREE is given, use this text instead of the kill ring."
6709 (interactive "P")
6710 (unless (org-kill-is-subtree-p tree)
6711 (error "%s"
6712 (substitute-command-keys
6713 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
6714 (let* ((txt (or tree (and kill-ring (current-kill 0))))
6715 (^re (concat "^\\(" outline-regexp "\\)"))
6716 (re (concat "\\(" outline-regexp "\\)"))
6717 (^re_ (concat "\\(\\*+\\)[ \t]*"))
6719 (old-level (if (string-match ^re txt)
6720 (- (match-end 0) (match-beginning 0) 1)
6721 -1))
6722 (force-level (cond (level (prefix-numeric-value level))
6723 ((string-match
6724 ^re_ (buffer-substring (point-at-bol) (point)))
6725 (- (match-end 1) (match-beginning 1)))
6726 (t nil)))
6727 (previous-level (save-excursion
6728 (condition-case nil
6729 (progn
6730 (outline-previous-visible-heading 1)
6731 (if (looking-at re)
6732 (- (match-end 0) (match-beginning 0) 1)
6734 (error 1))))
6735 (next-level (save-excursion
6736 (condition-case nil
6737 (progn
6738 (or (looking-at outline-regexp)
6739 (outline-next-visible-heading 1))
6740 (if (looking-at re)
6741 (- (match-end 0) (match-beginning 0) 1)
6743 (error 1))))
6744 (new-level (or force-level (max previous-level next-level)))
6745 (shift (if (or (= old-level -1)
6746 (= new-level -1)
6747 (= old-level new-level))
6749 (- new-level old-level)))
6750 (delta (if (> shift 0) -1 1))
6751 (func (if (> shift 0) 'org-demote 'org-promote))
6752 (org-odd-levels-only nil)
6753 beg end)
6754 ;; Remove the forced level indicator
6755 (if force-level
6756 (delete-region (point-at-bol) (point)))
6757 ;; Paste
6758 (beginning-of-line 1)
6759 (org-back-over-empty-lines) ;; FIXME: correct fix????
6760 (setq beg (point))
6761 (insert-before-markers txt) ;; FIXME: correct fix????
6762 (unless (string-match "\n\\'" txt) (insert "\n"))
6763 (setq end (point))
6764 (goto-char beg)
6765 (skip-chars-forward " \t\n\r")
6766 (setq beg (point))
6767 ;; Shift if necessary
6768 (unless (= shift 0)
6769 (save-restriction
6770 (narrow-to-region beg end)
6771 (while (not (= shift 0))
6772 (org-map-region func (point-min) (point-max))
6773 (setq shift (+ delta shift)))
6774 (goto-char (point-min))))
6775 (when (interactive-p)
6776 (message "Clipboard pasted as level %d subtree" new-level))
6777 (if (and kill-ring
6778 (eq org-subtree-clip (current-kill 0))
6779 org-subtree-clip-folded)
6780 ;; The tree was folded before it was killed/copied
6781 (hide-subtree))))
6783 (defun org-kill-is-subtree-p (&optional txt)
6784 "Check if the current kill is an outline subtree, or a set of trees.
6785 Returns nil if kill does not start with a headline, or if the first
6786 headline level is not the largest headline level in the tree.
6787 So this will actually accept several entries of equal levels as well,
6788 which is OK for `org-paste-subtree'.
6789 If optional TXT is given, check this string instead of the current kill."
6790 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
6791 (start-level (and kill
6792 (string-match (concat "\\`\\([ \t\n\r]*?\n\\)?\\("
6793 org-outline-regexp "\\)")
6794 kill)
6795 (- (match-end 2) (match-beginning 2) 1)))
6796 (re (concat "^" org-outline-regexp))
6797 (start (1+ (match-beginning 2))))
6798 (if (not start-level)
6799 (progn
6800 nil) ;; does not even start with a heading
6801 (catch 'exit
6802 (while (setq start (string-match re kill (1+ start)))
6803 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
6804 (throw 'exit nil)))
6805 t))))
6807 (defun org-narrow-to-subtree ()
6808 "Narrow buffer to the current subtree."
6809 (interactive)
6810 (save-excursion
6811 (save-match-data
6812 (narrow-to-region
6813 (progn (org-back-to-heading) (point))
6814 (progn (org-end-of-subtree t t) (point))))))
6817 ;;; Outline Sorting
6819 (defun org-sort (with-case)
6820 "Call `org-sort-entries-or-items' or `org-table-sort-lines'.
6821 Optional argument WITH-CASE means sort case-sensitively."
6822 (interactive "P")
6823 (if (org-at-table-p)
6824 (org-call-with-arg 'org-table-sort-lines with-case)
6825 (org-call-with-arg 'org-sort-entries-or-items with-case)))
6827 (defvar org-priority-regexp) ; defined later in the file
6829 (defun org-sort-entries-or-items (&optional with-case sorting-type getkey-func property)
6830 "Sort entries on a certain level of an outline tree.
6831 If there is an active region, the entries in the region are sorted.
6832 Else, if the cursor is before the first entry, sort the top-level items.
6833 Else, the children of the entry at point are sorted.
6835 Sorting can be alphabetically, numerically, and by date/time as given by
6836 the first time stamp in the entry. The command prompts for the sorting
6837 type unless it has been given to the function through the SORTING-TYPE
6838 argument, which needs to a character, any of (?n ?N ?a ?A ?t ?T ?p ?P ?f ?F).
6839 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
6840 called with point at the beginning of the record. It must return either
6841 a string or a number that should serve as the sorting key for that record.
6843 Comparing entries ignores case by default. However, with an optional argument
6844 WITH-CASE, the sorting considers case as well."
6845 (interactive "P")
6846 (let ((case-func (if with-case 'identity 'downcase))
6847 start beg end stars re re2
6848 txt what tmp plain-list-p)
6849 ;; Find beginning and end of region to sort
6850 (cond
6851 ((org-region-active-p)
6852 ;; we will sort the region
6853 (setq end (region-end)
6854 what "region")
6855 (goto-char (region-beginning))
6856 (if (not (org-on-heading-p)) (outline-next-heading))
6857 (setq start (point)))
6858 ((org-at-item-p)
6859 ;; we will sort this plain list
6860 (org-beginning-of-item-list) (setq start (point))
6861 (org-end-of-item-list) (setq end (point))
6862 (goto-char start)
6863 (setq plain-list-p t
6864 what "plain list"))
6865 ((or (org-on-heading-p)
6866 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
6867 ;; we will sort the children of the current headline
6868 (org-back-to-heading)
6869 (setq start (point)
6870 end (progn (org-end-of-subtree t t)
6871 (org-back-over-empty-lines)
6872 (point))
6873 what "children")
6874 (goto-char start)
6875 (show-subtree)
6876 (outline-next-heading))
6878 ;; we will sort the top-level entries in this file
6879 (goto-char (point-min))
6880 (or (org-on-heading-p) (outline-next-heading))
6881 (setq start (point) end (point-max) what "top-level")
6882 (goto-char start)
6883 (show-all)))
6885 (setq beg (point))
6886 (if (>= beg end) (error "Nothing to sort"))
6888 (unless plain-list-p
6889 (looking-at "\\(\\*+\\)")
6890 (setq stars (match-string 1)
6891 re (concat "^" (regexp-quote stars) " +")
6892 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[^*]")
6893 txt (buffer-substring beg end))
6894 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
6895 (if (and (not (equal stars "*")) (string-match re2 txt))
6896 (error "Region to sort contains a level above the first entry")))
6898 (unless sorting-type
6899 (message
6900 (if plain-list-p
6901 "Sort %s: [a]lpha [n]umeric [t]ime [f]unc A/N/T/F means reversed:"
6902 "Sort %s: [a]lpha [n]umeric [t]ime [p]riority p[r]operty [f]unc A/N/T/P/F means reversed:")
6903 what)
6904 (setq sorting-type (read-char-exclusive))
6906 (and (= (downcase sorting-type) ?f)
6907 (setq getkey-func
6908 (completing-read "Sort using function: "
6909 obarray 'fboundp t nil nil))
6910 (setq getkey-func (intern getkey-func)))
6912 (and (= (downcase sorting-type) ?r)
6913 (setq property
6914 (completing-read "Property: "
6915 (mapcar 'list (org-buffer-property-keys t))
6916 nil t))))
6918 (message "Sorting entries...")
6920 (save-restriction
6921 (narrow-to-region start end)
6923 (let ((dcst (downcase sorting-type))
6924 (now (current-time)))
6925 (sort-subr
6926 (/= dcst sorting-type)
6927 ;; This function moves to the beginning character of the "record" to
6928 ;; be sorted.
6929 (if plain-list-p
6930 (lambda nil
6931 (if (org-at-item-p) t (goto-char (point-max))))
6932 (lambda nil
6933 (if (re-search-forward re nil t)
6934 (goto-char (match-beginning 0))
6935 (goto-char (point-max)))))
6936 ;; This function moves to the last character of the "record" being
6937 ;; sorted.
6938 (if plain-list-p
6939 'org-end-of-item
6940 (lambda nil
6941 (save-match-data
6942 (condition-case nil
6943 (outline-forward-same-level 1)
6944 (error
6945 (goto-char (point-max)))))))
6947 ;; This function returns the value that gets sorted against.
6948 (if plain-list-p
6949 (lambda nil
6950 (when (looking-at "[ \t]*[-+*0-9.)]+[ \t]+")
6951 (cond
6952 ((= dcst ?n)
6953 (string-to-number (buffer-substring (match-end 0)
6954 (point-at-eol))))
6955 ((= dcst ?a)
6956 (buffer-substring (match-end 0) (point-at-eol)))
6957 ((= dcst ?t)
6958 (if (re-search-forward org-ts-regexp
6959 (point-at-eol) t)
6960 (org-time-string-to-time (match-string 0))
6961 now))
6962 ((= dcst ?f)
6963 (if getkey-func
6964 (progn
6965 (setq tmp (funcall getkey-func))
6966 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
6967 tmp)
6968 (error "Invalid key function `%s'" getkey-func)))
6969 (t (error "Invalid sorting type `%c'" sorting-type)))))
6970 (lambda nil
6971 (cond
6972 ((= dcst ?n)
6973 (if (looking-at outline-regexp)
6974 (string-to-number (buffer-substring (match-end 0)
6975 (point-at-eol)))
6976 nil))
6977 ((= dcst ?a)
6978 (funcall case-func (buffer-substring (point-at-bol)
6979 (point-at-eol))))
6980 ((= dcst ?t)
6981 (if (re-search-forward org-ts-regexp
6982 (save-excursion
6983 (forward-line 2)
6984 (point)) t)
6985 (org-time-string-to-time (match-string 0))
6986 now))
6987 ((= dcst ?p)
6988 (if (re-search-forward org-priority-regexp (point-at-eol) t)
6989 (string-to-char (match-string 2))
6990 org-default-priority))
6991 ((= dcst ?r)
6992 (or (org-entry-get nil property) ""))
6993 ((= dcst ?f)
6994 (if getkey-func
6995 (progn
6996 (setq tmp (funcall getkey-func))
6997 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
6998 tmp)
6999 (error "Invalid key function `%s'" getkey-func)))
7000 (t (error "Invalid sorting type `%c'" sorting-type)))))
7002 (cond
7003 ((= dcst ?a) 'string<)
7004 ((= dcst ?t) 'time-less-p)
7005 (t nil)))))
7006 (message "Sorting entries...done")))
7008 (defun org-do-sort (table what &optional with-case sorting-type)
7009 "Sort TABLE of WHAT according to SORTING-TYPE.
7010 The user will be prompted for the SORTING-TYPE if the call to this
7011 function does not specify it. WHAT is only for the prompt, to indicate
7012 what is being sorted. The sorting key will be extracted from
7013 the car of the elements of the table.
7014 If WITH-CASE is non-nil, the sorting will be case-sensitive."
7015 (unless sorting-type
7016 (message
7017 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
7018 what)
7019 (setq sorting-type (read-char-exclusive)))
7020 (let ((dcst (downcase sorting-type))
7021 extractfun comparefun)
7022 ;; Define the appropriate functions
7023 (cond
7024 ((= dcst ?n)
7025 (setq extractfun 'string-to-number
7026 comparefun (if (= dcst sorting-type) '< '>)))
7027 ((= dcst ?a)
7028 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
7029 (lambda(x) (downcase (org-sort-remove-invisible x))))
7030 comparefun (if (= dcst sorting-type)
7031 'string<
7032 (lambda (a b) (and (not (string< a b))
7033 (not (string= a b)))))))
7034 ((= dcst ?t)
7035 (setq extractfun
7036 (lambda (x)
7037 (if (string-match org-ts-regexp x)
7038 (time-to-seconds
7039 (org-time-string-to-time (match-string 0 x)))
7041 comparefun (if (= dcst sorting-type) '< '>)))
7042 (t (error "Invalid sorting type `%c'" sorting-type)))
7044 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
7045 table)
7046 (lambda (a b) (funcall comparefun (car a) (car b))))))
7048 ;;;; Plain list items, including checkboxes
7050 ;;; Plain list items
7052 (defun org-at-item-p ()
7053 "Is point in a line starting a hand-formatted item?"
7054 (let ((llt org-plain-list-ordered-item-terminator))
7055 (save-excursion
7056 (goto-char (point-at-bol))
7057 (looking-at
7058 (cond
7059 ((eq llt t) "\\([ \t]*\\([-+]\\|\\([0-9]+[.)]\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
7060 ((= llt ?.) "\\([ \t]*\\([-+]\\|\\([0-9]+\\.\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
7061 ((= llt ?\)) "\\([ \t]*\\([-+]\\|\\([0-9]+))\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
7062 (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))))))
7064 (defun org-in-item-p ()
7065 "It the cursor inside a plain list item.
7066 Does not have to be the first line."
7067 (save-excursion
7068 (condition-case nil
7069 (progn
7070 (org-beginning-of-item)
7071 (org-at-item-p)
7073 (error nil))))
7075 (defun org-insert-item (&optional checkbox)
7076 "Insert a new item at the current level.
7077 Return t when things worked, nil when we are not in an item."
7078 (when (save-excursion
7079 (condition-case nil
7080 (progn
7081 (org-beginning-of-item)
7082 (org-at-item-p)
7083 (if (org-invisible-p) (error "Invisible item"))
7085 (error nil)))
7086 (let* ((bul (match-string 0))
7087 (eow (save-excursion (beginning-of-line 1) (looking-at "[ \t]*")
7088 (match-end 0)))
7089 (blank (cdr (assq 'plain-list-item org-blank-before-new-entry)))
7090 pos)
7091 (cond
7092 ((and (org-at-item-p) (<= (point) eow))
7093 ;; before the bullet
7094 (beginning-of-line 1)
7095 (open-line (if blank 2 1)))
7096 ((<= (point) eow)
7097 (beginning-of-line 1))
7099 (unless (org-get-alist-option org-M-RET-may-split-line 'item)
7100 (end-of-line 1)
7101 (delete-horizontal-space))
7102 (newline (if blank 2 1))))
7103 (insert bul (if checkbox "[ ]" ""))
7104 (just-one-space)
7105 (setq pos (point))
7106 (end-of-line 1)
7107 (unless (= (point) pos) (just-one-space) (backward-delete-char 1)))
7108 (org-maybe-renumber-ordered-list)
7109 (and checkbox (org-update-checkbox-count-maybe))
7112 ;;; Checkboxes
7114 (defun org-at-item-checkbox-p ()
7115 "Is point at a line starting a plain-list item with a checklet?"
7116 (and (org-at-item-p)
7117 (save-excursion
7118 (goto-char (match-end 0))
7119 (skip-chars-forward " \t")
7120 (looking-at "\\[[- X]\\]"))))
7122 (defun org-toggle-checkbox (&optional arg)
7123 "Toggle the checkbox in the current line."
7124 (interactive "P")
7125 (catch 'exit
7126 (let (beg end status (firstnew 'unknown))
7127 (cond
7128 ((org-region-active-p)
7129 (setq beg (region-beginning) end (region-end)))
7130 ((org-on-heading-p)
7131 (setq beg (point) end (save-excursion (outline-next-heading) (point))))
7132 ((org-at-item-checkbox-p)
7133 (let ((pos (point)))
7134 (replace-match
7135 (cond (arg "[-]")
7136 ((member (match-string 0) '("[ ]" "[-]")) "[X]")
7137 (t "[ ]"))
7138 t t)
7139 (goto-char pos))
7140 (throw 'exit t))
7141 (t (error "Not at a checkbox or heading, and no active region")))
7142 (save-excursion
7143 (goto-char beg)
7144 (while (< (point) end)
7145 (when (org-at-item-checkbox-p)
7146 (setq status (equal (match-string 0) "[X]"))
7147 (when (eq firstnew 'unknown)
7148 (setq firstnew (not status)))
7149 (replace-match
7150 (if (if arg (not status) firstnew) "[X]" "[ ]") t t))
7151 (beginning-of-line 2)))))
7152 (org-update-checkbox-count-maybe))
7154 (defun org-update-checkbox-count-maybe ()
7155 "Update checkbox statistics unless turned off by user."
7156 (when org-provide-checkbox-statistics
7157 (org-update-checkbox-count)))
7159 (defun org-update-checkbox-count (&optional all)
7160 "Update the checkbox statistics in the current section.
7161 This will find all statistic cookies like [57%] and [6/12] and update them
7162 with the current numbers. With optional prefix argument ALL, do this for
7163 the whole buffer."
7164 (interactive "P")
7165 (save-excursion
7166 (let* ((buffer-invisibility-spec (org-inhibit-invisibility)) ; Emacs 21
7167 (beg (condition-case nil
7168 (progn (outline-back-to-heading) (point))
7169 (error (point-min))))
7170 (end (move-marker (make-marker)
7171 (progn (outline-next-heading) (point))))
7172 (re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
7173 (re-box "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)")
7174 (re-find (concat re "\\|" re-box))
7175 beg-cookie end-cookie is-percent c-on c-off lim
7176 eline curr-ind next-ind continue-from startsearch
7177 (cstat 0)
7179 (when all
7180 (goto-char (point-min))
7181 (outline-next-heading)
7182 (setq beg (point) end (point-max)))
7183 (goto-char end)
7184 ;; find each statistic cookie
7185 (while (re-search-backward re-find beg t)
7186 (setq beg-cookie (match-beginning 1)
7187 end-cookie (match-end 1)
7188 cstat (+ cstat (if end-cookie 1 0))
7189 startsearch (point-at-eol)
7190 continue-from (point-at-bol)
7191 is-percent (match-beginning 2)
7192 lim (cond
7193 ((org-on-heading-p) (outline-next-heading) (point))
7194 ((org-at-item-p) (org-end-of-item) (point))
7195 (t nil))
7196 c-on 0
7197 c-off 0)
7198 (when lim
7199 ;; find first checkbox for this cookie and gather
7200 ;; statistics from all that are at this indentation level
7201 (goto-char startsearch)
7202 (if (re-search-forward re-box lim t)
7203 (progn
7204 (org-beginning-of-item)
7205 (setq curr-ind (org-get-indentation))
7206 (setq next-ind curr-ind)
7207 (while (= curr-ind next-ind)
7208 (save-excursion (end-of-line) (setq eline (point)))
7209 (if (re-search-forward re-box eline t)
7210 (if (member (match-string 2) '("[ ]" "[-]"))
7211 (setq c-off (1+ c-off))
7212 (setq c-on (1+ c-on))
7215 (org-end-of-item)
7216 (setq next-ind (org-get-indentation))
7218 (goto-char continue-from)
7219 ;; update cookie
7220 (when end-cookie
7221 (delete-region beg-cookie end-cookie)
7222 (goto-char beg-cookie)
7223 (insert
7224 (if is-percent
7225 (format "[%d%%]" (/ (* 100 c-on) (max 1 (+ c-on c-off))))
7226 (format "[%d/%d]" c-on (+ c-on c-off)))))
7227 ;; update items checkbox if it has one
7228 (when (org-at-item-p)
7229 (org-beginning-of-item)
7230 (when (and (> (+ c-on c-off) 0)
7231 (re-search-forward re-box (point-at-eol) t))
7232 (setq beg-cookie (match-beginning 2)
7233 end-cookie (match-end 2))
7234 (delete-region beg-cookie end-cookie)
7235 (goto-char beg-cookie)
7236 (cond ((= c-off 0) (insert "[X]"))
7237 ((= c-on 0) (insert "[ ]"))
7238 (t (insert "[-]")))
7240 (goto-char continue-from))
7241 (when (interactive-p)
7242 (message "Checkbox satistics updated %s (%d places)"
7243 (if all "in entire file" "in current outline entry") cstat)))))
7245 (defun org-get-checkbox-statistics-face ()
7246 "Select the face for checkbox statistics.
7247 The face will be `org-done' when all relevant boxes are checked. Otherwise
7248 it will be `org-todo'."
7249 (if (match-end 1)
7250 (if (equal (match-string 1) "100%") 'org-done 'org-todo)
7251 (if (and (> (match-end 2) (match-beginning 2))
7252 (equal (match-string 2) (match-string 3)))
7253 'org-done
7254 'org-todo)))
7256 (defun org-get-indentation (&optional line)
7257 "Get the indentation of the current line, interpreting tabs.
7258 When LINE is given, assume it represents a line and compute its indentation."
7259 (if line
7260 (if (string-match "^ *" (org-remove-tabs line))
7261 (match-end 0))
7262 (save-excursion
7263 (beginning-of-line 1)
7264 (skip-chars-forward " \t")
7265 (current-column))))
7267 (defun org-remove-tabs (s &optional width)
7268 "Replace tabulators in S with spaces.
7269 Assumes that s is a single line, starting in column 0."
7270 (setq width (or width tab-width))
7271 (while (string-match "\t" s)
7272 (setq s (replace-match
7273 (make-string
7274 (- (* width (/ (+ (match-beginning 0) width) width))
7275 (match-beginning 0)) ?\ )
7276 t t s)))
7279 (defun org-fix-indentation (line ind)
7280 "Fix indentation in LINE.
7281 IND is a cons cell with target and minimum indentation.
7282 If the current indenation in LINE is smaller than the minimum,
7283 leave it alone. If it is larger than ind, set it to the target."
7284 (let* ((l (org-remove-tabs line))
7285 (i (org-get-indentation l))
7286 (i1 (car ind)) (i2 (cdr ind)))
7287 (if (>= i i2) (setq l (substring line i2)))
7288 (if (> i1 0)
7289 (concat (make-string i1 ?\ ) l)
7290 l)))
7292 (defcustom org-empty-line-terminates-plain-lists nil
7293 "Non-nil means, an empty line ends all plain list levels.
7294 When nil, empty lines are part of the preceeding item."
7295 :group 'org-plain-lists
7296 :type 'boolean)
7298 (defun org-beginning-of-item ()
7299 "Go to the beginning of the current hand-formatted item.
7300 If the cursor is not in an item, throw an error."
7301 (interactive)
7302 (let ((pos (point))
7303 (limit (save-excursion
7304 (condition-case nil
7305 (progn
7306 (org-back-to-heading)
7307 (beginning-of-line 2) (point))
7308 (error (point-min)))))
7309 (ind-empty (if org-empty-line-terminates-plain-lists 0 10000))
7310 ind ind1)
7311 (if (org-at-item-p)
7312 (beginning-of-line 1)
7313 (beginning-of-line 1)
7314 (skip-chars-forward " \t")
7315 (setq ind (current-column))
7316 (if (catch 'exit
7317 (while t
7318 (beginning-of-line 0)
7319 (if (or (bobp) (< (point) limit)) (throw 'exit nil))
7321 (if (looking-at "[ \t]*$")
7322 (setq ind1 ind-empty)
7323 (skip-chars-forward " \t")
7324 (setq ind1 (current-column)))
7325 (if (< ind1 ind)
7326 (progn (beginning-of-line 1) (throw 'exit (org-at-item-p))))))
7328 (goto-char pos)
7329 (error "Not in an item")))))
7331 (defun org-end-of-item ()
7332 "Go to the end of the current hand-formatted item.
7333 If the cursor is not in an item, throw an error."
7334 (interactive)
7335 (let* ((pos (point))
7336 ind1
7337 (ind-empty (if org-empty-line-terminates-plain-lists 0 10000))
7338 (limit (save-excursion (outline-next-heading) (point)))
7339 (ind (save-excursion
7340 (org-beginning-of-item)
7341 (skip-chars-forward " \t")
7342 (current-column)))
7343 (end (catch 'exit
7344 (while t
7345 (beginning-of-line 2)
7346 (if (eobp) (throw 'exit (point)))
7347 (if (>= (point) limit) (throw 'exit (point-at-bol)))
7348 (if (looking-at "[ \t]*$")
7349 (setq ind1 ind-empty)
7350 (skip-chars-forward " \t")
7351 (setq ind1 (current-column)))
7352 (if (<= ind1 ind)
7353 (throw 'exit (point-at-bol)))))))
7354 (if end
7355 (goto-char end)
7356 (goto-char pos)
7357 (error "Not in an item"))))
7359 (defun org-next-item ()
7360 "Move to the beginning of the next item in the current plain list.
7361 Error if not at a plain list, or if this is the last item in the list."
7362 (interactive)
7363 (let (ind ind1 (pos (point)))
7364 (org-beginning-of-item)
7365 (setq ind (org-get-indentation))
7366 (org-end-of-item)
7367 (setq ind1 (org-get-indentation))
7368 (unless (and (org-at-item-p) (= ind ind1))
7369 (goto-char pos)
7370 (error "On last item"))))
7372 (defun org-previous-item ()
7373 "Move to the beginning of the previous item in the current plain list.
7374 Error if not at a plain list, or if this is the first item in the list."
7375 (interactive)
7376 (let (beg ind ind1 (pos (point)))
7377 (org-beginning-of-item)
7378 (setq beg (point))
7379 (setq ind (org-get-indentation))
7380 (goto-char beg)
7381 (catch 'exit
7382 (while t
7383 (beginning-of-line 0)
7384 (if (looking-at "[ \t]*$")
7386 (if (<= (setq ind1 (org-get-indentation)) ind)
7387 (throw 'exit t)))))
7388 (condition-case nil
7389 (if (or (not (org-at-item-p))
7390 (< ind1 (1- ind)))
7391 (error "")
7392 (org-beginning-of-item))
7393 (error (goto-char pos)
7394 (error "On first item")))))
7396 (defun org-first-list-item-p ()
7397 "Is this heading the item in a plain list?"
7398 (unless (org-at-item-p)
7399 (error "Not at a plain list item"))
7400 (org-beginning-of-item)
7401 (= (point) (save-excursion (org-beginning-of-item-list))))
7403 (defun org-move-item-down ()
7404 "Move the plain list item at point down, i.e. swap with following item.
7405 Subitems (items with larger indentation) are considered part of the item,
7406 so this really moves item trees."
7407 (interactive)
7408 (let (beg beg0 end end0 ind ind1 (pos (point)) txt ne-end ne-beg)
7409 (org-beginning-of-item)
7410 (setq beg0 (point))
7411 (save-excursion
7412 (setq ne-beg (org-back-over-empty-lines))
7413 (setq beg (point)))
7414 (goto-char beg0)
7415 (setq ind (org-get-indentation))
7416 (org-end-of-item)
7417 (setq end0 (point))
7418 (setq ind1 (org-get-indentation))
7419 (setq ne-end (org-back-over-empty-lines))
7420 (setq end (point))
7421 (goto-char beg0)
7422 (when (and (org-first-list-item-p) (< ne-end ne-beg))
7423 ;; include less whitespace
7424 (save-excursion
7425 (goto-char beg)
7426 (forward-line (- ne-beg ne-end))
7427 (setq beg (point))))
7428 (goto-char end0)
7429 (if (and (org-at-item-p) (= ind ind1))
7430 (progn
7431 (org-end-of-item)
7432 (org-back-over-empty-lines)
7433 (setq txt (buffer-substring beg end))
7434 (save-excursion
7435 (delete-region beg end))
7436 (setq pos (point))
7437 (insert txt)
7438 (goto-char pos) (org-skip-whitespace)
7439 (org-maybe-renumber-ordered-list))
7440 (goto-char pos)
7441 (error "Cannot move this item further down"))))
7443 (defun org-move-item-up (arg)
7444 "Move the plain list item at point up, i.e. swap with previous item.
7445 Subitems (items with larger indentation) are considered part of the item,
7446 so this really moves item trees."
7447 (interactive "p")
7448 (let (beg beg0 end ind ind1 (pos (point)) txt
7449 ne-beg ne-ins ins-end)
7450 (org-beginning-of-item)
7451 (setq beg0 (point))
7452 (setq ind (org-get-indentation))
7453 (save-excursion
7454 (setq ne-beg (org-back-over-empty-lines))
7455 (setq beg (point)))
7456 (goto-char beg0)
7457 (org-end-of-item)
7458 (setq end (point))
7459 (goto-char beg0)
7460 (catch 'exit
7461 (while t
7462 (beginning-of-line 0)
7463 (if (looking-at "[ \t]*$")
7464 (if org-empty-line-terminates-plain-lists
7465 (progn
7466 (goto-char pos)
7467 (error "Cannot move this item further up"))
7468 nil)
7469 (if (<= (setq ind1 (org-get-indentation)) ind)
7470 (throw 'exit t)))))
7471 (condition-case nil
7472 (org-beginning-of-item)
7473 (error (goto-char beg)
7474 (error "Cannot move this item further up")))
7475 (setq ind1 (org-get-indentation))
7476 (if (and (org-at-item-p) (= ind ind1))
7477 (progn
7478 (setq ne-ins (org-back-over-empty-lines))
7479 (setq txt (buffer-substring beg end))
7480 (save-excursion
7481 (delete-region beg end))
7482 (setq pos (point))
7483 (insert txt)
7484 (setq ins-end (point))
7485 (goto-char pos) (org-skip-whitespace)
7487 (when (and (org-first-list-item-p) (> ne-ins ne-beg))
7488 ;; Move whitespace back to beginning
7489 (save-excursion
7490 (goto-char ins-end)
7491 (let ((kill-whole-line t))
7492 (kill-line (- ne-ins ne-beg)) (point)))
7493 (insert (make-string (- ne-ins ne-beg) ?\n)))
7495 (org-maybe-renumber-ordered-list))
7496 (goto-char pos)
7497 (error "Cannot move this item further up"))))
7499 (defun org-maybe-renumber-ordered-list ()
7500 "Renumber the ordered list at point if setup allows it.
7501 This tests the user option `org-auto-renumber-ordered-lists' before
7502 doing the renumbering."
7503 (interactive)
7504 (when (and org-auto-renumber-ordered-lists
7505 (org-at-item-p))
7506 (if (match-beginning 3)
7507 (org-renumber-ordered-list 1)
7508 (org-fix-bullet-type))))
7510 (defun org-maybe-renumber-ordered-list-safe ()
7511 (condition-case nil
7512 (save-excursion
7513 (org-maybe-renumber-ordered-list))
7514 (error nil)))
7516 (defun org-cycle-list-bullet (&optional which)
7517 "Cycle through the different itemize/enumerate bullets.
7518 This cycle the entire list level through the sequence:
7520 `-' -> `+' -> `*' -> `1.' -> `1)'
7522 If WHICH is a string, use that as the new bullet. If WHICH is an integer,
7523 0 meand `-', 1 means `+' etc."
7524 (interactive "P")
7525 (org-preserve-lc
7526 (org-beginning-of-item-list)
7527 (org-at-item-p)
7528 (beginning-of-line 1)
7529 (let ((current (match-string 0))
7530 (prevp (eq which 'previous))
7531 new)
7532 (setq new (cond
7533 ((and (numberp which)
7534 (nth (1- which) '("-" "+" "*" "1." "1)"))))
7535 ((string-match "-" current) (if prevp "1)" "+"))
7536 ((string-match "\\+" current)
7537 (if prevp "-" (if (looking-at "\\S-") "1." "*")))
7538 ((string-match "\\*" current) (if prevp "+" "1."))
7539 ((string-match "\\." current) (if prevp "*" "1)"))
7540 ((string-match ")" current) (if prevp "1." "-"))
7541 (t (error "This should not happen"))))
7542 (and (looking-at "\\([ \t]*\\)\\S-+") (replace-match (concat "\\1" new)))
7543 (org-fix-bullet-type)
7544 (org-maybe-renumber-ordered-list))))
7546 (defun org-get-string-indentation (s)
7547 "What indentation has S due to SPACE and TAB at the beginning of the string?"
7548 (let ((n -1) (i 0) (w tab-width) c)
7549 (catch 'exit
7550 (while (< (setq n (1+ n)) (length s))
7551 (setq c (aref s n))
7552 (cond ((= c ?\ ) (setq i (1+ i)))
7553 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
7554 (t (throw 'exit t)))))
7557 (defun org-renumber-ordered-list (arg)
7558 "Renumber an ordered plain list.
7559 Cursor needs to be in the first line of an item, the line that starts
7560 with something like \"1.\" or \"2)\"."
7561 (interactive "p")
7562 (unless (and (org-at-item-p)
7563 (match-beginning 3))
7564 (error "This is not an ordered list"))
7565 (let ((line (org-current-line))
7566 (col (current-column))
7567 (ind (org-get-string-indentation
7568 (buffer-substring (point-at-bol) (match-beginning 3))))
7569 ;; (term (substring (match-string 3) -1))
7570 ind1 (n (1- arg))
7571 fmt)
7572 ;; find where this list begins
7573 (org-beginning-of-item-list)
7574 (looking-at "[ \t]*[0-9]+\\([.)]\\)")
7575 (setq fmt (concat "%d" (match-string 1)))
7576 (beginning-of-line 0)
7577 ;; walk forward and replace these numbers
7578 (catch 'exit
7579 (while t
7580 (catch 'next
7581 (beginning-of-line 2)
7582 (if (eobp) (throw 'exit nil))
7583 (if (looking-at "[ \t]*$") (throw 'next nil))
7584 (skip-chars-forward " \t") (setq ind1 (current-column))
7585 (if (> ind1 ind) (throw 'next t))
7586 (if (< ind1 ind) (throw 'exit t))
7587 (if (not (org-at-item-p)) (throw 'exit nil))
7588 (delete-region (match-beginning 2) (match-end 2))
7589 (goto-char (match-beginning 2))
7590 (insert (format fmt (setq n (1+ n)))))))
7591 (goto-line line)
7592 (move-to-column col)))
7594 (defun org-fix-bullet-type ()
7595 "Make sure all items in this list have the same bullet as the firsst item."
7596 (interactive)
7597 (unless (org-at-item-p) (error "This is not a list"))
7598 (let ((line (org-current-line))
7599 (col (current-column))
7600 (ind (current-indentation))
7601 ind1 bullet)
7602 ;; find where this list begins
7603 (org-beginning-of-item-list)
7604 (beginning-of-line 1)
7605 ;; find out what the bullet type is
7606 (looking-at "[ \t]*\\(\\S-+\\)")
7607 (setq bullet (match-string 1))
7608 ;; walk forward and replace these numbers
7609 (beginning-of-line 0)
7610 (catch 'exit
7611 (while t
7612 (catch 'next
7613 (beginning-of-line 2)
7614 (if (eobp) (throw 'exit nil))
7615 (if (looking-at "[ \t]*$") (throw 'next nil))
7616 (skip-chars-forward " \t") (setq ind1 (current-column))
7617 (if (> ind1 ind) (throw 'next t))
7618 (if (< ind1 ind) (throw 'exit t))
7619 (if (not (org-at-item-p)) (throw 'exit nil))
7620 (skip-chars-forward " \t")
7621 (looking-at "\\S-+")
7622 (replace-match bullet))))
7623 (goto-line line)
7624 (move-to-column col)
7625 (if (string-match "[0-9]" bullet)
7626 (org-renumber-ordered-list 1))))
7628 (defun org-beginning-of-item-list ()
7629 "Go to the beginning of the current item list.
7630 I.e. to the first item in this list."
7631 (interactive)
7632 (org-beginning-of-item)
7633 (let ((pos (point-at-bol))
7634 (ind (org-get-indentation))
7635 ind1)
7636 ;; find where this list begins
7637 (catch 'exit
7638 (while t
7639 (catch 'next
7640 (beginning-of-line 0)
7641 (if (looking-at "[ \t]*$")
7642 (throw (if (bobp) 'exit 'next) t))
7643 (skip-chars-forward " \t") (setq ind1 (current-column))
7644 (if (or (< ind1 ind)
7645 (and (= ind1 ind)
7646 (not (org-at-item-p)))
7647 (bobp))
7648 (throw 'exit t)
7649 (when (org-at-item-p) (setq pos (point-at-bol)))))))
7650 (goto-char pos)))
7653 (defun org-end-of-item-list ()
7654 "Go to the end of the current item list.
7655 I.e. to the text after the last item."
7656 (interactive)
7657 (org-beginning-of-item)
7658 (let ((pos (point-at-bol))
7659 (ind (org-get-indentation))
7660 ind1)
7661 ;; find where this list begins
7662 (catch 'exit
7663 (while t
7664 (catch 'next
7665 (beginning-of-line 2)
7666 (if (looking-at "[ \t]*$")
7667 (throw (if (eobp) 'exit 'next) t))
7668 (skip-chars-forward " \t") (setq ind1 (current-column))
7669 (if (or (< ind1 ind)
7670 (and (= ind1 ind)
7671 (not (org-at-item-p)))
7672 (eobp))
7673 (progn
7674 (setq pos (point-at-bol))
7675 (throw 'exit t))))))
7676 (goto-char pos)))
7679 (defvar org-last-indent-begin-marker (make-marker))
7680 (defvar org-last-indent-end-marker (make-marker))
7682 (defun org-outdent-item (arg)
7683 "Outdent a local list item."
7684 (interactive "p")
7685 (org-indent-item (- arg)))
7687 (defun org-indent-item (arg)
7688 "Indent a local list item."
7689 (interactive "p")
7690 (unless (org-at-item-p)
7691 (error "Not on an item"))
7692 (save-excursion
7693 (let (beg end ind ind1 tmp delta ind-down ind-up)
7694 (if (memq last-command '(org-shiftmetaright org-shiftmetaleft))
7695 (setq beg org-last-indent-begin-marker
7696 end org-last-indent-end-marker)
7697 (org-beginning-of-item)
7698 (setq beg (move-marker org-last-indent-begin-marker (point)))
7699 (org-end-of-item)
7700 (setq end (move-marker org-last-indent-end-marker (point))))
7701 (goto-char beg)
7702 (setq tmp (org-item-indent-positions)
7703 ind (car tmp)
7704 ind-down (nth 2 tmp)
7705 ind-up (nth 1 tmp)
7706 delta (if (> arg 0)
7707 (if ind-down (- ind-down ind) 2)
7708 (if ind-up (- ind-up ind) -2)))
7709 (if (< (+ delta ind) 0) (error "Cannot outdent beyond margin"))
7710 (while (< (point) end)
7711 (beginning-of-line 1)
7712 (skip-chars-forward " \t") (setq ind1 (current-column))
7713 (delete-region (point-at-bol) (point))
7714 (or (eolp) (indent-to-column (+ ind1 delta)))
7715 (beginning-of-line 2))))
7716 (org-fix-bullet-type)
7717 (org-maybe-renumber-ordered-list-safe)
7718 (save-excursion
7719 (beginning-of-line 0)
7720 (condition-case nil (org-beginning-of-item) (error nil))
7721 (org-maybe-renumber-ordered-list-safe)))
7723 (defun org-item-indent-positions ()
7724 "Return indentation for plain list items.
7725 This returns a list with three values: The current indentation, the
7726 parent indentation and the indentation a child should habe.
7727 Assumes cursor in item line."
7728 (let* ((bolpos (point-at-bol))
7729 (ind (org-get-indentation))
7730 ind-down ind-up pos)
7731 (save-excursion
7732 (org-beginning-of-item-list)
7733 (skip-chars-backward "\n\r \t")
7734 (when (org-in-item-p)
7735 (org-beginning-of-item)
7736 (setq ind-up (org-get-indentation))))
7737 (setq pos (point))
7738 (save-excursion
7739 (cond
7740 ((and (condition-case nil (progn (org-previous-item) t)
7741 (error nil))
7742 (or (forward-char 1) t)
7743 (re-search-forward "^\\([ \t]*\\([-+]\\|\\([0-9]+[.)]\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)" bolpos t))
7744 (setq ind-down (org-get-indentation)))
7745 ((and (goto-char pos)
7746 (org-at-item-p))
7747 (goto-char (match-end 0))
7748 (skip-chars-forward " \t")
7749 (setq ind-down (current-column)))))
7750 (list ind ind-up ind-down)))
7752 ;;; The orgstruct minor mode
7754 ;; Define a minor mode which can be used in other modes in order to
7755 ;; integrate the org-mode structure editing commands.
7757 ;; This is really a hack, because the org-mode structure commands use
7758 ;; keys which normally belong to the major mode. Here is how it
7759 ;; works: The minor mode defines all the keys necessary to operate the
7760 ;; structure commands, but wraps the commands into a function which
7761 ;; tests if the cursor is currently at a headline or a plain list
7762 ;; item. If that is the case, the structure command is used,
7763 ;; temporarily setting many Org-mode variables like regular
7764 ;; expressions for filling etc. However, when any of those keys is
7765 ;; used at a different location, function uses `key-binding' to look
7766 ;; up if the key has an associated command in another currently active
7767 ;; keymap (minor modes, major mode, global), and executes that
7768 ;; command. There might be problems if any of the keys is otherwise
7769 ;; used as a prefix key.
7771 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
7772 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
7773 ;; addresses this by checking explicitly for both bindings.
7775 (defvar orgstruct-mode-map (make-sparse-keymap)
7776 "Keymap for the minor `orgstruct-mode'.")
7778 (defvar org-local-vars nil
7779 "List of local variables, for use by `orgstruct-mode'")
7781 ;;;###autoload
7782 (define-minor-mode orgstruct-mode
7783 "Toggle the minor more `orgstruct-mode'.
7784 This mode is for using Org-mode structure commands in other modes.
7785 The following key behave as if Org-mode was active, if the cursor
7786 is on a headline, or on a plain list item (both in the definition
7787 of Org-mode).
7789 M-up Move entry/item up
7790 M-down Move entry/item down
7791 M-left Promote
7792 M-right Demote
7793 M-S-up Move entry/item up
7794 M-S-down Move entry/item down
7795 M-S-left Promote subtree
7796 M-S-right Demote subtree
7797 M-q Fill paragraph and items like in Org-mode
7798 C-c ^ Sort entries
7799 C-c - Cycle list bullet
7800 TAB Cycle item visibility
7801 M-RET Insert new heading/item
7802 S-M-RET Insert new TODO heading / Chekbox item
7803 C-c C-c Set tags / toggle checkbox"
7804 nil " OrgStruct" nil
7805 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
7807 ;;;###autoload
7808 (defun turn-on-orgstruct ()
7809 "Unconditionally turn on `orgstruct-mode'."
7810 (orgstruct-mode 1))
7812 ;;;###autoload
7813 (defun turn-on-orgstruct++ ()
7814 "Unconditionally turn on `orgstruct-mode', and force org-mode indentations.
7815 In addition to setting orgstruct-mode, this also exports all indentation and
7816 autofilling variables from org-mode into the buffer. Note that turning
7817 off orgstruct-mode will *not* remove these additional settings."
7818 (orgstruct-mode 1)
7819 (let (var val)
7820 (mapc
7821 (lambda (x)
7822 (when (string-match
7823 "^\\(paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
7824 (symbol-name (car x)))
7825 (setq var (car x) val (nth 1 x))
7826 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
7827 org-local-vars)))
7829 (defun orgstruct-error ()
7830 "Error when there is no default binding for a structure key."
7831 (interactive)
7832 (error "This key has no function outside structure elements"))
7834 (defun orgstruct-setup ()
7835 "Setup orgstruct keymaps."
7836 (let ((nfunc 0)
7837 (bindings
7838 (list
7839 '([(meta up)] org-metaup)
7840 '([(meta down)] org-metadown)
7841 '([(meta left)] org-metaleft)
7842 '([(meta right)] org-metaright)
7843 '([(meta shift up)] org-shiftmetaup)
7844 '([(meta shift down)] org-shiftmetadown)
7845 '([(meta shift left)] org-shiftmetaleft)
7846 '([(meta shift right)] org-shiftmetaright)
7847 '([(shift up)] org-shiftup)
7848 '([(shift down)] org-shiftdown)
7849 '("\C-c\C-c" org-ctrl-c-ctrl-c)
7850 '("\M-q" fill-paragraph)
7851 '("\C-c^" org-sort)
7852 '("\C-c-" org-cycle-list-bullet)))
7853 elt key fun cmd)
7854 (while (setq elt (pop bindings))
7855 (setq nfunc (1+ nfunc))
7856 (setq key (org-key (car elt))
7857 fun (nth 1 elt)
7858 cmd (orgstruct-make-binding fun nfunc key))
7859 (org-defkey orgstruct-mode-map key cmd))
7861 ;; Special treatment needed for TAB and RET
7862 (org-defkey orgstruct-mode-map [(tab)]
7863 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
7864 (org-defkey orgstruct-mode-map "\C-i"
7865 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
7867 (org-defkey orgstruct-mode-map "\M-\C-m"
7868 (orgstruct-make-binding 'org-insert-heading 105
7869 "\M-\C-m" [(meta return)]))
7870 (org-defkey orgstruct-mode-map [(meta return)]
7871 (orgstruct-make-binding 'org-insert-heading 106
7872 [(meta return)] "\M-\C-m"))
7874 (org-defkey orgstruct-mode-map [(shift meta return)]
7875 (orgstruct-make-binding 'org-insert-todo-heading 107
7876 [(meta return)] "\M-\C-m"))
7878 (unless org-local-vars
7879 (setq org-local-vars (org-get-local-variables)))
7883 (defun orgstruct-make-binding (fun n &rest keys)
7884 "Create a function for binding in the structure minor mode.
7885 FUN is the command to call inside a table. N is used to create a unique
7886 command name. KEYS are keys that should be checked in for a command
7887 to execute outside of tables."
7888 (eval
7889 (list 'defun
7890 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
7891 '(arg)
7892 (concat "In Structure, run `" (symbol-name fun) "'.\n"
7893 "Outside of structure, run the binding of `"
7894 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
7895 "'.")
7896 '(interactive "p")
7897 (list 'if
7898 '(org-context-p 'headline 'item)
7899 (list 'org-run-like-in-org-mode (list 'quote fun))
7900 (list 'let '(orgstruct-mode)
7901 (list 'call-interactively
7902 (append '(or)
7903 (mapcar (lambda (k)
7904 (list 'key-binding k))
7905 keys)
7906 '('orgstruct-error))))))))
7908 (defun org-context-p (&rest contexts)
7909 "Check if local context is and of CONTEXTS.
7910 Possible values in the list of contexts are `table', `headline', and `item'."
7911 (let ((pos (point)))
7912 (goto-char (point-at-bol))
7913 (prog1 (or (and (memq 'table contexts)
7914 (looking-at "[ \t]*|"))
7915 (and (memq 'headline contexts)
7916 (looking-at "\\*+"))
7917 (and (memq 'item contexts)
7918 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)")))
7919 (goto-char pos))))
7921 (defun org-get-local-variables ()
7922 "Return a list of all local variables in an org-mode buffer."
7923 (let (varlist)
7924 (with-current-buffer (get-buffer-create "*Org tmp*")
7925 (erase-buffer)
7926 (org-mode)
7927 (setq varlist (buffer-local-variables)))
7928 (kill-buffer "*Org tmp*")
7929 (delq nil
7930 (mapcar
7931 (lambda (x)
7932 (setq x
7933 (if (symbolp x)
7934 (list x)
7935 (list (car x) (list 'quote (cdr x)))))
7936 (if (string-match
7937 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
7938 (symbol-name (car x)))
7939 x nil))
7940 varlist))))
7942 ;;;###autoload
7943 (defun org-run-like-in-org-mode (cmd)
7944 (unless org-local-vars
7945 (setq org-local-vars (org-get-local-variables)))
7946 (eval (list 'let org-local-vars
7947 (list 'call-interactively (list 'quote cmd)))))
7949 ;;;; Archiving
7951 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
7953 (defun org-archive-subtree (&optional find-done)
7954 "Move the current subtree to the archive.
7955 The archive can be a certain top-level heading in the current file, or in
7956 a different file. The tree will be moved to that location, the subtree
7957 heading be marked DONE, and the current time will be added.
7959 When called with prefix argument FIND-DONE, find whole trees without any
7960 open TODO items and archive them (after getting confirmation from the user).
7961 If the cursor is not at a headline when this comand is called, try all level
7962 1 trees. If the cursor is on a headline, only try the direct children of
7963 this heading."
7964 (interactive "P")
7965 (if find-done
7966 (org-archive-all-done)
7967 ;; Save all relevant TODO keyword-relatex variables
7969 (let ((tr-org-todo-line-regexp org-todo-line-regexp) ; keep despite compiler
7970 (tr-org-todo-keywords-1 org-todo-keywords-1)
7971 (tr-org-todo-kwd-alist org-todo-kwd-alist)
7972 (tr-org-done-keywords org-done-keywords)
7973 (tr-org-todo-regexp org-todo-regexp)
7974 (tr-org-todo-line-regexp org-todo-line-regexp)
7975 (tr-org-odd-levels-only org-odd-levels-only)
7976 (this-buffer (current-buffer))
7977 (org-archive-location org-archive-location)
7978 (re "^#\\+ARCHIVE:[ \t]+\\(\\S-.*\\S-\\)[ \t]*$")
7979 ;; start of variables that will be used for saving context
7980 ;; The compiler complains about them - keep them anyway!
7981 (file (abbreviate-file-name (buffer-file-name)))
7982 (olpath (mapconcat 'identity (org-get-outline-path) "/"))
7983 (time (format-time-string
7984 (substring (cdr org-time-stamp-formats) 1 -1)
7985 (current-time)))
7986 afile heading buffer level newfile-p
7987 category todo priority
7988 ;; start of variables that will be used for savind context
7989 ltags itags prop)
7991 ;; Try to find a local archive location
7992 (save-excursion
7993 (save-restriction
7994 (widen)
7995 (setq prop (org-entry-get nil "ARCHIVE" 'inherit))
7996 (if (and prop (string-match "\\S-" prop))
7997 (setq org-archive-location prop)
7998 (if (or (re-search-backward re nil t)
7999 (re-search-forward re nil t))
8000 (setq org-archive-location (match-string 1))))))
8002 (if (string-match "\\(.*\\)::\\(.*\\)" org-archive-location)
8003 (progn
8004 (setq afile (format (match-string 1 org-archive-location)
8005 (file-name-nondirectory buffer-file-name))
8006 heading (match-string 2 org-archive-location)))
8007 (error "Invalid `org-archive-location'"))
8008 (if (> (length afile) 0)
8009 (setq newfile-p (not (file-exists-p afile))
8010 buffer (find-file-noselect afile))
8011 (setq buffer (current-buffer)))
8012 (unless buffer
8013 (error "Cannot access file \"%s\"" afile))
8014 (if (and (> (length heading) 0)
8015 (string-match "^\\*+" heading))
8016 (setq level (match-end 0))
8017 (setq heading nil level 0))
8018 (save-excursion
8019 (org-back-to-heading t)
8020 ;; Get context information that will be lost by moving the tree
8021 (org-refresh-category-properties)
8022 (setq category (org-get-category)
8023 todo (and (looking-at org-todo-line-regexp)
8024 (match-string 2))
8025 priority (org-get-priority (if (match-end 3) (match-string 3) ""))
8026 ltags (org-get-tags)
8027 itags (org-delete-all ltags (org-get-tags-at)))
8028 (setq ltags (mapconcat 'identity ltags " ")
8029 itags (mapconcat 'identity itags " "))
8030 ;; We first only copy, in case something goes wrong
8031 ;; we need to protect this-command, to avoid kill-region sets it,
8032 ;; which would lead to duplication of subtrees
8033 (let (this-command) (org-copy-subtree))
8034 (set-buffer buffer)
8035 ;; Enforce org-mode for the archive buffer
8036 (if (not (org-mode-p))
8037 ;; Force the mode for future visits.
8038 (let ((org-insert-mode-line-in-empty-file t)
8039 (org-inhibit-startup t))
8040 (call-interactively 'org-mode)))
8041 (when newfile-p
8042 (goto-char (point-max))
8043 (insert (format "\nArchived entries from file %s\n\n"
8044 (buffer-file-name this-buffer))))
8045 ;; Force the TODO keywords of the original buffer
8046 (let ((org-todo-line-regexp tr-org-todo-line-regexp)
8047 (org-todo-keywords-1 tr-org-todo-keywords-1)
8048 (org-todo-kwd-alist tr-org-todo-kwd-alist)
8049 (org-done-keywords tr-org-done-keywords)
8050 (org-todo-regexp tr-org-todo-regexp)
8051 (org-todo-line-regexp tr-org-todo-line-regexp)
8052 (org-odd-levels-only
8053 (if (local-variable-p 'org-odd-levels-only (current-buffer))
8054 org-odd-levels-only
8055 tr-org-odd-levels-only)))
8056 (goto-char (point-min))
8057 (if heading
8058 (progn
8059 (if (re-search-forward
8060 (concat "^" (regexp-quote heading)
8061 (org-re "[ \t]*\\(:[[:alnum:]_@:]+:\\)?[ \t]*\\($\\|\r\\)"))
8062 nil t)
8063 (goto-char (match-end 0))
8064 ;; Heading not found, just insert it at the end
8065 (goto-char (point-max))
8066 (or (bolp) (insert "\n"))
8067 (insert "\n" heading "\n")
8068 (end-of-line 0))
8069 ;; Make the subtree visible
8070 (show-subtree)
8071 (org-end-of-subtree t)
8072 (skip-chars-backward " \t\r\n")
8073 (and (looking-at "[ \t\r\n]*")
8074 (replace-match "\n\n")))
8075 ;; No specific heading, just go to end of file.
8076 (goto-char (point-max)) (insert "\n"))
8077 ;; Paste
8078 (org-paste-subtree (org-get-legal-level level 1))
8080 ;; Mark the entry as done
8081 (when (and org-archive-mark-done
8082 (looking-at org-todo-line-regexp)
8083 (or (not (match-end 2))
8084 (not (member (match-string 2) org-done-keywords))))
8085 (let (org-log-done org-todo-log-states)
8086 (org-todo
8087 (car (or (member org-archive-mark-done org-done-keywords)
8088 org-done-keywords)))))
8090 ;; Add the context info
8091 (when org-archive-save-context-info
8092 (let ((l org-archive-save-context-info) e n v)
8093 (while (setq e (pop l))
8094 (when (and (setq v (symbol-value e))
8095 (stringp v) (string-match "\\S-" v))
8096 (setq n (concat "ARCHIVE_" (upcase (symbol-name e))))
8097 (org-entry-put (point) n v)))))
8099 ;; Save the buffer, if it is not the same buffer.
8100 (if (not (eq this-buffer buffer)) (save-buffer))))
8101 ;; Here we are back in the original buffer. Everything seems to have
8102 ;; worked. So now cut the tree and finish up.
8103 (let (this-command) (org-cut-subtree))
8104 (if (and (not (eobp)) (looking-at "[ \t]*$")) (kill-line))
8105 (message "Subtree archived %s"
8106 (if (eq this-buffer buffer)
8107 (concat "under heading: " heading)
8108 (concat "in file: " (abbreviate-file-name afile)))))))
8110 (defun org-refresh-category-properties ()
8111 "Refresh category text properties in teh buffer."
8112 (let ((def-cat (cond
8113 ((null org-category)
8114 (if buffer-file-name
8115 (file-name-sans-extension
8116 (file-name-nondirectory buffer-file-name))
8117 "???"))
8118 ((symbolp org-category) (symbol-name org-category))
8119 (t org-category)))
8120 beg end cat pos optionp)
8121 (org-unmodified
8122 (save-excursion
8123 (save-restriction
8124 (widen)
8125 (goto-char (point-min))
8126 (put-text-property (point) (point-max) 'org-category def-cat)
8127 (while (re-search-forward
8128 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
8129 (setq pos (match-end 0)
8130 optionp (equal (char-after (match-beginning 0)) ?#)
8131 cat (org-trim (match-string 2)))
8132 (if optionp
8133 (setq beg (point-at-bol) end (point-max))
8134 (org-back-to-heading t)
8135 (setq beg (point) end (org-end-of-subtree t t)))
8136 (put-text-property beg end 'org-category cat)
8137 (goto-char pos)))))))
8139 (defun org-archive-all-done (&optional tag)
8140 "Archive sublevels of the current tree without open TODO items.
8141 If the cursor is not on a headline, try all level 1 trees. If
8142 it is on a headline, try all direct children.
8143 When TAG is non-nil, don't move trees, but mark them with the ARCHIVE tag."
8144 (let ((re (concat "^\\*+ +" org-not-done-regexp)) re1
8145 (rea (concat ".*:" org-archive-tag ":"))
8146 (begm (make-marker))
8147 (endm (make-marker))
8148 (question (if tag "Set ARCHIVE tag (no open TODO items)? "
8149 "Move subtree to archive (no open TODO items)? "))
8150 beg end (cntarch 0))
8151 (if (org-on-heading-p)
8152 (progn
8153 (setq re1 (concat "^" (regexp-quote
8154 (make-string
8155 (1+ (- (match-end 0) (match-beginning 0) 1))
8156 ?*))
8157 " "))
8158 (move-marker begm (point))
8159 (move-marker endm (org-end-of-subtree t)))
8160 (setq re1 "^* ")
8161 (move-marker begm (point-min))
8162 (move-marker endm (point-max)))
8163 (save-excursion
8164 (goto-char begm)
8165 (while (re-search-forward re1 endm t)
8166 (setq beg (match-beginning 0)
8167 end (save-excursion (org-end-of-subtree t) (point)))
8168 (goto-char beg)
8169 (if (re-search-forward re end t)
8170 (goto-char end)
8171 (goto-char beg)
8172 (if (and (or (not tag) (not (looking-at rea)))
8173 (y-or-n-p question))
8174 (progn
8175 (if tag
8176 (org-toggle-tag org-archive-tag 'on)
8177 (org-archive-subtree))
8178 (setq cntarch (1+ cntarch)))
8179 (goto-char end)))))
8180 (message "%d trees archived" cntarch)))
8182 (defun org-cycle-hide-drawers (state)
8183 "Re-hide all drawers after a visibility state change."
8184 (when (and (org-mode-p)
8185 (not (memq state '(overview folded))))
8186 (save-excursion
8187 (let* ((globalp (memq state '(contents all)))
8188 (beg (if globalp (point-min) (point)))
8189 (end (if globalp (point-max) (org-end-of-subtree t))))
8190 (goto-char beg)
8191 (while (re-search-forward org-drawer-regexp end t)
8192 (org-flag-drawer t))))))
8194 (defun org-flag-drawer (flag)
8195 (save-excursion
8196 (beginning-of-line 1)
8197 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
8198 (let ((b (match-end 0))
8199 (outline-regexp org-outline-regexp))
8200 (if (re-search-forward
8201 "^[ \t]*:END:"
8202 (save-excursion (outline-next-heading) (point)) t)
8203 (outline-flag-region b (point-at-eol) flag)
8204 (error ":END: line missing"))))))
8206 (defun org-cycle-hide-archived-subtrees (state)
8207 "Re-hide all archived subtrees after a visibility state change."
8208 (when (and (not org-cycle-open-archived-trees)
8209 (not (memq state '(overview folded))))
8210 (save-excursion
8211 (let* ((globalp (memq state '(contents all)))
8212 (beg (if globalp (point-min) (point)))
8213 (end (if globalp (point-max) (org-end-of-subtree t))))
8214 (org-hide-archived-subtrees beg end)
8215 (goto-char beg)
8216 (if (looking-at (concat ".*:" org-archive-tag ":"))
8217 (message "%s" (substitute-command-keys
8218 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
8220 (defun org-force-cycle-archived ()
8221 "Cycle subtree even if it is archived."
8222 (interactive)
8223 (setq this-command 'org-cycle)
8224 (let ((org-cycle-open-archived-trees t))
8225 (call-interactively 'org-cycle)))
8227 (defun org-hide-archived-subtrees (beg end)
8228 "Re-hide all archived subtrees after a visibility state change."
8229 (save-excursion
8230 (let* ((re (concat ":" org-archive-tag ":")))
8231 (goto-char beg)
8232 (while (re-search-forward re end t)
8233 (and (org-on-heading-p) (hide-subtree))
8234 (org-end-of-subtree t)))))
8236 (defun org-toggle-tag (tag &optional onoff)
8237 "Toggle the tag TAG for the current line.
8238 If ONOFF is `on' or `off', don't toggle but set to this state."
8239 (unless (org-on-heading-p t) (error "Not on headling"))
8240 (let (res current)
8241 (save-excursion
8242 (beginning-of-line)
8243 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t]*$")
8244 (point-at-eol) t)
8245 (progn
8246 (setq current (match-string 1))
8247 (replace-match ""))
8248 (setq current ""))
8249 (setq current (nreverse (org-split-string current ":")))
8250 (cond
8251 ((eq onoff 'on)
8252 (setq res t)
8253 (or (member tag current) (push tag current)))
8254 ((eq onoff 'off)
8255 (or (not (member tag current)) (setq current (delete tag current))))
8256 (t (if (member tag current)
8257 (setq current (delete tag current))
8258 (setq res t)
8259 (push tag current))))
8260 (end-of-line 1)
8261 (if current
8262 (progn
8263 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
8264 (org-set-tags nil t))
8265 (delete-horizontal-space))
8266 (run-hooks 'org-after-tags-change-hook))
8267 res))
8269 (defun org-toggle-archive-tag (&optional arg)
8270 "Toggle the archive tag for the current headline.
8271 With prefix ARG, check all children of current headline and offer tagging
8272 the children that do not contain any open TODO items."
8273 (interactive "P")
8274 (if arg
8275 (org-archive-all-done 'tag)
8276 (let (set)
8277 (save-excursion
8278 (org-back-to-heading t)
8279 (setq set (org-toggle-tag org-archive-tag))
8280 (when set (hide-subtree)))
8281 (and set (beginning-of-line 1))
8282 (message "Subtree %s" (if set "archived" "unarchived")))))
8285 ;;;; Tables
8287 ;;; The table editor
8289 ;; Watch out: Here we are talking about two different kind of tables.
8290 ;; Most of the code is for the tables created with the Org-mode table editor.
8291 ;; Sometimes, we talk about tables created and edited with the table.el
8292 ;; Emacs package. We call the former org-type tables, and the latter
8293 ;; table.el-type tables.
8295 (defun org-before-change-function (beg end)
8296 "Every change indicates that a table might need an update."
8297 (setq org-table-may-need-update t))
8299 (defconst org-table-line-regexp "^[ \t]*|"
8300 "Detects an org-type table line.")
8301 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
8302 "Detects an org-type table line.")
8303 (defconst org-table-auto-recalculate-regexp "^[ \t]*| *# *\\(|\\|$\\)"
8304 "Detects a table line marked for automatic recalculation.")
8305 (defconst org-table-recalculate-regexp "^[ \t]*| *[#*] *\\(|\\|$\\)"
8306 "Detects a table line marked for automatic recalculation.")
8307 (defconst org-table-calculate-mark-regexp "^[ \t]*| *[!$^_#*] *\\(|\\|$\\)"
8308 "Detects a table line marked for automatic recalculation.")
8309 (defconst org-table-hline-regexp "^[ \t]*|-"
8310 "Detects an org-type table hline.")
8311 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
8312 "Detects a table-type table hline.")
8313 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
8314 "Detects an org-type or table-type table.")
8315 (defconst org-table-border-regexp "^[ \t]*[^| \t]"
8316 "Searching from within a table (any type) this finds the first line
8317 outside the table.")
8318 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
8319 "Searching from within a table (any type) this finds the first line
8320 outside the table.")
8322 (defvar org-table-last-highlighted-reference nil)
8323 (defvar org-table-formula-history nil)
8325 (defvar org-table-column-names nil
8326 "Alist with column names, derived from the `!' line.")
8327 (defvar org-table-column-name-regexp nil
8328 "Regular expression matching the current column names.")
8329 (defvar org-table-local-parameters nil
8330 "Alist with parameter names, derived from the `$' line.")
8331 (defvar org-table-named-field-locations nil
8332 "Alist with locations of named fields.")
8334 (defvar org-table-current-line-types nil
8335 "Table row types, non-nil only for the duration of a comand.")
8336 (defvar org-table-current-begin-line nil
8337 "Table begin line, non-nil only for the duration of a comand.")
8338 (defvar org-table-current-begin-pos nil
8339 "Table begin position, non-nil only for the duration of a comand.")
8340 (defvar org-table-dlines nil
8341 "Vector of data line line numbers in the current table.")
8342 (defvar org-table-hlines nil
8343 "Vector of hline line numbers in the current table.")
8345 (defconst org-table-range-regexp
8346 "@\\([-+]?I*[-+]?[0-9]*\\)?\\(\\$[-+]?[0-9]+\\)?\\(\\.\\.@?\\([-+]?I*[-+]?[0-9]*\\)?\\(\\$[-+]?[0-9]+\\)?\\)?"
8347 ;; 1 2 3 4 5
8348 "Regular expression for matching ranges in formulas.")
8350 (defconst org-table-range-regexp2
8351 (concat
8352 "\\(" "@[-0-9I$&]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\|" "\\$[a-zA-Z0-9]+" "\\)"
8353 "\\.\\."
8354 "\\(" "@?[-0-9I$&]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\|" "\\$[a-zA-Z0-9]+" "\\)")
8355 "Match a range for reference display.")
8357 (defconst org-table-translate-regexp
8358 (concat "\\(" "@[-0-9I$]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\)")
8359 "Match a reference that needs translation, for reference display.")
8361 (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
8363 (defun org-table-create-with-table.el ()
8364 "Use the table.el package to insert a new table.
8365 If there is already a table at point, convert between Org-mode tables
8366 and table.el tables."
8367 (interactive)
8368 (require 'table)
8369 (cond
8370 ((org-at-table.el-p)
8371 (if (y-or-n-p "Convert table to Org-mode table? ")
8372 (org-table-convert)))
8373 ((org-at-table-p)
8374 (if (y-or-n-p "Convert table to table.el table? ")
8375 (org-table-convert)))
8376 (t (call-interactively 'table-insert))))
8378 (defun org-table-create-or-convert-from-region (arg)
8379 "Convert region to table, or create an empty table.
8380 If there is an active region, convert it to a table, using the function
8381 `org-table-convert-region'. See the documentation of that function
8382 to learn how the prefix argument is interpreted to determine the field
8383 separator.
8384 If there is no such region, create an empty table with `org-table-create'."
8385 (interactive "P")
8386 (if (org-region-active-p)
8387 (org-table-convert-region (region-beginning) (region-end) arg)
8388 (org-table-create arg)))
8390 (defun org-table-create (&optional size)
8391 "Query for a size and insert a table skeleton.
8392 SIZE is a string Columns x Rows like for example \"3x2\"."
8393 (interactive "P")
8394 (unless size
8395 (setq size (read-string
8396 (concat "Table size Columns x Rows [e.g. "
8397 org-table-default-size "]: ")
8398 "" nil org-table-default-size)))
8400 (let* ((pos (point))
8401 (indent (make-string (current-column) ?\ ))
8402 (split (org-split-string size " *x *"))
8403 (rows (string-to-number (nth 1 split)))
8404 (columns (string-to-number (car split)))
8405 (line (concat (apply 'concat indent "|" (make-list columns " |"))
8406 "\n")))
8407 (if (string-match "^[ \t]*$" (buffer-substring-no-properties
8408 (point-at-bol) (point)))
8409 (beginning-of-line 1)
8410 (newline))
8411 ;; (mapcar (lambda (x) (insert line)) (make-list rows t))
8412 (dotimes (i rows) (insert line))
8413 (goto-char pos)
8414 (if (> rows 1)
8415 ;; Insert a hline after the first row.
8416 (progn
8417 (end-of-line 1)
8418 (insert "\n|-")
8419 (goto-char pos)))
8420 (org-table-align)))
8422 (defun org-table-convert-region (beg0 end0 &optional separator)
8423 "Convert region to a table.
8424 The region goes from BEG0 to END0, but these borders will be moved
8425 slightly, to make sure a beginning of line in the first line is included.
8427 SEPARATOR specifies the field separator in the lines. It can have the
8428 following values:
8430 '(4) Use the comma as a field separator
8431 '(16) Use a TAB as field separator
8432 integer When a number, use that many spaces as field separator
8433 nil When nil, the command tries to be smart and figure out the
8434 separator in the following way:
8435 - when each line contains a TAB, assume TAB-separated material
8436 - when each line contains a comme, assume CSV material
8437 - else, assume one or more SPACE charcters as separator."
8438 (interactive "rP")
8439 (let* ((beg (min beg0 end0))
8440 (end (max beg0 end0))
8442 (goto-char beg)
8443 (beginning-of-line 1)
8444 (setq beg (move-marker (make-marker) (point)))
8445 (goto-char end)
8446 (if (bolp) (backward-char 1) (end-of-line 1))
8447 (setq end (move-marker (make-marker) (point)))
8448 ;; Get the right field separator
8449 (unless separator
8450 (goto-char beg)
8451 (setq separator
8452 (cond
8453 ((not (re-search-forward "^[^\n\t]+$" end t)) '(16))
8454 ((not (re-search-forward "^[^\n,]+$" end t)) '(4))
8455 (t 1))))
8456 (setq re (cond
8457 ((equal separator '(4)) "^\\|\"?[ \t]*,[ \t]*\"?")
8458 ((equal separator '(16)) "^\\|\t")
8459 ((integerp separator)
8460 (format "^ *\\| *\t *\\| \\{%d,\\}" separator))
8461 (t (error "This should not happen"))))
8462 (goto-char beg)
8463 (while (re-search-forward re end t)
8464 (replace-match "| " t t))
8465 (goto-char beg)
8466 (insert " ")
8467 (org-table-align)))
8469 (defun org-table-import (file arg)
8470 "Import FILE as a table.
8471 The file is assumed to be tab-separated. Such files can be produced by most
8472 spreadsheet and database applications. If no tabs (at least one per line)
8473 are found, lines will be split on whitespace into fields."
8474 (interactive "f\nP")
8475 (or (bolp) (newline))
8476 (let ((beg (point))
8477 (pm (point-max)))
8478 (insert-file-contents file)
8479 (org-table-convert-region beg (+ (point) (- (point-max) pm)) arg)))
8481 (defun org-table-export ()
8482 "Export table as a tab-separated file.
8483 Such a file can be imported into a spreadsheet program like Excel."
8484 (interactive)
8485 (let* ((beg (org-table-begin))
8486 (end (org-table-end))
8487 (table (buffer-substring beg end))
8488 (file (read-file-name "Export table to: "))
8489 buf)
8490 (unless (or (not (file-exists-p file))
8491 (y-or-n-p (format "Overwrite file %s? " file)))
8492 (error "Abort"))
8493 (with-current-buffer (find-file-noselect file)
8494 (setq buf (current-buffer))
8495 (erase-buffer)
8496 (fundamental-mode)
8497 (insert table)
8498 (goto-char (point-min))
8499 (while (re-search-forward "^[ \t]*|[ \t]*" nil t)
8500 (replace-match "" t t)
8501 (end-of-line 1))
8502 (goto-char (point-min))
8503 (while (re-search-forward "[ \t]*|[ \t]*$" nil t)
8504 (replace-match "" t t)
8505 (goto-char (min (1+ (point)) (point-max))))
8506 (goto-char (point-min))
8507 (while (re-search-forward "^-[-+]*$" nil t)
8508 (replace-match "")
8509 (if (looking-at "\n")
8510 (delete-char 1)))
8511 (goto-char (point-min))
8512 (while (re-search-forward "[ \t]*|[ \t]*" nil t)
8513 (replace-match "\t" t t))
8514 (save-buffer))
8515 (kill-buffer buf)))
8517 (defvar org-table-aligned-begin-marker (make-marker)
8518 "Marker at the beginning of the table last aligned.
8519 Used to check if cursor still is in that table, to minimize realignment.")
8520 (defvar org-table-aligned-end-marker (make-marker)
8521 "Marker at the end of the table last aligned.
8522 Used to check if cursor still is in that table, to minimize realignment.")
8523 (defvar org-table-last-alignment nil
8524 "List of flags for flushright alignment, from the last re-alignment.
8525 This is being used to correctly align a single field after TAB or RET.")
8526 (defvar org-table-last-column-widths nil
8527 "List of max width of fields in each column.
8528 This is being used to correctly align a single field after TAB or RET.")
8529 (defvar org-table-overlay-coordinates nil
8530 "Overlay coordinates after each align of a table.")
8531 (make-variable-buffer-local 'org-table-overlay-coordinates)
8533 (defvar org-last-recalc-line nil)
8534 (defconst org-narrow-column-arrow "=>"
8535 "Used as display property in narrowed table columns.")
8537 (defun org-table-align ()
8538 "Align the table at point by aligning all vertical bars."
8539 (interactive)
8540 (let* (
8541 ;; Limits of table
8542 (beg (org-table-begin))
8543 (end (org-table-end))
8544 ;; Current cursor position
8545 (linepos (org-current-line))
8546 (colpos (org-table-current-column))
8547 (winstart (window-start))
8548 (winstartline (org-current-line (min winstart (1- (point-max)))))
8549 lines (new "") lengths l typenums ty fields maxfields i
8550 column
8551 (indent "") cnt frac
8552 rfmt hfmt
8553 (spaces '(1 . 1))
8554 (sp1 (car spaces))
8555 (sp2 (cdr spaces))
8556 (rfmt1 (concat
8557 (make-string sp2 ?\ ) "%%%s%ds" (make-string sp1 ?\ ) "|"))
8558 (hfmt1 (concat
8559 (make-string sp2 ?-) "%s" (make-string sp1 ?-) "+"))
8560 emptystrings links dates emph narrow fmax f1 len c e)
8561 (untabify beg end)
8562 (remove-text-properties beg end '(org-cwidth t org-dwidth t display t))
8563 ;; Check if we have links or dates
8564 (goto-char beg)
8565 (setq links (re-search-forward org-bracket-link-regexp end t))
8566 (goto-char beg)
8567 (setq emph (and org-hide-emphasis-markers
8568 (re-search-forward org-emph-re end t)))
8569 (goto-char beg)
8570 (setq dates (and org-display-custom-times
8571 (re-search-forward org-ts-regexp-both end t)))
8572 ;; Make sure the link properties are right
8573 (when links (goto-char beg) (while (org-activate-bracket-links end)))
8574 ;; Make sure the date properties are right
8575 (when dates (goto-char beg) (while (org-activate-dates end)))
8576 (when emph (goto-char beg) (while (org-do-emphasis-faces end)))
8578 ;; Check if we are narrowing any columns
8579 (goto-char beg)
8580 (setq narrow (and org-format-transports-properties-p
8581 (re-search-forward "<[0-9]+>" end t)))
8582 ;; Get the rows
8583 (setq lines (org-split-string
8584 (buffer-substring beg end) "\n"))
8585 ;; Store the indentation of the first line
8586 (if (string-match "^ *" (car lines))
8587 (setq indent (make-string (- (match-end 0) (match-beginning 0)) ?\ )))
8588 ;; Mark the hlines by setting the corresponding element to nil
8589 ;; At the same time, we remove trailing space.
8590 (setq lines (mapcar (lambda (l)
8591 (if (string-match "^ *|-" l)
8593 (if (string-match "[ \t]+$" l)
8594 (substring l 0 (match-beginning 0))
8595 l)))
8596 lines))
8597 ;; Get the data fields by splitting the lines.
8598 (setq fields (mapcar
8599 (lambda (l)
8600 (org-split-string l " *| *"))
8601 (delq nil (copy-sequence lines))))
8602 ;; How many fields in the longest line?
8603 (condition-case nil
8604 (setq maxfields (apply 'max (mapcar 'length fields)))
8605 (error
8606 (kill-region beg end)
8607 (org-table-create org-table-default-size)
8608 (error "Empty table - created default table")))
8609 ;; A list of empty strings to fill any short rows on output
8610 (setq emptystrings (make-list maxfields ""))
8611 ;; Check for special formatting.
8612 (setq i -1)
8613 (while (< (setq i (1+ i)) maxfields) ;; Loop over all columns
8614 (setq column (mapcar (lambda (x) (or (nth i x) "")) fields))
8615 ;; Check if there is an explicit width specified
8616 (when narrow
8617 (setq c column fmax nil)
8618 (while c
8619 (setq e (pop c))
8620 (if (and (stringp e) (string-match "^<\\([0-9]+\\)>$" e))
8621 (setq fmax (string-to-number (match-string 1 e)) c nil)))
8622 ;; Find fields that are wider than fmax, and shorten them
8623 (when fmax
8624 (loop for xx in column do
8625 (when (and (stringp xx)
8626 (> (org-string-width xx) fmax))
8627 (org-add-props xx nil
8628 'help-echo
8629 (concat "Clipped table field, use C-c ` to edit. Full value is:\n" (org-no-properties (copy-sequence xx))))
8630 (setq f1 (min fmax (or (string-match org-bracket-link-regexp xx) fmax)))
8631 (unless (> f1 1)
8632 (error "Cannot narrow field starting with wide link \"%s\""
8633 (match-string 0 xx)))
8634 (add-text-properties f1 (length xx) (list 'org-cwidth t) xx)
8635 (add-text-properties (- f1 2) f1
8636 (list 'display org-narrow-column-arrow)
8637 xx)))))
8638 ;; Get the maximum width for each column
8639 (push (apply 'max 1 (mapcar 'org-string-width column)) lengths)
8640 ;; Get the fraction of numbers, to decide about alignment of the column
8641 (setq cnt 0 frac 0.0)
8642 (loop for x in column do
8643 (if (equal x "")
8645 (setq frac ( / (+ (* frac cnt)
8646 (if (string-match org-table-number-regexp x) 1 0))
8647 (setq cnt (1+ cnt))))))
8648 (push (>= frac org-table-number-fraction) typenums))
8649 (setq lengths (nreverse lengths) typenums (nreverse typenums))
8651 ;; Store the alignment of this table, for later editing of single fields
8652 (setq org-table-last-alignment typenums
8653 org-table-last-column-widths lengths)
8655 ;; With invisible characters, `format' does not get the field width right
8656 ;; So we need to make these fields wide by hand.
8657 (when (or links emph)
8658 (loop for i from 0 upto (1- maxfields) do
8659 (setq len (nth i lengths))
8660 (loop for j from 0 upto (1- (length fields)) do
8661 (setq c (nthcdr i (car (nthcdr j fields))))
8662 (if (and (stringp (car c))
8663 (text-property-any 0 (length (car c)) 'invisible 'org-link (car c))
8664 ; (string-match org-bracket-link-regexp (car c))
8665 (< (org-string-width (car c)) len))
8666 (setcar c (concat (car c) (make-string (- len (org-string-width (car c))) ?\ )))))))
8668 ;; Compute the formats needed for output of the table
8669 (setq rfmt (concat indent "|") hfmt (concat indent "|"))
8670 (while (setq l (pop lengths))
8671 (setq ty (if (pop typenums) "" "-")) ; number types flushright
8672 (setq rfmt (concat rfmt (format rfmt1 ty l))
8673 hfmt (concat hfmt (format hfmt1 (make-string l ?-)))))
8674 (setq rfmt (concat rfmt "\n")
8675 hfmt (concat (substring hfmt 0 -1) "|\n"))
8677 (setq new (mapconcat
8678 (lambda (l)
8679 (if l (apply 'format rfmt
8680 (append (pop fields) emptystrings))
8681 hfmt))
8682 lines ""))
8683 ;; Replace the old one
8684 (delete-region beg end)
8685 (move-marker end nil)
8686 (move-marker org-table-aligned-begin-marker (point))
8687 (insert new)
8688 (move-marker org-table-aligned-end-marker (point))
8689 (when (and orgtbl-mode (not (org-mode-p)))
8690 (goto-char org-table-aligned-begin-marker)
8691 (while (org-hide-wide-columns org-table-aligned-end-marker)))
8692 ;; Try to move to the old location
8693 (goto-line winstartline)
8694 (setq winstart (point-at-bol))
8695 (goto-line linepos)
8696 (set-window-start (selected-window) winstart 'noforce)
8697 (org-table-goto-column colpos)
8698 (and org-table-overlay-coordinates (org-table-overlay-coordinates))
8699 (setq org-table-may-need-update nil)
8702 (defun org-string-width (s)
8703 "Compute width of string, ignoring invisible characters.
8704 This ignores character with invisibility property `org-link', and also
8705 characters with property `org-cwidth', because these will become invisible
8706 upon the next fontification round."
8707 (let (b l)
8708 (when (or (eq t buffer-invisibility-spec)
8709 (assq 'org-link buffer-invisibility-spec))
8710 (while (setq b (text-property-any 0 (length s)
8711 'invisible 'org-link s))
8712 (setq s (concat (substring s 0 b)
8713 (substring s (or (next-single-property-change
8714 b 'invisible s) (length s)))))))
8715 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
8716 (setq s (concat (substring s 0 b)
8717 (substring s (or (next-single-property-change
8718 b 'org-cwidth s) (length s))))))
8719 (setq l (string-width s) b -1)
8720 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
8721 (setq l (- l (get-text-property b 'org-dwidth-n s))))
8724 (defun org-table-begin (&optional table-type)
8725 "Find the beginning of the table and return its position.
8726 With argument TABLE-TYPE, go to the beginning of a table.el-type table."
8727 (save-excursion
8728 (if (not (re-search-backward
8729 (if table-type org-table-any-border-regexp
8730 org-table-border-regexp)
8731 nil t))
8732 (progn (goto-char (point-min)) (point))
8733 (goto-char (match-beginning 0))
8734 (beginning-of-line 2)
8735 (point))))
8737 (defun org-table-end (&optional table-type)
8738 "Find the end of the table and return its position.
8739 With argument TABLE-TYPE, go to the end of a table.el-type table."
8740 (save-excursion
8741 (if (not (re-search-forward
8742 (if table-type org-table-any-border-regexp
8743 org-table-border-regexp)
8744 nil t))
8745 (goto-char (point-max))
8746 (goto-char (match-beginning 0)))
8747 (point-marker)))
8749 (defun org-table-justify-field-maybe (&optional new)
8750 "Justify the current field, text to left, number to right.
8751 Optional argument NEW may specify text to replace the current field content."
8752 (cond
8753 ((and (not new) org-table-may-need-update)) ; Realignment will happen anyway
8754 ((org-at-table-hline-p))
8755 ((and (not new)
8756 (or (not (equal (marker-buffer org-table-aligned-begin-marker)
8757 (current-buffer)))
8758 (< (point) org-table-aligned-begin-marker)
8759 (>= (point) org-table-aligned-end-marker)))
8760 ;; This is not the same table, force a full re-align
8761 (setq org-table-may-need-update t))
8762 (t ;; realign the current field, based on previous full realign
8763 (let* ((pos (point)) s
8764 (col (org-table-current-column))
8765 (num (if (> col 0) (nth (1- col) org-table-last-alignment)))
8766 l f n o e)
8767 (when (> col 0)
8768 (skip-chars-backward "^|\n")
8769 (if (looking-at " *\\([^|\n]*?\\) *\\(|\\|$\\)")
8770 (progn
8771 (setq s (match-string 1)
8772 o (match-string 0)
8773 l (max 1 (- (match-end 0) (match-beginning 0) 3))
8774 e (not (= (match-beginning 2) (match-end 2))))
8775 (setq f (format (if num " %%%ds %s" " %%-%ds %s")
8776 l (if e "|" (setq org-table-may-need-update t) ""))
8777 n (format f s))
8778 (if new
8779 (if (<= (length new) l) ;; FIXME: length -> str-width?
8780 (setq n (format f new))
8781 (setq n (concat new "|") org-table-may-need-update t)))
8782 (or (equal n o)
8783 (let (org-table-may-need-update)
8784 (replace-match n t t))))
8785 (setq org-table-may-need-update t))
8786 (goto-char pos))))))
8788 (defun org-table-next-field ()
8789 "Go to the next field in the current table, creating new lines as needed.
8790 Before doing so, re-align the table if necessary."
8791 (interactive)
8792 (org-table-maybe-eval-formula)
8793 (org-table-maybe-recalculate-line)
8794 (if (and org-table-automatic-realign
8795 org-table-may-need-update)
8796 (org-table-align))
8797 (let ((end (org-table-end)))
8798 (if (org-at-table-hline-p)
8799 (end-of-line 1))
8800 (condition-case nil
8801 (progn
8802 (re-search-forward "|" end)
8803 (if (looking-at "[ \t]*$")
8804 (re-search-forward "|" end))
8805 (if (and (looking-at "-")
8806 org-table-tab-jumps-over-hlines
8807 (re-search-forward "^[ \t]*|\\([^-]\\)" end t))
8808 (goto-char (match-beginning 1)))
8809 (if (looking-at "-")
8810 (progn
8811 (beginning-of-line 0)
8812 (org-table-insert-row 'below))
8813 (if (looking-at " ") (forward-char 1))))
8814 (error
8815 (org-table-insert-row 'below)))))
8817 (defun org-table-previous-field ()
8818 "Go to the previous field in the table.
8819 Before doing so, re-align the table if necessary."
8820 (interactive)
8821 (org-table-justify-field-maybe)
8822 (org-table-maybe-recalculate-line)
8823 (if (and org-table-automatic-realign
8824 org-table-may-need-update)
8825 (org-table-align))
8826 (if (org-at-table-hline-p)
8827 (end-of-line 1))
8828 (re-search-backward "|" (org-table-begin))
8829 (re-search-backward "|" (org-table-begin))
8830 (while (looking-at "|\\(-\\|[ \t]*$\\)")
8831 (re-search-backward "|" (org-table-begin)))
8832 (if (looking-at "| ?")
8833 (goto-char (match-end 0))))
8835 (defun org-table-next-row ()
8836 "Go to the next row (same column) in the current table.
8837 Before doing so, re-align the table if necessary."
8838 (interactive)
8839 (org-table-maybe-eval-formula)
8840 (org-table-maybe-recalculate-line)
8841 (if (or (looking-at "[ \t]*$")
8842 (save-excursion (skip-chars-backward " \t") (bolp)))
8843 (newline)
8844 (if (and org-table-automatic-realign
8845 org-table-may-need-update)
8846 (org-table-align))
8847 (let ((col (org-table-current-column)))
8848 (beginning-of-line 2)
8849 (if (or (not (org-at-table-p))
8850 (org-at-table-hline-p))
8851 (progn
8852 (beginning-of-line 0)
8853 (org-table-insert-row 'below)))
8854 (org-table-goto-column col)
8855 (skip-chars-backward "^|\n\r")
8856 (if (looking-at " ") (forward-char 1)))))
8858 (defun org-table-copy-down (n)
8859 "Copy a field down in the current column.
8860 If the field at the cursor is empty, copy into it the content of the nearest
8861 non-empty field above. With argument N, use the Nth non-empty field.
8862 If the current field is not empty, it is copied down to the next row, and
8863 the cursor is moved with it. Therefore, repeating this command causes the
8864 column to be filled row-by-row.
8865 If the variable `org-table-copy-increment' is non-nil and the field is an
8866 integer or a timestamp, it will be incremented while copying. In the case of
8867 a timestamp, if the cursor is on the year, change the year. If it is on the
8868 month or the day, change that. Point will stay on the current date field
8869 in order to easily repeat the interval."
8870 (interactive "p")
8871 (let* ((colpos (org-table-current-column))
8872 (col (current-column))
8873 (field (org-table-get-field))
8874 (non-empty (string-match "[^ \t]" field))
8875 (beg (org-table-begin))
8876 txt)
8877 (org-table-check-inside-data-field)
8878 (if non-empty
8879 (progn
8880 (setq txt (org-trim field))
8881 (org-table-next-row)
8882 (org-table-blank-field))
8883 (save-excursion
8884 (setq txt
8885 (catch 'exit
8886 (while (progn (beginning-of-line 1)
8887 (re-search-backward org-table-dataline-regexp
8888 beg t))
8889 (org-table-goto-column colpos t)
8890 (if (and (looking-at
8891 "|[ \t]*\\([^| \t][^|]*?\\)[ \t]*|")
8892 (= (setq n (1- n)) 0))
8893 (throw 'exit (match-string 1))))))))
8894 (if txt
8895 (progn
8896 (if (and org-table-copy-increment
8897 (string-match "^[0-9]+$" txt))
8898 (setq txt (format "%d" (+ (string-to-number txt) 1))))
8899 (insert txt)
8900 (move-to-column col)
8901 (if (and org-table-copy-increment (org-at-timestamp-p t))
8902 (org-timestamp-up 1)
8903 (org-table-maybe-recalculate-line))
8904 (org-table-align)
8905 (move-to-column col))
8906 (error "No non-empty field found"))))
8908 (defun org-table-check-inside-data-field ()
8909 "Is point inside a table data field?
8910 I.e. not on a hline or before the first or after the last column?
8911 This actually throws an error, so it aborts the current command."
8912 (if (or (not (org-at-table-p))
8913 (= (org-table-current-column) 0)
8914 (org-at-table-hline-p)
8915 (looking-at "[ \t]*$"))
8916 (error "Not in table data field")))
8918 (defvar org-table-clip nil
8919 "Clipboard for table regions.")
8921 (defun org-table-blank-field ()
8922 "Blank the current table field or active region."
8923 (interactive)
8924 (org-table-check-inside-data-field)
8925 (if (and (interactive-p) (org-region-active-p))
8926 (let (org-table-clip)
8927 (org-table-cut-region (region-beginning) (region-end)))
8928 (skip-chars-backward "^|")
8929 (backward-char 1)
8930 (if (looking-at "|[^|\n]+")
8931 (let* ((pos (match-beginning 0))
8932 (match (match-string 0))
8933 (len (org-string-width match)))
8934 (replace-match (concat "|" (make-string (1- len) ?\ )))
8935 (goto-char (+ 2 pos))
8936 (substring match 1)))))
8938 (defun org-table-get-field (&optional n replace)
8939 "Return the value of the field in column N of current row.
8940 N defaults to current field.
8941 If REPLACE is a string, replace field with this value. The return value
8942 is always the old value."
8943 (and n (org-table-goto-column n))
8944 (skip-chars-backward "^|\n")
8945 (backward-char 1)
8946 (if (looking-at "|[^|\r\n]*")
8947 (let* ((pos (match-beginning 0))
8948 (val (buffer-substring (1+ pos) (match-end 0))))
8949 (if replace
8950 (replace-match (concat "|" replace) t t))
8951 (goto-char (min (point-at-eol) (+ 2 pos)))
8952 val)
8953 (forward-char 1) ""))
8955 (defun org-table-field-info (arg)
8956 "Show info about the current field, and highlight any reference at point."
8957 (interactive "P")
8958 (org-table-get-specials)
8959 (save-excursion
8960 (let* ((pos (point))
8961 (col (org-table-current-column))
8962 (cname (car (rassoc (int-to-string col) org-table-column-names)))
8963 (name (car (rassoc (list (org-current-line) col)
8964 org-table-named-field-locations)))
8965 (eql (org-table-get-stored-formulas))
8966 (dline (org-table-current-dline))
8967 (ref (format "@%d$%d" dline col))
8968 (ref1 (org-table-convert-refs-to-an ref))
8969 (fequation (or (assoc name eql) (assoc ref eql)))
8970 (cequation (assoc (int-to-string col) eql))
8971 (eqn (or fequation cequation)))
8972 (goto-char pos)
8973 (condition-case nil
8974 (org-table-show-reference 'local)
8975 (error nil))
8976 (message "line @%d, col $%s%s, ref @%d$%d or %s%s%s"
8977 dline col
8978 (if cname (concat " or $" cname) "")
8979 dline col ref1
8980 (if name (concat " or $" name) "")
8981 ;; FIXME: formula info not correct if special table line
8982 (if eqn
8983 (concat ", formula: "
8984 (org-table-formula-to-user
8985 (concat
8986 (if (string-match "^[$@]"(car eqn)) "" "$")
8987 (car eqn) "=" (cdr eqn))))
8988 "")))))
8990 (defun org-table-current-column ()
8991 "Find out which column we are in.
8992 When called interactively, column is also displayed in echo area."
8993 (interactive)
8994 (if (interactive-p) (org-table-check-inside-data-field))
8995 (save-excursion
8996 (let ((cnt 0) (pos (point)))
8997 (beginning-of-line 1)
8998 (while (search-forward "|" pos t)
8999 (setq cnt (1+ cnt)))
9000 (if (interactive-p) (message "This is table column %d" cnt))
9001 cnt)))
9003 (defun org-table-current-dline ()
9004 "Find out what table data line we are in.
9005 Only datalins count for this."
9006 (interactive)
9007 (if (interactive-p) (org-table-check-inside-data-field))
9008 (save-excursion
9009 (let ((cnt 0) (pos (point)))
9010 (goto-char (org-table-begin))
9011 (while (<= (point) pos)
9012 (if (looking-at org-table-dataline-regexp) (setq cnt (1+ cnt)))
9013 (beginning-of-line 2))
9014 (if (interactive-p) (message "This is table line %d" cnt))
9015 cnt)))
9017 (defun org-table-goto-column (n &optional on-delim force)
9018 "Move the cursor to the Nth column in the current table line.
9019 With optional argument ON-DELIM, stop with point before the left delimiter
9020 of the field.
9021 If there are less than N fields, just go to after the last delimiter.
9022 However, when FORCE is non-nil, create new columns if necessary."
9023 (interactive "p")
9024 (let ((pos (point-at-eol)))
9025 (beginning-of-line 1)
9026 (when (> n 0)
9027 (while (and (> (setq n (1- n)) -1)
9028 (or (search-forward "|" pos t)
9029 (and force
9030 (progn (end-of-line 1)
9031 (skip-chars-backward "^|")
9032 (insert " | "))))))
9033 ; (backward-char 2) t)))))
9034 (when (and force (not (looking-at ".*|")))
9035 (save-excursion (end-of-line 1) (insert " | ")))
9036 (if on-delim
9037 (backward-char 1)
9038 (if (looking-at " ") (forward-char 1))))))
9040 (defun org-at-table-p (&optional table-type)
9041 "Return t if the cursor is inside an org-type table.
9042 If TABLE-TYPE is non-nil, also check for table.el-type tables."
9043 (if org-enable-table-editor
9044 (save-excursion
9045 (beginning-of-line 1)
9046 (looking-at (if table-type org-table-any-line-regexp
9047 org-table-line-regexp)))
9048 nil))
9050 (defun org-at-table.el-p ()
9051 "Return t if and only if we are at a table.el table."
9052 (and (org-at-table-p 'any)
9053 (save-excursion
9054 (goto-char (org-table-begin 'any))
9055 (looking-at org-table1-hline-regexp))))
9057 (defun org-table-recognize-table.el ()
9058 "If there is a table.el table nearby, recognize it and move into it."
9059 (if org-table-tab-recognizes-table.el
9060 (if (org-at-table.el-p)
9061 (progn
9062 (beginning-of-line 1)
9063 (if (looking-at org-table-dataline-regexp)
9065 (if (looking-at org-table1-hline-regexp)
9066 (progn
9067 (beginning-of-line 2)
9068 (if (looking-at org-table-any-border-regexp)
9069 (beginning-of-line -1)))))
9070 (if (re-search-forward "|" (org-table-end t) t)
9071 (progn
9072 (require 'table)
9073 (if (table--at-cell-p (point))
9075 (message "recognizing table.el table...")
9076 (table-recognize-table)
9077 (message "recognizing table.el table...done")))
9078 (error "This should not happen..."))
9080 nil)
9081 nil))
9083 (defun org-at-table-hline-p ()
9084 "Return t if the cursor is inside a hline in a table."
9085 (if org-enable-table-editor
9086 (save-excursion
9087 (beginning-of-line 1)
9088 (looking-at org-table-hline-regexp))
9089 nil))
9091 (defun org-table-insert-column ()
9092 "Insert a new column into the table."
9093 (interactive)
9094 (if (not (org-at-table-p))
9095 (error "Not at a table"))
9096 (org-table-find-dataline)
9097 (let* ((col (max 1 (org-table-current-column)))
9098 (beg (org-table-begin))
9099 (end (org-table-end))
9100 ;; Current cursor position
9101 (linepos (org-current-line))
9102 (colpos col))
9103 (goto-char beg)
9104 (while (< (point) end)
9105 (if (org-at-table-hline-p)
9107 (org-table-goto-column col t)
9108 (insert "| "))
9109 (beginning-of-line 2))
9110 (move-marker end nil)
9111 (goto-line linepos)
9112 (org-table-goto-column colpos)
9113 (org-table-align)
9114 (org-table-fix-formulas "$" nil (1- col) 1)))
9116 (defun org-table-find-dataline ()
9117 "Find a dataline in the current table, which is needed for column commands."
9118 (if (and (org-at-table-p)
9119 (not (org-at-table-hline-p)))
9121 (let ((col (current-column))
9122 (end (org-table-end)))
9123 (move-to-column col)
9124 (while (and (< (point) end)
9125 (or (not (= (current-column) col))
9126 (org-at-table-hline-p)))
9127 (beginning-of-line 2)
9128 (move-to-column col))
9129 (if (and (org-at-table-p)
9130 (not (org-at-table-hline-p)))
9132 (error
9133 "Please position cursor in a data line for column operations")))))
9135 (defun org-table-delete-column ()
9136 "Delete a column from the table."
9137 (interactive)
9138 (if (not (org-at-table-p))
9139 (error "Not at a table"))
9140 (org-table-find-dataline)
9141 (org-table-check-inside-data-field)
9142 (let* ((col (org-table-current-column))
9143 (beg (org-table-begin))
9144 (end (org-table-end))
9145 ;; Current cursor position
9146 (linepos (org-current-line))
9147 (colpos col))
9148 (goto-char beg)
9149 (while (< (point) end)
9150 (if (org-at-table-hline-p)
9152 (org-table-goto-column col t)
9153 (and (looking-at "|[^|\n]+|")
9154 (replace-match "|")))
9155 (beginning-of-line 2))
9156 (move-marker end nil)
9157 (goto-line linepos)
9158 (org-table-goto-column colpos)
9159 (org-table-align)
9160 (org-table-fix-formulas "$" (list (cons (number-to-string col) "INVALID"))
9161 col -1 col)))
9163 (defun org-table-move-column-right ()
9164 "Move column to the right."
9165 (interactive)
9166 (org-table-move-column nil))
9167 (defun org-table-move-column-left ()
9168 "Move column to the left."
9169 (interactive)
9170 (org-table-move-column 'left))
9172 (defun org-table-move-column (&optional left)
9173 "Move the current column to the right. With arg LEFT, move to the left."
9174 (interactive "P")
9175 (if (not (org-at-table-p))
9176 (error "Not at a table"))
9177 (org-table-find-dataline)
9178 (org-table-check-inside-data-field)
9179 (let* ((col (org-table-current-column))
9180 (col1 (if left (1- col) col))
9181 (beg (org-table-begin))
9182 (end (org-table-end))
9183 ;; Current cursor position
9184 (linepos (org-current-line))
9185 (colpos (if left (1- col) (1+ col))))
9186 (if (and left (= col 1))
9187 (error "Cannot move column further left"))
9188 (if (and (not left) (looking-at "[^|\n]*|[^|\n]*$"))
9189 (error "Cannot move column further right"))
9190 (goto-char beg)
9191 (while (< (point) end)
9192 (if (org-at-table-hline-p)
9194 (org-table-goto-column col1 t)
9195 (and (looking-at "|\\([^|\n]+\\)|\\([^|\n]+\\)|")
9196 (replace-match "|\\2|\\1|")))
9197 (beginning-of-line 2))
9198 (move-marker end nil)
9199 (goto-line linepos)
9200 (org-table-goto-column colpos)
9201 (org-table-align)
9202 (org-table-fix-formulas
9203 "$" (list (cons (number-to-string col) (number-to-string colpos))
9204 (cons (number-to-string colpos) (number-to-string col))))))
9206 (defun org-table-move-row-down ()
9207 "Move table row down."
9208 (interactive)
9209 (org-table-move-row nil))
9210 (defun org-table-move-row-up ()
9211 "Move table row up."
9212 (interactive)
9213 (org-table-move-row 'up))
9215 (defun org-table-move-row (&optional up)
9216 "Move the current table line down. With arg UP, move it up."
9217 (interactive "P")
9218 (let* ((col (current-column))
9219 (pos (point))
9220 (hline1p (save-excursion (beginning-of-line 1)
9221 (looking-at org-table-hline-regexp)))
9222 (dline1 (org-table-current-dline))
9223 (dline2 (+ dline1 (if up -1 1)))
9224 (tonew (if up 0 2))
9225 txt hline2p)
9226 (beginning-of-line tonew)
9227 (unless (org-at-table-p)
9228 (goto-char pos)
9229 (error "Cannot move row further"))
9230 (setq hline2p (looking-at org-table-hline-regexp))
9231 (goto-char pos)
9232 (beginning-of-line 1)
9233 (setq pos (point))
9234 (setq txt (buffer-substring (point) (1+ (point-at-eol))))
9235 (delete-region (point) (1+ (point-at-eol)))
9236 (beginning-of-line tonew)
9237 (insert txt)
9238 (beginning-of-line 0)
9239 (move-to-column col)
9240 (unless (or hline1p hline2p)
9241 (org-table-fix-formulas
9242 "@" (list (cons (number-to-string dline1) (number-to-string dline2))
9243 (cons (number-to-string dline2) (number-to-string dline1)))))))
9245 (defun org-table-insert-row (&optional arg)
9246 "Insert a new row above the current line into the table.
9247 With prefix ARG, insert below the current line."
9248 (interactive "P")
9249 (if (not (org-at-table-p))
9250 (error "Not at a table"))
9251 (let* ((line (buffer-substring (point-at-bol) (point-at-eol)))
9252 (new (org-table-clean-line line)))
9253 ;; Fix the first field if necessary
9254 (if (string-match "^[ \t]*| *[#$] *|" line)
9255 (setq new (replace-match (match-string 0 line) t t new)))
9256 (beginning-of-line (if arg 2 1))
9257 (let (org-table-may-need-update) (insert-before-markers new "\n"))
9258 (beginning-of-line 0)
9259 (re-search-forward "| ?" (point-at-eol) t)
9260 (and (or org-table-may-need-update org-table-overlay-coordinates)
9261 (org-table-align))
9262 (org-table-fix-formulas "@" nil (1- (org-table-current-dline)) 1)))
9264 (defun org-table-insert-hline (&optional above)
9265 "Insert a horizontal-line below the current line into the table.
9266 With prefix ABOVE, insert above the current line."
9267 (interactive "P")
9268 (if (not (org-at-table-p))
9269 (error "Not at a table"))
9270 (let ((line (org-table-clean-line
9271 (buffer-substring (point-at-bol) (point-at-eol))))
9272 (col (current-column)))
9273 (while (string-match "|\\( +\\)|" line)
9274 (setq line (replace-match
9275 (concat "+" (make-string (- (match-end 1) (match-beginning 1))
9276 ?-) "|") t t line)))
9277 (and (string-match "\\+" line) (setq line (replace-match "|" t t line)))
9278 (beginning-of-line (if above 1 2))
9279 (insert line "\n")
9280 (beginning-of-line (if above 1 -1))
9281 (move-to-column col)
9282 (and org-table-overlay-coordinates (org-table-align))))
9284 (defun org-table-hline-and-move (&optional same-column)
9285 "Insert a hline and move to the row below that line."
9286 (interactive "P")
9287 (let ((col (org-table-current-column)))
9288 (org-table-maybe-eval-formula)
9289 (org-table-maybe-recalculate-line)
9290 (org-table-insert-hline)
9291 (end-of-line 2)
9292 (if (looking-at "\n[ \t]*|-")
9293 (progn (insert "\n|") (org-table-align))
9294 (org-table-next-field))
9295 (if same-column (org-table-goto-column col))))
9297 (defun org-table-clean-line (s)
9298 "Convert a table line S into a string with only \"|\" and space.
9299 In particular, this does handle wide and invisible characters."
9300 (if (string-match "^[ \t]*|-" s)
9301 ;; It's a hline, just map the characters
9302 (setq s (mapconcat (lambda (x) (if (member x '(?| ?+)) "|" " ")) s ""))
9303 (while (string-match "|\\([ \t]*?[^ \t\r\n|][^\r\n|]*\\)|" s)
9304 (setq s (replace-match
9305 (concat "|" (make-string (org-string-width (match-string 1 s))
9306 ?\ ) "|")
9307 t t s)))
9310 (defun org-table-kill-row ()
9311 "Delete the current row or horizontal line from the table."
9312 (interactive)
9313 (if (not (org-at-table-p))
9314 (error "Not at a table"))
9315 (let ((col (current-column))
9316 (dline (org-table-current-dline)))
9317 (kill-region (point-at-bol) (min (1+ (point-at-eol)) (point-max)))
9318 (if (not (org-at-table-p)) (beginning-of-line 0))
9319 (move-to-column col)
9320 (org-table-fix-formulas "@" (list (cons (number-to-string dline) "INVALID"))
9321 dline -1 dline)))
9323 (defun org-table-sort-lines (with-case &optional sorting-type)
9324 "Sort table lines according to the column at point.
9326 The position of point indicates the column to be used for
9327 sorting, and the range of lines is the range between the nearest
9328 horizontal separator lines, or the entire table of no such lines
9329 exist. If point is before the first column, you will be prompted
9330 for the sorting column. If there is an active region, the mark
9331 specifies the first line and the sorting column, while point
9332 should be in the last line to be included into the sorting.
9334 The command then prompts for the sorting type which can be
9335 alphabetically, numerically, or by time (as given in a time stamp
9336 in the field). Sorting in reverse order is also possible.
9338 With prefix argument WITH-CASE, alphabetic sorting will be case-sensitive.
9340 If SORTING-TYPE is specified when this function is called from a Lisp
9341 program, no prompting will take place. SORTING-TYPE must be a character,
9342 any of (?a ?A ?n ?N ?t ?T) where the capital letter indicate that sorting
9343 should be done in reverse order."
9344 (interactive "P")
9345 (let* ((thisline (org-current-line))
9346 (thiscol (org-table-current-column))
9347 beg end bcol ecol tend tbeg column lns pos)
9348 (when (equal thiscol 0)
9349 (if (interactive-p)
9350 (setq thiscol
9351 (string-to-number
9352 (read-string "Use column N for sorting: ")))
9353 (setq thiscol 1))
9354 (org-table-goto-column thiscol))
9355 (org-table-check-inside-data-field)
9356 (if (org-region-active-p)
9357 (progn
9358 (setq beg (region-beginning) end (region-end))
9359 (goto-char beg)
9360 (setq column (org-table-current-column)
9361 beg (point-at-bol))
9362 (goto-char end)
9363 (setq end (point-at-bol 2)))
9364 (setq column (org-table-current-column)
9365 pos (point)
9366 tbeg (org-table-begin)
9367 tend (org-table-end))
9368 (if (re-search-backward org-table-hline-regexp tbeg t)
9369 (setq beg (point-at-bol 2))
9370 (goto-char tbeg)
9371 (setq beg (point-at-bol 1)))
9372 (goto-char pos)
9373 (if (re-search-forward org-table-hline-regexp tend t)
9374 (setq end (point-at-bol 1))
9375 (goto-char tend)
9376 (setq end (point-at-bol))))
9377 (setq beg (move-marker (make-marker) beg)
9378 end (move-marker (make-marker) end))
9379 (untabify beg end)
9380 (goto-char beg)
9381 (org-table-goto-column column)
9382 (skip-chars-backward "^|")
9383 (setq bcol (current-column))
9384 (org-table-goto-column (1+ column))
9385 (skip-chars-backward "^|")
9386 (setq ecol (1- (current-column)))
9387 (org-table-goto-column column)
9388 (setq lns (mapcar (lambda(x) (cons
9389 (org-sort-remove-invisible
9390 (nth (1- column)
9391 (org-split-string x "[ \t]*|[ \t]*")))
9393 (org-split-string (buffer-substring beg end) "\n")))
9394 (setq lns (org-do-sort lns "Table" with-case sorting-type))
9395 (delete-region beg end)
9396 (move-marker beg nil)
9397 (move-marker end nil)
9398 (insert (mapconcat 'cdr lns "\n") "\n")
9399 (goto-line thisline)
9400 (org-table-goto-column thiscol)
9401 (message "%d lines sorted, based on column %d" (length lns) column)))
9403 ;; FIXME: maybe we will not need this? Table sorting is broken....
9404 (defun org-sort-remove-invisible (s)
9405 (remove-text-properties 0 (length s) org-rm-props s)
9406 (while (string-match org-bracket-link-regexp s)
9407 (setq s (replace-match (if (match-end 2)
9408 (match-string 3 s)
9409 (match-string 1 s)) t t s)))
9412 (defun org-table-cut-region (beg end)
9413 "Copy region in table to the clipboard and blank all relevant fields."
9414 (interactive "r")
9415 (org-table-copy-region beg end 'cut))
9417 (defun org-table-copy-region (beg end &optional cut)
9418 "Copy rectangular region in table to clipboard.
9419 A special clipboard is used which can only be accessed
9420 with `org-table-paste-rectangle'."
9421 (interactive "rP")
9422 (let* (l01 c01 l02 c02 l1 c1 l2 c2 ic1 ic2
9423 region cols
9424 (rpl (if cut " " nil)))
9425 (goto-char beg)
9426 (org-table-check-inside-data-field)
9427 (setq l01 (org-current-line)
9428 c01 (org-table-current-column))
9429 (goto-char end)
9430 (org-table-check-inside-data-field)
9431 (setq l02 (org-current-line)
9432 c02 (org-table-current-column))
9433 (setq l1 (min l01 l02) l2 (max l01 l02)
9434 c1 (min c01 c02) c2 (max c01 c02))
9435 (catch 'exit
9436 (while t
9437 (catch 'nextline
9438 (if (> l1 l2) (throw 'exit t))
9439 (goto-line l1)
9440 (if (org-at-table-hline-p) (throw 'nextline (setq l1 (1+ l1))))
9441 (setq cols nil ic1 c1 ic2 c2)
9442 (while (< ic1 (1+ ic2))
9443 (push (org-table-get-field ic1 rpl) cols)
9444 (setq ic1 (1+ ic1)))
9445 (push (nreverse cols) region)
9446 (setq l1 (1+ l1)))))
9447 (setq org-table-clip (nreverse region))
9448 (if cut (org-table-align))
9449 org-table-clip))
9451 (defun org-table-paste-rectangle ()
9452 "Paste a rectangular region into a table.
9453 The upper right corner ends up in the current field. All involved fields
9454 will be overwritten. If the rectangle does not fit into the present table,
9455 the table is enlarged as needed. The process ignores horizontal separator
9456 lines."
9457 (interactive)
9458 (unless (and org-table-clip (listp org-table-clip))
9459 (error "First cut/copy a region to paste!"))
9460 (org-table-check-inside-data-field)
9461 (let* ((clip org-table-clip)
9462 (line (org-current-line))
9463 (col (org-table-current-column))
9464 (org-enable-table-editor t)
9465 (org-table-automatic-realign nil)
9466 c cols field)
9467 (while (setq cols (pop clip))
9468 (while (org-at-table-hline-p) (beginning-of-line 2))
9469 (if (not (org-at-table-p))
9470 (progn (end-of-line 0) (org-table-next-field)))
9471 (setq c col)
9472 (while (setq field (pop cols))
9473 (org-table-goto-column c nil 'force)
9474 (org-table-get-field nil field)
9475 (setq c (1+ c)))
9476 (beginning-of-line 2))
9477 (goto-line line)
9478 (org-table-goto-column col)
9479 (org-table-align)))
9481 (defun org-table-convert ()
9482 "Convert from `org-mode' table to table.el and back.
9483 Obviously, this only works within limits. When an Org-mode table is
9484 converted to table.el, all horizontal separator lines get lost, because
9485 table.el uses these as cell boundaries and has no notion of horizontal lines.
9486 A table.el table can be converted to an Org-mode table only if it does not
9487 do row or column spanning. Multiline cells will become multiple cells.
9488 Beware, Org-mode does not test if the table can be successfully converted - it
9489 blindly applies a recipe that works for simple tables."
9490 (interactive)
9491 (require 'table)
9492 (if (org-at-table.el-p)
9493 ;; convert to Org-mode table
9494 (let ((beg (move-marker (make-marker) (org-table-begin t)))
9495 (end (move-marker (make-marker) (org-table-end t))))
9496 (table-unrecognize-region beg end)
9497 (goto-char beg)
9498 (while (re-search-forward "^\\([ \t]*\\)\\+-.*\n" end t)
9499 (replace-match ""))
9500 (goto-char beg))
9501 (if (org-at-table-p)
9502 ;; convert to table.el table
9503 (let ((beg (move-marker (make-marker) (org-table-begin)))
9504 (end (move-marker (make-marker) (org-table-end))))
9505 ;; first, get rid of all horizontal lines
9506 (goto-char beg)
9507 (while (re-search-forward "^\\([ \t]*\\)|-.*\n" end t)
9508 (replace-match ""))
9509 ;; insert a hline before first
9510 (goto-char beg)
9511 (org-table-insert-hline 'above)
9512 (beginning-of-line -1)
9513 ;; insert a hline after each line
9514 (while (progn (beginning-of-line 3) (< (point) end))
9515 (org-table-insert-hline))
9516 (goto-char beg)
9517 (setq end (move-marker end (org-table-end)))
9518 ;; replace "+" at beginning and ending of hlines
9519 (while (re-search-forward "^\\([ \t]*\\)|-" end t)
9520 (replace-match "\\1+-"))
9521 (goto-char beg)
9522 (while (re-search-forward "-|[ \t]*$" end t)
9523 (replace-match "-+"))
9524 (goto-char beg)))))
9526 (defun org-table-wrap-region (arg)
9527 "Wrap several fields in a column like a paragraph.
9528 This is useful if you'd like to spread the contents of a field over several
9529 lines, in order to keep the table compact.
9531 If there is an active region, and both point and mark are in the same column,
9532 the text in the column is wrapped to minimum width for the given number of
9533 lines. Generally, this makes the table more compact. A prefix ARG may be
9534 used to change the number of desired lines. For example, `C-2 \\[org-table-wrap]'
9535 formats the selected text to two lines. If the region was longer than two
9536 lines, the remaining lines remain empty. A negative prefix argument reduces
9537 the current number of lines by that amount. The wrapped text is pasted back
9538 into the table. If you formatted it to more lines than it was before, fields
9539 further down in the table get overwritten - so you might need to make space in
9540 the table first.
9542 If there is no region, the current field is split at the cursor position and
9543 the text fragment to the right of the cursor is prepended to the field one
9544 line down.
9546 If there is no region, but you specify a prefix ARG, the current field gets
9547 blank, and the content is appended to the field above."
9548 (interactive "P")
9549 (org-table-check-inside-data-field)
9550 (if (org-region-active-p)
9551 ;; There is a region: fill as a paragraph
9552 (let* ((beg (region-beginning))
9553 (cline (save-excursion (goto-char beg) (org-current-line)))
9554 (ccol (save-excursion (goto-char beg) (org-table-current-column)))
9555 nlines)
9556 (org-table-cut-region (region-beginning) (region-end))
9557 (if (> (length (car org-table-clip)) 1)
9558 (error "Region must be limited to single column"))
9559 (setq nlines (if arg
9560 (if (< arg 1)
9561 (+ (length org-table-clip) arg)
9562 arg)
9563 (length org-table-clip)))
9564 (setq org-table-clip
9565 (mapcar 'list (org-wrap (mapconcat 'car org-table-clip " ")
9566 nil nlines)))
9567 (goto-line cline)
9568 (org-table-goto-column ccol)
9569 (org-table-paste-rectangle))
9570 ;; No region, split the current field at point
9571 (unless (org-get-alist-option org-M-RET-may-split-line 'table)
9572 (skip-chars-forward "^\r\n|"))
9573 (if arg
9574 ;; combine with field above
9575 (let ((s (org-table-blank-field))
9576 (col (org-table-current-column)))
9577 (beginning-of-line 0)
9578 (while (org-at-table-hline-p) (beginning-of-line 0))
9579 (org-table-goto-column col)
9580 (skip-chars-forward "^|")
9581 (skip-chars-backward " ")
9582 (insert " " (org-trim s))
9583 (org-table-align))
9584 ;; split field
9585 (if (looking-at "\\([^|]+\\)+|")
9586 (let ((s (match-string 1)))
9587 (replace-match " |")
9588 (goto-char (match-beginning 0))
9589 (org-table-next-row)
9590 (insert (org-trim s) " ")
9591 (org-table-align))
9592 (org-table-next-row)))))
9594 (defvar org-field-marker nil)
9596 (defun org-table-edit-field (arg)
9597 "Edit table field in a different window.
9598 This is mainly useful for fields that contain hidden parts.
9599 When called with a \\[universal-argument] prefix, just make the full field visible so that
9600 it can be edited in place."
9601 (interactive "P")
9602 (if arg
9603 (let ((b (save-excursion (skip-chars-backward "^|") (point)))
9604 (e (save-excursion (skip-chars-forward "^|\r\n") (point))))
9605 (remove-text-properties b e '(org-cwidth t invisible t
9606 display t intangible t))
9607 (if (and (boundp 'font-lock-mode) font-lock-mode)
9608 (font-lock-fontify-block)))
9609 (let ((pos (move-marker (make-marker) (point)))
9610 (field (org-table-get-field))
9611 (cw (current-window-configuration))
9613 (org-switch-to-buffer-other-window "*Org tmp*")
9614 (erase-buffer)
9615 (insert "#\n# Edit field and finish with C-c C-c\n#\n")
9616 (let ((org-inhibit-startup t)) (org-mode))
9617 (goto-char (setq p (point-max)))
9618 (insert (org-trim field))
9619 (remove-text-properties p (point-max)
9620 '(invisible t org-cwidth t display t
9621 intangible t))
9622 (goto-char p)
9623 (org-set-local 'org-finish-function 'org-table-finish-edit-field)
9624 (org-set-local 'org-window-configuration cw)
9625 (org-set-local 'org-field-marker pos)
9626 (message "Edit and finish with C-c C-c"))))
9628 (defun org-table-finish-edit-field ()
9629 "Finish editing a table data field.
9630 Remove all newline characters, insert the result into the table, realign
9631 the table and kill the editing buffer."
9632 (let ((pos org-field-marker)
9633 (cw org-window-configuration)
9634 (cb (current-buffer))
9635 text)
9636 (goto-char (point-min))
9637 (while (re-search-forward "^#.*\n?" nil t) (replace-match ""))
9638 (while (re-search-forward "\\([ \t]*\n[ \t]*\\)+" nil t)
9639 (replace-match " "))
9640 (setq text (org-trim (buffer-string)))
9641 (set-window-configuration cw)
9642 (kill-buffer cb)
9643 (select-window (get-buffer-window (marker-buffer pos)))
9644 (goto-char pos)
9645 (move-marker pos nil)
9646 (org-table-check-inside-data-field)
9647 (org-table-get-field nil text)
9648 (org-table-align)
9649 (message "New field value inserted")))
9651 (defun org-trim (s)
9652 "Remove whitespace at beginning and end of string."
9653 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
9654 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
9657 (defun org-wrap (string &optional width lines)
9658 "Wrap string to either a number of lines, or a width in characters.
9659 If WIDTH is non-nil, the string is wrapped to that width, however many lines
9660 that costs. If there is a word longer than WIDTH, the text is actually
9661 wrapped to the length of that word.
9662 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
9663 many lines, whatever width that takes.
9664 The return value is a list of lines, without newlines at the end."
9665 (let* ((words (org-split-string string "[ \t\n]+"))
9666 (maxword (apply 'max (mapcar 'org-string-width words)))
9667 w ll)
9668 (cond (width
9669 (org-do-wrap words (max maxword width)))
9670 (lines
9671 (setq w maxword)
9672 (setq ll (org-do-wrap words maxword))
9673 (if (<= (length ll) lines)
9675 (setq ll words)
9676 (while (> (length ll) lines)
9677 (setq w (1+ w))
9678 (setq ll (org-do-wrap words w)))
9679 ll))
9680 (t (error "Cannot wrap this")))))
9683 (defun org-do-wrap (words width)
9684 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
9685 (let (lines line)
9686 (while words
9687 (setq line (pop words))
9688 (while (and words (< (+ (length line) (length (car words))) width))
9689 (setq line (concat line " " (pop words))))
9690 (setq lines (push line lines)))
9691 (nreverse lines)))
9693 (defun org-split-string (string &optional separators)
9694 "Splits STRING into substrings at SEPARATORS.
9695 No empty strings are returned if there are matches at the beginning
9696 and end of string."
9697 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
9698 (start 0)
9699 notfirst
9700 (list nil))
9701 (while (and (string-match rexp string
9702 (if (and notfirst
9703 (= start (match-beginning 0))
9704 (< start (length string)))
9705 (1+ start) start))
9706 (< (match-beginning 0) (length string)))
9707 (setq notfirst t)
9708 (or (eq (match-beginning 0) 0)
9709 (and (eq (match-beginning 0) (match-end 0))
9710 (eq (match-beginning 0) start))
9711 (setq list
9712 (cons (substring string start (match-beginning 0))
9713 list)))
9714 (setq start (match-end 0)))
9715 (or (eq start (length string))
9716 (setq list
9717 (cons (substring string start)
9718 list)))
9719 (nreverse list)))
9721 (defun org-table-map-tables (function)
9722 "Apply FUNCTION to the start of all tables in the buffer."
9723 (save-excursion
9724 (save-restriction
9725 (widen)
9726 (goto-char (point-min))
9727 (while (re-search-forward org-table-any-line-regexp nil t)
9728 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
9729 (beginning-of-line 1)
9730 (if (looking-at org-table-line-regexp)
9731 (save-excursion (funcall function)))
9732 (re-search-forward org-table-any-border-regexp nil 1))))
9733 (message "Mapping tables: done"))
9735 (defvar org-timecnt) ; dynamically scoped parameter
9737 (defun org-table-sum (&optional beg end nlast)
9738 "Sum numbers in region of current table column.
9739 The result will be displayed in the echo area, and will be available
9740 as kill to be inserted with \\[yank].
9742 If there is an active region, it is interpreted as a rectangle and all
9743 numbers in that rectangle will be summed. If there is no active
9744 region and point is located in a table column, sum all numbers in that
9745 column.
9747 If at least one number looks like a time HH:MM or HH:MM:SS, all other
9748 numbers are assumed to be times as well (in decimal hours) and the
9749 numbers are added as such.
9751 If NLAST is a number, only the NLAST fields will actually be summed."
9752 (interactive)
9753 (save-excursion
9754 (let (col (org-timecnt 0) diff h m s org-table-clip)
9755 (cond
9756 ((and beg end)) ; beg and end given explicitly
9757 ((org-region-active-p)
9758 (setq beg (region-beginning) end (region-end)))
9760 (setq col (org-table-current-column))
9761 (goto-char (org-table-begin))
9762 (unless (re-search-forward "^[ \t]*|[^-]" nil t)
9763 (error "No table data"))
9764 (org-table-goto-column col)
9765 (setq beg (point))
9766 (goto-char (org-table-end))
9767 (unless (re-search-backward "^[ \t]*|[^-]" nil t)
9768 (error "No table data"))
9769 (org-table-goto-column col)
9770 (setq end (point))))
9771 (let* ((items (apply 'append (org-table-copy-region beg end)))
9772 (items1 (cond ((not nlast) items)
9773 ((>= nlast (length items)) items)
9774 (t (setq items (reverse items))
9775 (setcdr (nthcdr (1- nlast) items) nil)
9776 (nreverse items))))
9777 (numbers (delq nil (mapcar 'org-table-get-number-for-summing
9778 items1)))
9779 (res (apply '+ numbers))
9780 (sres (if (= org-timecnt 0)
9781 (format "%g" res)
9782 (setq diff (* 3600 res)
9783 h (floor (/ diff 3600)) diff (mod diff 3600)
9784 m (floor (/ diff 60)) diff (mod diff 60)
9785 s diff)
9786 (format "%d:%02d:%02d" h m s))))
9787 (kill-new sres)
9788 (if (interactive-p)
9789 (message "%s"
9790 (substitute-command-keys
9791 (format "Sum of %d items: %-20s (\\[yank] will insert result into buffer)"
9792 (length numbers) sres))))
9793 sres))))
9795 (defun org-table-get-number-for-summing (s)
9796 (let (n)
9797 (if (string-match "^ *|? *" s)
9798 (setq s (replace-match "" nil nil s)))
9799 (if (string-match " *|? *$" s)
9800 (setq s (replace-match "" nil nil s)))
9801 (setq n (string-to-number s))
9802 (cond
9803 ((and (string-match "0" s)
9804 (string-match "\\`[-+ \t0.edED]+\\'" s)) 0)
9805 ((string-match "\\`[ \t]+\\'" s) nil)
9806 ((string-match "\\`\\([0-9]+\\):\\([0-9]+\\)\\(:\\([0-9]+\\)\\)?\\'" s)
9807 (let ((h (string-to-number (or (match-string 1 s) "0")))
9808 (m (string-to-number (or (match-string 2 s) "0")))
9809 (s (string-to-number (or (match-string 4 s) "0"))))
9810 (if (boundp 'org-timecnt) (setq org-timecnt (1+ org-timecnt)))
9811 (* 1.0 (+ h (/ m 60.0) (/ s 3600.0)))))
9812 ((equal n 0) nil)
9813 (t n))))
9815 (defun org-table-current-field-formula (&optional key noerror)
9816 "Return the formula active for the current field.
9817 Assumes that specials are in place.
9818 If KEY is given, return the key to this formula.
9819 Otherwise return the formula preceeded with \"=\" or \":=\"."
9820 (let* ((name (car (rassoc (list (org-current-line)
9821 (org-table-current-column))
9822 org-table-named-field-locations)))
9823 (col (org-table-current-column))
9824 (scol (int-to-string col))
9825 (ref (format "@%d$%d" (org-table-current-dline) col))
9826 (stored-list (org-table-get-stored-formulas noerror))
9827 (ass (or (assoc name stored-list)
9828 (assoc ref stored-list)
9829 (assoc scol stored-list))))
9830 (if key
9831 (car ass)
9832 (if ass (concat (if (string-match "^[0-9]+$" (car ass)) "=" ":=")
9833 (cdr ass))))))
9835 (defun org-table-get-formula (&optional equation named)
9836 "Read a formula from the minibuffer, offer stored formula as default.
9837 When NAMED is non-nil, look for a named equation."
9838 (let* ((stored-list (org-table-get-stored-formulas))
9839 (name (car (rassoc (list (org-current-line)
9840 (org-table-current-column))
9841 org-table-named-field-locations)))
9842 (ref (format "@%d$%d" (org-table-current-dline)
9843 (org-table-current-column)))
9844 (refass (assoc ref stored-list))
9845 (scol (if named
9846 (if name name ref)
9847 (int-to-string (org-table-current-column))))
9848 (dummy (and (or name refass) (not named)
9849 (not (y-or-n-p "Replace field formula with column formula? " ))
9850 (error "Abort")))
9851 (name (or name ref))
9852 (org-table-may-need-update nil)
9853 (stored (cdr (assoc scol stored-list)))
9854 (eq (cond
9855 ((and stored equation (string-match "^ *=? *$" equation))
9856 stored)
9857 ((stringp equation)
9858 equation)
9859 (t (org-table-formula-from-user
9860 (read-string
9861 (org-table-formula-to-user
9862 (format "%s formula %s%s="
9863 (if named "Field" "Column")
9864 (if (member (string-to-char scol) '(?$ ?@)) "" "$")
9865 scol))
9866 (if stored (org-table-formula-to-user stored) "")
9867 'org-table-formula-history
9868 )))))
9869 mustsave)
9870 (when (not (string-match "\\S-" eq))
9871 ;; remove formula
9872 (setq stored-list (delq (assoc scol stored-list) stored-list))
9873 (org-table-store-formulas stored-list)
9874 (error "Formula removed"))
9875 (if (string-match "^ *=?" eq) (setq eq (replace-match "" t t eq)))
9876 (if (string-match " *$" eq) (setq eq (replace-match "" t t eq)))
9877 (if (and name (not named))
9878 ;; We set the column equation, delete the named one.
9879 (setq stored-list (delq (assoc name stored-list) stored-list)
9880 mustsave t))
9881 (if stored
9882 (setcdr (assoc scol stored-list) eq)
9883 (setq stored-list (cons (cons scol eq) stored-list)))
9884 (if (or mustsave (not (equal stored eq)))
9885 (org-table-store-formulas stored-list))
9886 eq))
9888 (defun org-table-store-formulas (alist)
9889 "Store the list of formulas below the current table."
9890 (setq alist (sort alist 'org-table-formula-less-p))
9891 (save-excursion
9892 (goto-char (org-table-end))
9893 (if (looking-at "\\([ \t]*\n\\)*#\\+TBLFM:\\(.*\n?\\)")
9894 (progn
9895 ;; don't overwrite TBLFM, we might use text properties to store stuff
9896 (goto-char (match-beginning 2))
9897 (delete-region (match-beginning 2) (match-end 0)))
9898 (insert "#+TBLFM:"))
9899 (insert " "
9900 (mapconcat (lambda (x)
9901 (concat
9902 (if (equal (string-to-char (car x)) ?@) "" "$")
9903 (car x) "=" (cdr x)))
9904 alist "::")
9905 "\n")))
9907 (defsubst org-table-formula-make-cmp-string (a)
9908 (when (string-match "^\\(@\\([0-9]+\\)\\)?\\(\\$?\\([0-9]+\\)\\)?\\(\\$?[a-zA-Z0-9]+\\)?" a)
9909 (concat
9910 (if (match-end 2) (format "@%05d" (string-to-number (match-string 2 a))) "")
9911 (if (match-end 4) (format "$%05d" (string-to-number (match-string 4 a))) "")
9912 (if (match-end 5) (concat "@@" (match-string 5 a))))))
9914 (defun org-table-formula-less-p (a b)
9915 "Compare two formulas for sorting."
9916 (let ((as (org-table-formula-make-cmp-string (car a)))
9917 (bs (org-table-formula-make-cmp-string (car b))))
9918 (and as bs (string< as bs))))
9920 (defun org-table-get-stored-formulas (&optional noerror)
9921 "Return an alist with the stored formulas directly after current table."
9922 (interactive)
9923 (let (scol eq eq-alist strings string seen)
9924 (save-excursion
9925 (goto-char (org-table-end))
9926 (when (looking-at "\\([ \t]*\n\\)*#\\+TBLFM: *\\(.*\\)")
9927 (setq strings (org-split-string (match-string 2) " *:: *"))
9928 (while (setq string (pop strings))
9929 (when (string-match "\\(@[0-9]+\\$[0-9]+\\|\\$\\([a-zA-Z0-9]+\\)\\) *= *\\(.*[^ \t]\\)" string)
9930 (setq scol (if (match-end 2)
9931 (match-string 2 string)
9932 (match-string 1 string))
9933 eq (match-string 3 string)
9934 eq-alist (cons (cons scol eq) eq-alist))
9935 (if (member scol seen)
9936 (if noerror
9937 (progn
9938 (message "Double definition `$%s=' in TBLFM line, please fix by hand" scol)
9939 (ding)
9940 (sit-for 2))
9941 (error "Double definition `$%s=' in TBLFM line, please fix by hand" scol))
9942 (push scol seen))))))
9943 (nreverse eq-alist)))
9945 (defun org-table-fix-formulas (key replace &optional limit delta remove)
9946 "Modify the equations after the table structure has been edited.
9947 KEY is \"@\" or \"$\". REPLACE is an alist of numbers to replace.
9948 For all numbers larger than LIMIT, shift them by DELTA."
9949 (save-excursion
9950 (goto-char (org-table-end))
9951 (when (looking-at "#\\+TBLFM:")
9952 (let ((re (concat key "\\([0-9]+\\)"))
9953 (re2
9954 (when remove
9955 (if (equal key "$")
9956 (format "\\(@[0-9]+\\)?\\$%d=.*?\\(::\\|$\\)" remove)
9957 (format "@%d\\$[0-9]+=.*?\\(::\\|$\\)" remove))))
9958 s n a)
9959 (when remove
9960 (while (re-search-forward re2 (point-at-eol) t)
9961 (replace-match "")))
9962 (while (re-search-forward re (point-at-eol) t)
9963 (setq s (match-string 1) n (string-to-number s))
9964 (cond
9965 ((setq a (assoc s replace))
9966 (replace-match (concat key (cdr a)) t t))
9967 ((and limit (> n limit))
9968 (replace-match (concat key (int-to-string (+ n delta))) t t))))))))
9970 (defun org-table-get-specials ()
9971 "Get the column names and local parameters for this table."
9972 (save-excursion
9973 (let ((beg (org-table-begin)) (end (org-table-end))
9974 names name fields fields1 field cnt
9975 c v l line col types dlines hlines)
9976 (setq org-table-column-names nil
9977 org-table-local-parameters nil
9978 org-table-named-field-locations nil
9979 org-table-current-begin-line nil
9980 org-table-current-begin-pos nil
9981 org-table-current-line-types nil)
9982 (goto-char beg)
9983 (when (re-search-forward "^[ \t]*| *! *\\(|.*\\)" end t)
9984 (setq names (org-split-string (match-string 1) " *| *")
9985 cnt 1)
9986 (while (setq name (pop names))
9987 (setq cnt (1+ cnt))
9988 (if (string-match "^[a-zA-Z][a-zA-Z0-9]*$" name)
9989 (push (cons name (int-to-string cnt)) org-table-column-names))))
9990 (setq org-table-column-names (nreverse org-table-column-names))
9991 (setq org-table-column-name-regexp
9992 (concat "\\$\\(" (mapconcat 'car org-table-column-names "\\|") "\\)\\>"))
9993 (goto-char beg)
9994 (while (re-search-forward "^[ \t]*| *\\$ *\\(|.*\\)" end t)
9995 (setq fields (org-split-string (match-string 1) " *| *"))
9996 (while (setq field (pop fields))
9997 (if (string-match "^\\([a-zA-Z][_a-zA-Z0-9]*\\|%\\) *= *\\(.*\\)" field)
9998 (push (cons (match-string 1 field) (match-string 2 field))
9999 org-table-local-parameters))))
10000 (goto-char beg)
10001 (while (re-search-forward "^[ \t]*| *\\([_^]\\) *\\(|.*\\)" end t)
10002 (setq c (match-string 1)
10003 fields (org-split-string (match-string 2) " *| *"))
10004 (save-excursion
10005 (beginning-of-line (if (equal c "_") 2 0))
10006 (setq line (org-current-line) col 1)
10007 (and (looking-at "^[ \t]*|[^|]*\\(|.*\\)")
10008 (setq fields1 (org-split-string (match-string 1) " *| *"))))
10009 (while (and fields1 (setq field (pop fields)))
10010 (setq v (pop fields1) col (1+ col))
10011 (when (and (stringp field) (stringp v)
10012 (string-match "^[a-zA-Z][a-zA-Z0-9]*$" field))
10013 (push (cons field v) org-table-local-parameters)
10014 (push (list field line col) org-table-named-field-locations))))
10015 ;; Analyse the line types
10016 (goto-char beg)
10017 (setq org-table-current-begin-line (org-current-line)
10018 org-table-current-begin-pos (point)
10019 l org-table-current-begin-line)
10020 (while (looking-at "[ \t]*|\\(-\\)?")
10021 (push (if (match-end 1) 'hline 'dline) types)
10022 (if (match-end 1) (push l hlines) (push l dlines))
10023 (beginning-of-line 2)
10024 (setq l (1+ l)))
10025 (setq org-table-current-line-types (apply 'vector (nreverse types))
10026 org-table-dlines (apply 'vector (cons nil (nreverse dlines)))
10027 org-table-hlines (apply 'vector (cons nil (nreverse hlines)))))))
10029 (defun org-table-maybe-eval-formula ()
10030 "Check if the current field starts with \"=\" or \":=\".
10031 If yes, store the formula and apply it."
10032 ;; We already know we are in a table. Get field will only return a formula
10033 ;; when appropriate. It might return a separator line, but no problem.
10034 (when org-table-formula-evaluate-inline
10035 (let* ((field (org-trim (or (org-table-get-field) "")))
10036 named eq)
10037 (when (string-match "^:?=\\(.*\\)" field)
10038 (setq named (equal (string-to-char field) ?:)
10039 eq (match-string 1 field))
10040 (if (or (fboundp 'calc-eval)
10041 (equal (substring eq 0 (min 2 (length eq))) "'("))
10042 (org-table-eval-formula (if named '(4) nil)
10043 (org-table-formula-from-user eq))
10044 (error "Calc does not seem to be installed, and is needed to evaluate the formula"))))))
10046 (defvar org-recalc-commands nil
10047 "List of commands triggering the recalculation of a line.
10048 Will be filled automatically during use.")
10050 (defvar org-recalc-marks
10051 '((" " . "Unmarked: no special line, no automatic recalculation")
10052 ("#" . "Automatically recalculate this line upon TAB, RET, and C-c C-c in the line")
10053 ("*" . "Recalculate only when entire table is recalculated with `C-u C-c *'")
10054 ("!" . "Column name definition line. Reference in formula as $name.")
10055 ("$" . "Parameter definition line name=value. Reference in formula as $name.")
10056 ("_" . "Names for values in row below this one.")
10057 ("^" . "Names for values in row above this one.")))
10059 (defun org-table-rotate-recalc-marks (&optional newchar)
10060 "Rotate the recalculation mark in the first column.
10061 If in any row, the first field is not consistent with a mark,
10062 insert a new column for the markers.
10063 When there is an active region, change all the lines in the region,
10064 after prompting for the marking character.
10065 After each change, a message will be displayed indicating the meaning
10066 of the new mark."
10067 (interactive)
10068 (unless (org-at-table-p) (error "Not at a table"))
10069 (let* ((marks (append (mapcar 'car org-recalc-marks) '(" ")))
10070 (beg (org-table-begin))
10071 (end (org-table-end))
10072 (l (org-current-line))
10073 (l1 (if (org-region-active-p) (org-current-line (region-beginning))))
10074 (l2 (if (org-region-active-p) (org-current-line (region-end))))
10075 (have-col
10076 (save-excursion
10077 (goto-char beg)
10078 (not (re-search-forward "^[ \t]*|[^-|][^|]*[^#!$*_^| \t][^|]*|" end t))))
10079 (col (org-table-current-column))
10080 (forcenew (car (assoc newchar org-recalc-marks)))
10081 epos new)
10082 (when l1
10083 (message "Change region to what mark? Type # * ! $ or SPC: ")
10084 (setq newchar (char-to-string (read-char-exclusive))
10085 forcenew (car (assoc newchar org-recalc-marks))))
10086 (if (and newchar (not forcenew))
10087 (error "Invalid NEWCHAR `%s' in `org-table-rotate-recalc-marks'"
10088 newchar))
10089 (if l1 (goto-line l1))
10090 (save-excursion
10091 (beginning-of-line 1)
10092 (unless (looking-at org-table-dataline-regexp)
10093 (error "Not at a table data line")))
10094 (unless have-col
10095 (org-table-goto-column 1)
10096 (org-table-insert-column)
10097 (org-table-goto-column (1+ col)))
10098 (setq epos (point-at-eol))
10099 (save-excursion
10100 (beginning-of-line 1)
10101 (org-table-get-field
10102 1 (if (looking-at "^[ \t]*| *\\([#!$*^_ ]\\) *|")
10103 (concat " "
10104 (setq new (or forcenew
10105 (cadr (member (match-string 1) marks))))
10106 " ")
10107 " # ")))
10108 (if (and l1 l2)
10109 (progn
10110 (goto-line l1)
10111 (while (progn (beginning-of-line 2) (not (= (org-current-line) l2)))
10112 (and (looking-at org-table-dataline-regexp)
10113 (org-table-get-field 1 (concat " " new " "))))
10114 (goto-line l1)))
10115 (if (not (= epos (point-at-eol))) (org-table-align))
10116 (goto-line l)
10117 (and (interactive-p) (message "%s" (cdr (assoc new org-recalc-marks))))))
10119 (defun org-table-maybe-recalculate-line ()
10120 "Recompute the current line if marked for it, and if we haven't just done it."
10121 (interactive)
10122 (and org-table-allow-automatic-line-recalculation
10123 (not (and (memq last-command org-recalc-commands)
10124 (equal org-last-recalc-line (org-current-line))))
10125 (save-excursion (beginning-of-line 1)
10126 (looking-at org-table-auto-recalculate-regexp))
10127 (org-table-recalculate) t))
10129 (defvar org-table-formula-debug nil
10130 "Non-nil means, debug table formulas.
10131 When nil, simply write \"#ERROR\" in corrupted fields.")
10132 (make-variable-buffer-local 'org-table-formula-debug)
10134 (defvar modes)
10135 (defsubst org-set-calc-mode (var &optional value)
10136 (if (stringp var)
10137 (setq var (assoc var '(("D" calc-angle-mode deg)
10138 ("R" calc-angle-mode rad)
10139 ("F" calc-prefer-frac t)
10140 ("S" calc-symbolic-mode t)))
10141 value (nth 2 var) var (nth 1 var)))
10142 (if (memq var modes)
10143 (setcar (cdr (memq var modes)) value)
10144 (cons var (cons value modes)))
10145 modes)
10147 (defun org-table-eval-formula (&optional arg equation
10148 suppress-align suppress-const
10149 suppress-store suppress-analysis)
10150 "Replace the table field value at the cursor by the result of a calculation.
10152 This function makes use of Dave Gillespie's Calc package, in my view the
10153 most exciting program ever written for GNU Emacs. So you need to have Calc
10154 installed in order to use this function.
10156 In a table, this command replaces the value in the current field with the
10157 result of a formula. It also installs the formula as the \"current\" column
10158 formula, by storing it in a special line below the table. When called
10159 with a `C-u' prefix, the current field must ba a named field, and the
10160 formula is installed as valid in only this specific field.
10162 When called with two `C-u' prefixes, insert the active equation
10163 for the field back into the current field, so that it can be
10164 edited there. This is useful in order to use \\[org-table-show-reference]
10165 to check the referenced fields.
10167 When called, the command first prompts for a formula, which is read in
10168 the minibuffer. Previously entered formulas are available through the
10169 history list, and the last used formula is offered as a default.
10170 These stored formulas are adapted correctly when moving, inserting, or
10171 deleting columns with the corresponding commands.
10173 The formula can be any algebraic expression understood by the Calc package.
10174 For details, see the Org-mode manual.
10176 This function can also be called from Lisp programs and offers
10177 additional arguments: EQUATION can be the formula to apply. If this
10178 argument is given, the user will not be prompted. SUPPRESS-ALIGN is
10179 used to speed-up recursive calls by by-passing unnecessary aligns.
10180 SUPPRESS-CONST suppresses the interpretation of constants in the
10181 formula, assuming that this has been done already outside the function.
10182 SUPPRESS-STORE means the formula should not be stored, either because
10183 it is already stored, or because it is a modified equation that should
10184 not overwrite the stored one."
10185 (interactive "P")
10186 (org-table-check-inside-data-field)
10187 (or suppress-analysis (org-table-get-specials))
10188 (if (equal arg '(16))
10189 (let ((eq (org-table-current-field-formula)))
10190 (or eq (error "No equation active for current field"))
10191 (org-table-get-field nil eq)
10192 (org-table-align)
10193 (setq org-table-may-need-update t))
10194 (let* (fields
10195 (ndown (if (integerp arg) arg 1))
10196 (org-table-automatic-realign nil)
10197 (case-fold-search nil)
10198 (down (> ndown 1))
10199 (formula (if (and equation suppress-store)
10200 equation
10201 (org-table-get-formula equation (equal arg '(4)))))
10202 (n0 (org-table-current-column))
10203 (modes (copy-sequence org-calc-default-modes))
10204 (numbers nil) ; was a variable, now fixed default
10205 (keep-empty nil)
10206 n form form0 bw fmt x ev orig c lispp literal)
10207 ;; Parse the format string. Since we have a lot of modes, this is
10208 ;; a lot of work. However, I think calc still uses most of the time.
10209 (if (string-match ";" formula)
10210 (let ((tmp (org-split-string formula ";")))
10211 (setq formula (car tmp)
10212 fmt (concat (cdr (assoc "%" org-table-local-parameters))
10213 (nth 1 tmp)))
10214 (while (string-match "\\([pnfse]\\)\\(-?[0-9]+\\)" fmt)
10215 (setq c (string-to-char (match-string 1 fmt))
10216 n (string-to-number (match-string 2 fmt)))
10217 (if (= c ?p)
10218 (setq modes (org-set-calc-mode 'calc-internal-prec n))
10219 (setq modes (org-set-calc-mode
10220 'calc-float-format
10221 (list (cdr (assoc c '((?n . float) (?f . fix)
10222 (?s . sci) (?e . eng))))
10223 n))))
10224 (setq fmt (replace-match "" t t fmt)))
10225 (if (string-match "[NT]" fmt)
10226 (setq numbers (equal (match-string 0 fmt) "N")
10227 fmt (replace-match "" t t fmt)))
10228 (if (string-match "L" fmt)
10229 (setq literal t
10230 fmt (replace-match "" t t fmt)))
10231 (if (string-match "E" fmt)
10232 (setq keep-empty t
10233 fmt (replace-match "" t t fmt)))
10234 (while (string-match "[DRFS]" fmt)
10235 (setq modes (org-set-calc-mode (match-string 0 fmt)))
10236 (setq fmt (replace-match "" t t fmt)))
10237 (unless (string-match "\\S-" fmt)
10238 (setq fmt nil))))
10239 (if (and (not suppress-const) org-table-formula-use-constants)
10240 (setq formula (org-table-formula-substitute-names formula)))
10241 (setq orig (or (get-text-property 1 :orig-formula formula) "?"))
10242 (while (> ndown 0)
10243 (setq fields (org-split-string
10244 (org-no-properties
10245 (buffer-substring (point-at-bol) (point-at-eol)))
10246 " *| *"))
10247 (if (eq numbers t)
10248 (setq fields (mapcar
10249 (lambda (x) (number-to-string (string-to-number x)))
10250 fields)))
10251 (setq ndown (1- ndown))
10252 (setq form (copy-sequence formula)
10253 lispp (and (> (length form) 2)(equal (substring form 0 2) "'(")))
10254 (if (and lispp literal) (setq lispp 'literal))
10255 ;; Check for old vertical references
10256 (setq form (org-rewrite-old-row-references form))
10257 ;; Insert complex ranges
10258 (while (string-match org-table-range-regexp form)
10259 (setq form
10260 (replace-match
10261 (save-match-data
10262 (org-table-make-reference
10263 (org-table-get-range (match-string 0 form) nil n0)
10264 keep-empty numbers lispp))
10265 t t form)))
10266 ;; Insert simple ranges
10267 (while (string-match "\\$\\([0-9]+\\)\\.\\.\\$\\([0-9]+\\)" form)
10268 (setq form
10269 (replace-match
10270 (save-match-data
10271 (org-table-make-reference
10272 (org-sublist
10273 fields (string-to-number (match-string 1 form))
10274 (string-to-number (match-string 2 form)))
10275 keep-empty numbers lispp))
10276 t t form)))
10277 (setq form0 form)
10278 ;; Insert the references to fields in same row
10279 (while (string-match "\\$\\([0-9]+\\)" form)
10280 (setq n (string-to-number (match-string 1 form))
10281 x (nth (1- (if (= n 0) n0 n)) fields))
10282 (unless x (error "Invalid field specifier \"%s\""
10283 (match-string 0 form)))
10284 (setq form (replace-match
10285 (save-match-data
10286 (org-table-make-reference x nil numbers lispp))
10287 t t form)))
10289 (if lispp
10290 (setq ev (condition-case nil
10291 (eval (eval (read form)))
10292 (error "#ERROR"))
10293 ev (if (numberp ev) (number-to-string ev) ev))
10294 (or (fboundp 'calc-eval)
10295 (error "Calc does not seem to be installed, and is needed to evaluate the formula"))
10296 (setq ev (calc-eval (cons form modes)
10297 (if numbers 'num))))
10299 (when org-table-formula-debug
10300 (with-output-to-temp-buffer "*Substitution History*"
10301 (princ (format "Substitution history of formula
10302 Orig: %s
10303 $xyz-> %s
10304 @r$c-> %s
10305 $1-> %s\n" orig formula form0 form))
10306 (if (listp ev)
10307 (princ (format " %s^\nError: %s"
10308 (make-string (car ev) ?\-) (nth 1 ev)))
10309 (princ (format "Result: %s\nFormat: %s\nFinal: %s"
10310 ev (or fmt "NONE")
10311 (if fmt (format fmt (string-to-number ev)) ev)))))
10312 (setq bw (get-buffer-window "*Substitution History*"))
10313 (shrink-window-if-larger-than-buffer bw)
10314 (unless (and (interactive-p) (not ndown))
10315 (unless (let (inhibit-redisplay)
10316 (y-or-n-p "Debugging Formula. Continue to next? "))
10317 (org-table-align)
10318 (error "Abort"))
10319 (delete-window bw)
10320 (message "")))
10321 (if (listp ev) (setq fmt nil ev "#ERROR"))
10322 (org-table-justify-field-maybe
10323 (if fmt (format fmt (string-to-number ev)) ev))
10324 (if (and down (> ndown 0) (looking-at ".*\n[ \t]*|[^-]"))
10325 (call-interactively 'org-return)
10326 (setq ndown 0)))
10327 (and down (org-table-maybe-recalculate-line))
10328 (or suppress-align (and org-table-may-need-update
10329 (org-table-align))))))
10331 (defun org-table-put-field-property (prop value)
10332 (save-excursion
10333 (put-text-property (progn (skip-chars-backward "^|") (point))
10334 (progn (skip-chars-forward "^|") (point))
10335 prop value)))
10337 (defun org-table-get-range (desc &optional tbeg col highlight)
10338 "Get a calc vector from a column, accorting to descriptor DESC.
10339 Optional arguments TBEG and COL can give the beginning of the table and
10340 the current column, to avoid unnecessary parsing.
10341 HIGHLIGHT means, just highlight the range."
10342 (if (not (equal (string-to-char desc) ?@))
10343 (setq desc (concat "@" desc)))
10344 (save-excursion
10345 (or tbeg (setq tbeg (org-table-begin)))
10346 (or col (setq col (org-table-current-column)))
10347 (let ((thisline (org-current-line))
10348 beg end c1 c2 r1 r2 rangep tmp)
10349 (unless (string-match org-table-range-regexp desc)
10350 (error "Invalid table range specifier `%s'" desc))
10351 (setq rangep (match-end 3)
10352 r1 (and (match-end 1) (match-string 1 desc))
10353 r2 (and (match-end 4) (match-string 4 desc))
10354 c1 (and (match-end 2) (substring (match-string 2 desc) 1))
10355 c2 (and (match-end 5) (substring (match-string 5 desc) 1)))
10357 (and c1 (setq c1 (+ (string-to-number c1)
10358 (if (memq (string-to-char c1) '(?- ?+)) col 0))))
10359 (and c2 (setq c2 (+ (string-to-number c2)
10360 (if (memq (string-to-char c2) '(?- ?+)) col 0))))
10361 (if (equal r1 "") (setq r1 nil))
10362 (if (equal r2 "") (setq r2 nil))
10363 (if r1 (setq r1 (org-table-get-descriptor-line r1)))
10364 (if r2 (setq r2 (org-table-get-descriptor-line r2)))
10365 ; (setq r2 (or r2 r1) c2 (or c2 c1))
10366 (if (not r1) (setq r1 thisline))
10367 (if (not r2) (setq r2 thisline))
10368 (if (not c1) (setq c1 col))
10369 (if (not c2) (setq c2 col))
10370 (if (or (not rangep) (and (= r1 r2) (= c1 c2)))
10371 ;; just one field
10372 (progn
10373 (goto-line r1)
10374 (while (not (looking-at org-table-dataline-regexp))
10375 (beginning-of-line 2))
10376 (prog1 (org-trim (org-table-get-field c1))
10377 (if highlight (org-table-highlight-rectangle (point) (point)))))
10378 ;; A range, return a vector
10379 ;; First sort the numbers to get a regular ractangle
10380 (if (< r2 r1) (setq tmp r1 r1 r2 r2 tmp))
10381 (if (< c2 c1) (setq tmp c1 c1 c2 c2 tmp))
10382 (goto-line r1)
10383 (while (not (looking-at org-table-dataline-regexp))
10384 (beginning-of-line 2))
10385 (org-table-goto-column c1)
10386 (setq beg (point))
10387 (goto-line r2)
10388 (while (not (looking-at org-table-dataline-regexp))
10389 (beginning-of-line 0))
10390 (org-table-goto-column c2)
10391 (setq end (point))
10392 (if highlight
10393 (org-table-highlight-rectangle
10394 beg (progn (skip-chars-forward "^|\n") (point))))
10395 ;; return string representation of calc vector
10396 (mapcar 'org-trim
10397 (apply 'append (org-table-copy-region beg end)))))))
10399 (defun org-table-get-descriptor-line (desc &optional cline bline table)
10400 "Analyze descriptor DESC and retrieve the corresponding line number.
10401 The cursor is currently in line CLINE, the table begins in line BLINE,
10402 and TABLE is a vector with line types."
10403 (if (string-match "^[0-9]+$" desc)
10404 (aref org-table-dlines (string-to-number desc))
10405 (setq cline (or cline (org-current-line))
10406 bline (or bline org-table-current-begin-line)
10407 table (or table org-table-current-line-types))
10408 (if (or
10409 (not (string-match "^\\(\\([-+]\\)?\\(I+\\)\\)?\\(\\([-+]\\)?\\([0-9]+\\)\\)?" desc))
10410 ;; 1 2 3 4 5 6
10411 (and (not (match-end 3)) (not (match-end 6)))
10412 (and (match-end 3) (match-end 6) (not (match-end 5))))
10413 (error "invalid row descriptor `%s'" desc))
10414 (let* ((hdir (and (match-end 2) (match-string 2 desc)))
10415 (hn (if (match-end 3) (- (match-end 3) (match-beginning 3)) nil))
10416 (odir (and (match-end 5) (match-string 5 desc)))
10417 (on (if (match-end 6) (string-to-number (match-string 6 desc))))
10418 (i (- cline bline))
10419 (rel (and (match-end 6)
10420 (or (and (match-end 1) (not (match-end 3)))
10421 (match-end 5)))))
10422 (if (and hn (not hdir))
10423 (progn
10424 (setq i 0 hdir "+")
10425 (if (eq (aref table 0) 'hline) (setq hn (1- hn)))))
10426 (if (and (not hn) on (not odir))
10427 (error "should never happen");;(aref org-table-dlines on)
10428 (if (and hn (> hn 0))
10429 (setq i (org-find-row-type table i 'hline (equal hdir "-") nil hn)))
10430 (if on
10431 (setq i (org-find-row-type table i 'dline (equal odir "-") rel on)))
10432 (+ bline i)))))
10434 (defun org-find-row-type (table i type backwards relative n)
10435 (let ((l (length table)))
10436 (while (> n 0)
10437 (while (and (setq i (+ i (if backwards -1 1)))
10438 (>= i 0) (< i l)
10439 (not (eq (aref table i) type))
10440 (if (and relative (eq (aref table i) 'hline))
10441 (progn (setq i (- i (if backwards -1 1)) n 1) nil)
10442 t)))
10443 (setq n (1- n)))
10444 (if (or (< i 0) (>= i l))
10445 (error "Row descriptior leads outside table")
10446 i)))
10448 (defun org-rewrite-old-row-references (s)
10449 (if (string-match "&[-+0-9I]" s)
10450 (error "Formula contains old &row reference, please rewrite using @-syntax")
10453 (defun org-table-make-reference (elements keep-empty numbers lispp)
10454 "Convert list ELEMENTS to something appropriate to insert into formula.
10455 KEEP-EMPTY indicated to keep empty fields, default is to skip them.
10456 NUMBERS indicates that everything should be converted to numbers.
10457 LISPP means to return something appropriate for a Lisp list."
10458 (if (stringp elements) ; just a single val
10459 (if lispp
10460 (if (eq lispp 'literal)
10461 elements
10462 (prin1-to-string (if numbers (string-to-number elements) elements)))
10463 (if (equal elements "") (setq elements "0"))
10464 (if numbers (number-to-string (string-to-number elements)) elements))
10465 (unless keep-empty
10466 (setq elements
10467 (delq nil
10468 (mapcar (lambda (x) (if (string-match "\\S-" x) x nil))
10469 elements))))
10470 (setq elements (or elements '("0")))
10471 (if lispp
10472 (mapconcat
10473 (lambda (x)
10474 (if (eq lispp 'literal)
10476 (prin1-to-string (if numbers (string-to-number x) x))))
10477 elements " ")
10478 (concat "[" (mapconcat
10479 (lambda (x)
10480 (if numbers (number-to-string (string-to-number x)) x))
10481 elements
10482 ",") "]"))))
10484 (defun org-table-recalculate (&optional all noalign)
10485 "Recalculate the current table line by applying all stored formulas.
10486 With prefix arg ALL, do this for all lines in the table."
10487 (interactive "P")
10488 (or (memq this-command org-recalc-commands)
10489 (setq org-recalc-commands (cons this-command org-recalc-commands)))
10490 (unless (org-at-table-p) (error "Not at a table"))
10491 (if (equal all '(16))
10492 (org-table-iterate)
10493 (org-table-get-specials)
10494 (let* ((eqlist (sort (org-table-get-stored-formulas)
10495 (lambda (a b) (string< (car a) (car b)))))
10496 (inhibit-redisplay (not debug-on-error))
10497 (line-re org-table-dataline-regexp)
10498 (thisline (org-current-line))
10499 (thiscol (org-table-current-column))
10500 beg end entry eqlnum eqlname eqlname1 eql (cnt 0) eq a name)
10501 ;; Insert constants in all formulas
10502 (setq eqlist
10503 (mapcar (lambda (x)
10504 (setcdr x (org-table-formula-substitute-names (cdr x)))
10506 eqlist))
10507 ;; Split the equation list
10508 (while (setq eq (pop eqlist))
10509 (if (<= (string-to-char (car eq)) ?9)
10510 (push eq eqlnum)
10511 (push eq eqlname)))
10512 (setq eqlnum (nreverse eqlnum) eqlname (nreverse eqlname))
10513 (if all
10514 (progn
10515 (setq end (move-marker (make-marker) (1+ (org-table-end))))
10516 (goto-char (setq beg (org-table-begin)))
10517 (if (re-search-forward org-table-calculate-mark-regexp end t)
10518 ;; This is a table with marked lines, compute selected lines
10519 (setq line-re org-table-recalculate-regexp)
10520 ;; Move forward to the first non-header line
10521 (if (and (re-search-forward org-table-dataline-regexp end t)
10522 (re-search-forward org-table-hline-regexp end t)
10523 (re-search-forward org-table-dataline-regexp end t))
10524 (setq beg (match-beginning 0))
10525 nil))) ;; just leave beg where it is
10526 (setq beg (point-at-bol)
10527 end (move-marker (make-marker) (1+ (point-at-eol)))))
10528 (goto-char beg)
10529 (and all (message "Re-applying formulas to full table..."))
10531 ;; First find the named fields, and mark them untouchanble
10532 (remove-text-properties beg end '(org-untouchable t))
10533 (while (setq eq (pop eqlname))
10534 (setq name (car eq)
10535 a (assoc name org-table-named-field-locations))
10536 (and (not a)
10537 (string-match "@\\([0-9]+\\)\\$\\([0-9]+\\)" name)
10538 (setq a (list name
10539 (aref org-table-dlines
10540 (string-to-number (match-string 1 name)))
10541 (string-to-number (match-string 2 name)))))
10542 (when (and a (or all (equal (nth 1 a) thisline)))
10543 (message "Re-applying formula to field: %s" name)
10544 (goto-line (nth 1 a))
10545 (org-table-goto-column (nth 2 a))
10546 (push (append a (list (cdr eq))) eqlname1)
10547 (org-table-put-field-property :org-untouchable t)))
10549 ;; Now evauluate the column formulas, but skip fields covered by
10550 ;; field formulas
10551 (goto-char beg)
10552 (while (re-search-forward line-re end t)
10553 (unless (string-match "^ *[_^!$/] *$" (org-table-get-field 1))
10554 ;; Unprotected line, recalculate
10555 (and all (message "Re-applying formulas to full table...(line %d)"
10556 (setq cnt (1+ cnt))))
10557 (setq org-last-recalc-line (org-current-line))
10558 (setq eql eqlnum)
10559 (while (setq entry (pop eql))
10560 (goto-line org-last-recalc-line)
10561 (org-table-goto-column (string-to-number (car entry)) nil 'force)
10562 (unless (get-text-property (point) :org-untouchable)
10563 (org-table-eval-formula nil (cdr entry)
10564 'noalign 'nocst 'nostore 'noanalysis)))))
10566 ;; Now evaluate the field formulas
10567 (while (setq eq (pop eqlname1))
10568 (message "Re-applying formula to field: %s" (car eq))
10569 (goto-line (nth 1 eq))
10570 (org-table-goto-column (nth 2 eq))
10571 (org-table-eval-formula nil (nth 3 eq) 'noalign 'nocst
10572 'nostore 'noanalysis))
10574 (goto-line thisline)
10575 (org-table-goto-column thiscol)
10576 (remove-text-properties (point-min) (point-max) '(org-untouchable t))
10577 (or noalign (and org-table-may-need-update (org-table-align))
10578 (and all (message "Re-applying formulas to %d lines...done" cnt)))
10580 ;; back to initial position
10581 (message "Re-applying formulas...done")
10582 (goto-line thisline)
10583 (org-table-goto-column thiscol)
10584 (or noalign (and org-table-may-need-update (org-table-align))
10585 (and all (message "Re-applying formulas...done"))))))
10587 (defun org-table-iterate (&optional arg)
10588 "Recalculate the table until it does not change anymore."
10589 (interactive "P")
10590 (let ((imax (if arg (prefix-numeric-value arg) 10))
10591 (i 0)
10592 (lasttbl (buffer-substring (org-table-begin) (org-table-end)))
10593 thistbl)
10594 (catch 'exit
10595 (while (< i imax)
10596 (setq i (1+ i))
10597 (org-table-recalculate 'all)
10598 (setq thistbl (buffer-substring (org-table-begin) (org-table-end)))
10599 (if (not (string= lasttbl thistbl))
10600 (setq lasttbl thistbl)
10601 (if (> i 1)
10602 (message "Convergence after %d iterations" i)
10603 (message "Table was already stable"))
10604 (throw 'exit t)))
10605 (error "No convergence after %d iterations" i))))
10607 (defun org-table-formula-substitute-names (f)
10608 "Replace $const with values in string F."
10609 (let ((start 0) a (f1 f) (pp (/= (string-to-char f) ?')))
10610 ;; First, check for column names
10611 (while (setq start (string-match org-table-column-name-regexp f start))
10612 (setq start (1+ start))
10613 (setq a (assoc (match-string 1 f) org-table-column-names))
10614 (setq f (replace-match (concat "$" (cdr a)) t t f)))
10615 ;; Parameters and constants
10616 (setq start 0)
10617 (while (setq start (string-match "\\$\\([a-zA-Z][_a-zA-Z0-9]*\\)" f start))
10618 (setq start (1+ start))
10619 (if (setq a (save-match-data
10620 (org-table-get-constant (match-string 1 f))))
10621 (setq f (replace-match
10622 (concat (if pp "(") a (if pp ")")) t t f))))
10623 (if org-table-formula-debug
10624 (put-text-property 0 (length f) :orig-formula f1 f))
10627 (defun org-table-get-constant (const)
10628 "Find the value for a parameter or constant in a formula.
10629 Parameters get priority."
10630 (or (cdr (assoc const org-table-local-parameters))
10631 (cdr (assoc const org-table-formula-constants-local))
10632 (cdr (assoc const org-table-formula-constants))
10633 (and (fboundp 'constants-get) (constants-get const))
10634 (and (string= (substring const 0 (min 5 (length const))) "PROP_")
10635 (org-entry-get nil (substring const 5) 'inherit))
10636 "#UNDEFINED_NAME"))
10638 (defvar org-table-fedit-map
10639 (let ((map (make-sparse-keymap)))
10640 (org-defkey map "\C-x\C-s" 'org-table-fedit-finish)
10641 (org-defkey map "\C-c\C-s" 'org-table-fedit-finish)
10642 (org-defkey map "\C-c\C-c" 'org-table-fedit-finish)
10643 (org-defkey map "\C-c\C-q" 'org-table-fedit-abort)
10644 (org-defkey map "\C-c?" 'org-table-show-reference)
10645 (org-defkey map [(meta shift up)] 'org-table-fedit-line-up)
10646 (org-defkey map [(meta shift down)] 'org-table-fedit-line-down)
10647 (org-defkey map [(shift up)] 'org-table-fedit-ref-up)
10648 (org-defkey map [(shift down)] 'org-table-fedit-ref-down)
10649 (org-defkey map [(shift left)] 'org-table-fedit-ref-left)
10650 (org-defkey map [(shift right)] 'org-table-fedit-ref-right)
10651 (org-defkey map [(meta up)] 'org-table-fedit-scroll-down)
10652 (org-defkey map [(meta down)] 'org-table-fedit-scroll)
10653 (org-defkey map [(meta tab)] 'lisp-complete-symbol)
10654 (org-defkey map "\M-\C-i" 'lisp-complete-symbol)
10655 (org-defkey map [(tab)] 'org-table-fedit-lisp-indent)
10656 (org-defkey map "\C-i" 'org-table-fedit-lisp-indent)
10657 (org-defkey map "\C-c\C-r" 'org-table-fedit-toggle-ref-type)
10658 (org-defkey map "\C-c}" 'org-table-fedit-toggle-coordinates)
10659 map))
10661 (easy-menu-define org-table-fedit-menu org-table-fedit-map "Org Edit Formulas Menu"
10662 '("Edit-Formulas"
10663 ["Finish and Install" org-table-fedit-finish t]
10664 ["Finish, Install, and Apply" (org-table-fedit-finish t) :keys "C-u C-c C-c"]
10665 ["Abort" org-table-fedit-abort t]
10666 "--"
10667 ["Pretty-Print Lisp Formula" org-table-fedit-lisp-indent t]
10668 ["Complete Lisp Symbol" lisp-complete-symbol t]
10669 "--"
10670 "Shift Reference at Point"
10671 ["Up" org-table-fedit-ref-up t]
10672 ["Down" org-table-fedit-ref-down t]
10673 ["Left" org-table-fedit-ref-left t]
10674 ["Right" org-table-fedit-ref-right t]
10676 "Change Test Row for Column Formulas"
10677 ["Up" org-table-fedit-line-up t]
10678 ["Down" org-table-fedit-line-down t]
10679 "--"
10680 ["Scroll Table Window" org-table-fedit-scroll t]
10681 ["Scroll Table Window down" org-table-fedit-scroll-down t]
10682 ["Show Table Grid" org-table-fedit-toggle-coordinates
10683 :style toggle :selected (with-current-buffer (marker-buffer org-pos)
10684 org-table-overlay-coordinates)]
10685 "--"
10686 ["Standard Refs (B3 instead of @3$2)" org-table-fedit-toggle-ref-type
10687 :style toggle :selected org-table-buffer-is-an]))
10689 (defvar org-pos)
10691 (defun org-table-edit-formulas ()
10692 "Edit the formulas of the current table in a separate buffer."
10693 (interactive)
10694 (when (save-excursion (beginning-of-line 1) (looking-at "#\\+TBLFM"))
10695 (beginning-of-line 0))
10696 (unless (org-at-table-p) (error "Not at a table"))
10697 (org-table-get-specials)
10698 (let ((key (org-table-current-field-formula 'key 'noerror))
10699 (eql (sort (org-table-get-stored-formulas 'noerror)
10700 'org-table-formula-less-p))
10701 (pos (move-marker (make-marker) (point)))
10702 (startline 1)
10703 (wc (current-window-configuration))
10704 (titles '((column . "# Column Formulas\n")
10705 (field . "# Field Formulas\n")
10706 (named . "# Named Field Formulas\n")))
10707 entry s type title)
10708 (org-switch-to-buffer-other-window "*Edit Formulas*")
10709 (erase-buffer)
10710 ;; Keep global-font-lock-mode from turning on font-lock-mode
10711 (let ((font-lock-global-modes '(not fundamental-mode)))
10712 (fundamental-mode))
10713 (org-set-local 'font-lock-global-modes (list 'not major-mode))
10714 (org-set-local 'org-pos pos)
10715 (org-set-local 'org-window-configuration wc)
10716 (use-local-map org-table-fedit-map)
10717 (org-add-hook 'post-command-hook 'org-table-fedit-post-command t t)
10718 (easy-menu-add org-table-fedit-menu)
10719 (setq startline (org-current-line))
10720 (while (setq entry (pop eql))
10721 (setq type (cond
10722 ((equal (string-to-char (car entry)) ?@) 'field)
10723 ((string-match "^[0-9]" (car entry)) 'column)
10724 (t 'named)))
10725 (when (setq title (assq type titles))
10726 (or (bobp) (insert "\n"))
10727 (insert (org-add-props (cdr title) nil 'face font-lock-comment-face))
10728 (setq titles (delq title titles)))
10729 (if (equal key (car entry)) (setq startline (org-current-line)))
10730 (setq s (concat (if (equal (string-to-char (car entry)) ?@) "" "$")
10731 (car entry) " = " (cdr entry) "\n"))
10732 (remove-text-properties 0 (length s) '(face nil) s)
10733 (insert s))
10734 (if (eq org-table-use-standard-references t)
10735 (org-table-fedit-toggle-ref-type))
10736 (goto-line startline)
10737 (message "Edit formulas and finish with `C-c C-c'. See menu for more commands.")))
10739 (defun org-table-fedit-post-command ()
10740 (when (not (memq this-command '(lisp-complete-symbol)))
10741 (let ((win (selected-window)))
10742 (save-excursion
10743 (condition-case nil
10744 (org-table-show-reference)
10745 (error nil))
10746 (select-window win)))))
10748 (defun org-table-formula-to-user (s)
10749 "Convert a formula from internal to user representation."
10750 (if (eq org-table-use-standard-references t)
10751 (org-table-convert-refs-to-an s)
10754 (defun org-table-formula-from-user (s)
10755 "Convert a formula from user to internal representation."
10756 (if org-table-use-standard-references
10757 (org-table-convert-refs-to-rc s)
10760 (defun org-table-convert-refs-to-rc (s)
10761 "Convert spreadsheet references from AB7 to @7$28.
10762 Works for single references, but also for entire formulas and even the
10763 full TBLFM line."
10764 (let ((start 0))
10765 (while (string-match "\\<\\([a-zA-Z]+\\)\\([0-9]+\\>\\|&\\)\\|\\(;[^\r\n:]+\\)" s start)
10766 (cond
10767 ((match-end 3)
10768 ;; format match, just advance
10769 (setq start (match-end 0)))
10770 ((and (> (match-beginning 0) 0)
10771 (equal ?. (aref s (max (1- (match-beginning 0)) 0)))
10772 (not (equal ?. (aref s (max (- (match-beginning 0) 2) 0)))))
10773 ;; 3.e5 or something like this.
10774 (setq start (match-end 0)))
10776 (setq start (match-beginning 0)
10777 s (replace-match
10778 (if (equal (match-string 2 s) "&")
10779 (format "$%d" (org-letters-to-number (match-string 1 s)))
10780 (format "@%d$%d"
10781 (string-to-number (match-string 2 s))
10782 (org-letters-to-number (match-string 1 s))))
10783 t t s)))))
10786 (defun org-table-convert-refs-to-an (s)
10787 "Convert spreadsheet references from to @7$28 to AB7.
10788 Works for single references, but also for entire formulas and even the
10789 full TBLFM line."
10790 (while (string-match "@\\([0-9]+\\)\\$\\([0-9]+\\)" s)
10791 (setq s (replace-match
10792 (format "%s%d"
10793 (org-number-to-letters
10794 (string-to-number (match-string 2 s)))
10795 (string-to-number (match-string 1 s)))
10796 t t s)))
10797 (while (string-match "\\(^\\|[^0-9a-zA-Z]\\)\\$\\([0-9]+\\)" s)
10798 (setq s (replace-match (concat "\\1"
10799 (org-number-to-letters
10800 (string-to-number (match-string 2 s))) "&")
10801 t nil s)))
10804 (defun org-letters-to-number (s)
10805 "Convert a base 26 number represented by letters into an integer.
10806 For example: AB -> 28."
10807 (let ((n 0))
10808 (setq s (upcase s))
10809 (while (> (length s) 0)
10810 (setq n (+ (* n 26) (string-to-char s) (- ?A) 1)
10811 s (substring s 1)))
10814 (defun org-number-to-letters (n)
10815 "Convert an integer into a base 26 number represented by letters.
10816 For example: 28 -> AB."
10817 (let ((s ""))
10818 (while (> n 0)
10819 (setq s (concat (char-to-string (+ (mod (1- n) 26) ?A)) s)
10820 n (/ (1- n) 26)))
10823 (defun org-table-fedit-convert-buffer (function)
10824 "Convert all references in this buffer, using FUNTION."
10825 (let ((line (org-current-line)))
10826 (goto-char (point-min))
10827 (while (not (eobp))
10828 (insert (funcall function (buffer-substring (point) (point-at-eol))))
10829 (delete-region (point) (point-at-eol))
10830 (or (eobp) (forward-char 1)))
10831 (goto-line line)))
10833 (defun org-table-fedit-toggle-ref-type ()
10834 "Convert all references in the buffer from B3 to @3$2 and back."
10835 (interactive)
10836 (org-set-local 'org-table-buffer-is-an (not org-table-buffer-is-an))
10837 (org-table-fedit-convert-buffer
10838 (if org-table-buffer-is-an
10839 'org-table-convert-refs-to-an 'org-table-convert-refs-to-rc))
10840 (message "Reference type switched to %s"
10841 (if org-table-buffer-is-an "A1 etc" "@row$column")))
10843 (defun org-table-fedit-ref-up ()
10844 "Shift the reference at point one row/hline up."
10845 (interactive)
10846 (org-table-fedit-shift-reference 'up))
10847 (defun org-table-fedit-ref-down ()
10848 "Shift the reference at point one row/hline down."
10849 (interactive)
10850 (org-table-fedit-shift-reference 'down))
10851 (defun org-table-fedit-ref-left ()
10852 "Shift the reference at point one field to the left."
10853 (interactive)
10854 (org-table-fedit-shift-reference 'left))
10855 (defun org-table-fedit-ref-right ()
10856 "Shift the reference at point one field to the right."
10857 (interactive)
10858 (org-table-fedit-shift-reference 'right))
10860 (defun org-table-fedit-shift-reference (dir)
10861 (cond
10862 ((org-at-regexp-p "\\(\\<[a-zA-Z]\\)&")
10863 (if (memq dir '(left right))
10864 (org-rematch-and-replace 1 (eq dir 'left))
10865 (error "Cannot shift reference in this direction")))
10866 ((org-at-regexp-p "\\(\\<[a-zA-Z]\\{1,2\\}\\)\\([0-9]+\\)")
10867 ;; A B3-like reference
10868 (if (memq dir '(up down))
10869 (org-rematch-and-replace 2 (eq dir 'up))
10870 (org-rematch-and-replace 1 (eq dir 'left))))
10871 ((org-at-regexp-p
10872 "\\(@\\|\\.\\.\\)\\([-+]?\\(I+\\>\\|[0-9]+\\)\\)\\(\\$\\([-+]?[0-9]+\\)\\)?")
10873 ;; An internal reference
10874 (if (memq dir '(up down))
10875 (org-rematch-and-replace 2 (eq dir 'up) (match-end 3))
10876 (org-rematch-and-replace 5 (eq dir 'left))))))
10878 (defun org-rematch-and-replace (n &optional decr hline)
10879 "Re-match the group N, and replace it with the shifted refrence."
10880 (or (match-end n) (error "Cannot shift reference in this direction"))
10881 (goto-char (match-beginning n))
10882 (and (looking-at (regexp-quote (match-string n)))
10883 (replace-match (org-shift-refpart (match-string 0) decr hline)
10884 t t)))
10886 (defun org-shift-refpart (ref &optional decr hline)
10887 "Shift a refrence part REF.
10888 If DECR is set, decrease the references row/column, else increase.
10889 If HLINE is set, this may be a hline reference, it certainly is not
10890 a translation reference."
10891 (save-match-data
10892 (let* ((sign (string-match "^[-+]" ref)) n)
10894 (if sign (setq sign (substring ref 0 1) ref (substring ref 1)))
10895 (cond
10896 ((and hline (string-match "^I+" ref))
10897 (setq n (string-to-number (concat sign (number-to-string (length ref)))))
10898 (setq n (+ n (if decr -1 1)))
10899 (if (= n 0) (setq n (+ n (if decr -1 1))))
10900 (if sign
10901 (setq sign (if (< n 0) "-" "+") n (abs n))
10902 (setq n (max 1 n)))
10903 (concat sign (make-string n ?I)))
10905 ((string-match "^[0-9]+" ref)
10906 (setq n (string-to-number (concat sign ref)))
10907 (setq n (+ n (if decr -1 1)))
10908 (if sign
10909 (concat (if (< n 0) "-" "+") (number-to-string (abs n)))
10910 (number-to-string (max 1 n))))
10912 ((string-match "^[a-zA-Z]+" ref)
10913 (org-number-to-letters
10914 (max 1 (+ (org-letters-to-number ref) (if decr -1 1)))))
10916 (t (error "Cannot shift reference"))))))
10918 (defun org-table-fedit-toggle-coordinates ()
10919 "Toggle the display of coordinates in the refrenced table."
10920 (interactive)
10921 (let ((pos (marker-position org-pos)))
10922 (with-current-buffer (marker-buffer org-pos)
10923 (save-excursion
10924 (goto-char pos)
10925 (org-table-toggle-coordinate-overlays)))))
10927 (defun org-table-fedit-finish (&optional arg)
10928 "Parse the buffer for formula definitions and install them.
10929 With prefix ARG, apply the new formulas to the table."
10930 (interactive "P")
10931 (org-table-remove-rectangle-highlight)
10932 (if org-table-use-standard-references
10933 (progn
10934 (org-table-fedit-convert-buffer 'org-table-convert-refs-to-rc)
10935 (setq org-table-buffer-is-an nil)))
10936 (let ((pos org-pos) eql var form)
10937 (goto-char (point-min))
10938 (while (re-search-forward
10939 "^\\(@[0-9]+\\$[0-9]+\\|\\$\\([a-zA-Z0-9]+\\)\\) *= *\\(.*\\(\n[ \t]+.*$\\)*\\)"
10940 nil t)
10941 (setq var (if (match-end 2) (match-string 2) (match-string 1))
10942 form (match-string 3))
10943 (setq form (org-trim form))
10944 (when (not (equal form ""))
10945 (while (string-match "[ \t]*\n[ \t]*" form)
10946 (setq form (replace-match " " t t form)))
10947 (when (assoc var eql)
10948 (error "Double formulas for %s" var))
10949 (push (cons var form) eql)))
10950 (setq org-pos nil)
10951 (set-window-configuration org-window-configuration)
10952 (select-window (get-buffer-window (marker-buffer pos)))
10953 (goto-char pos)
10954 (unless (org-at-table-p)
10955 (error "Lost table position - cannot install formulae"))
10956 (org-table-store-formulas eql)
10957 (move-marker pos nil)
10958 (kill-buffer "*Edit Formulas*")
10959 (if arg
10960 (org-table-recalculate 'all)
10961 (message "New formulas installed - press C-u C-c C-c to apply."))))
10963 (defun org-table-fedit-abort ()
10964 "Abort editing formulas, without installing the changes."
10965 (interactive)
10966 (org-table-remove-rectangle-highlight)
10967 (let ((pos org-pos))
10968 (set-window-configuration org-window-configuration)
10969 (select-window (get-buffer-window (marker-buffer pos)))
10970 (goto-char pos)
10971 (move-marker pos nil)
10972 (message "Formula editing aborted without installing changes")))
10974 (defun org-table-fedit-lisp-indent ()
10975 "Pretty-print and re-indent Lisp expressions in the Formula Editor."
10976 (interactive)
10977 (let ((pos (point)) beg end ind)
10978 (beginning-of-line 1)
10979 (cond
10980 ((looking-at "[ \t]")
10981 (goto-char pos)
10982 (call-interactively 'lisp-indent-line))
10983 ((looking-at "[$&@0-9a-zA-Z]+ *= *[^ \t\n']") (goto-char pos))
10984 ((not (fboundp 'pp-buffer))
10985 (error "Cannot pretty-print. Command `pp-buffer' is not available."))
10986 ((looking-at "[$&@0-9a-zA-Z]+ *= *'(")
10987 (goto-char (- (match-end 0) 2))
10988 (setq beg (point))
10989 (setq ind (make-string (current-column) ?\ ))
10990 (condition-case nil (forward-sexp 1)
10991 (error
10992 (error "Cannot pretty-print Lisp expression: Unbalanced parenthesis")))
10993 (setq end (point))
10994 (save-restriction
10995 (narrow-to-region beg end)
10996 (if (eq last-command this-command)
10997 (progn
10998 (goto-char (point-min))
10999 (setq this-command nil)
11000 (while (re-search-forward "[ \t]*\n[ \t]*" nil t)
11001 (replace-match " ")))
11002 (pp-buffer)
11003 (untabify (point-min) (point-max))
11004 (goto-char (1+ (point-min)))
11005 (while (re-search-forward "^." nil t)
11006 (beginning-of-line 1)
11007 (insert ind))
11008 (goto-char (point-max))
11009 (backward-delete-char 1)))
11010 (goto-char beg))
11011 (t nil))))
11013 (defvar org-show-positions nil)
11015 (defun org-table-show-reference (&optional local)
11016 "Show the location/value of the $ expression at point."
11017 (interactive)
11018 (org-table-remove-rectangle-highlight)
11019 (catch 'exit
11020 (let ((pos (if local (point) org-pos))
11021 (face2 'highlight)
11022 (org-inhibit-highlight-removal t)
11023 (win (selected-window))
11024 (org-show-positions nil)
11025 var name e what match dest)
11026 (if local (org-table-get-specials))
11027 (setq what (cond
11028 ((or (org-at-regexp-p org-table-range-regexp2)
11029 (org-at-regexp-p org-table-translate-regexp)
11030 (org-at-regexp-p org-table-range-regexp))
11031 (setq match
11032 (save-match-data
11033 (org-table-convert-refs-to-rc (match-string 0))))
11034 'range)
11035 ((org-at-regexp-p "\\$[a-zA-Z][a-zA-Z0-9]*") 'name)
11036 ((org-at-regexp-p "\\$[0-9]+") 'column)
11037 ((not local) nil)
11038 (t (error "No reference at point")))
11039 match (and what (or match (match-string 0))))
11040 (when (and match (not (equal (match-beginning 0) (point-at-bol))))
11041 (org-table-add-rectangle-overlay (match-beginning 0) (match-end 0)
11042 'secondary-selection))
11043 (org-add-hook 'before-change-functions
11044 'org-table-remove-rectangle-highlight)
11045 (if (eq what 'name) (setq var (substring match 1)))
11046 (when (eq what 'range)
11047 (or (equal (string-to-char match) ?@) (setq match (concat "@" match)))
11048 (setq match (org-table-formula-substitute-names match)))
11049 (unless local
11050 (save-excursion
11051 (end-of-line 1)
11052 (re-search-backward "^\\S-" nil t)
11053 (beginning-of-line 1)
11054 (when (looking-at "\\(\\$[0-9a-zA-Z]+\\|@[0-9]+\\$[0-9]+\\|[a-zA-Z]+\\([0-9]+\\|&\\)\\) *=")
11055 (setq dest
11056 (save-match-data
11057 (org-table-convert-refs-to-rc (match-string 1))))
11058 (org-table-add-rectangle-overlay
11059 (match-beginning 1) (match-end 1) face2))))
11060 (if (and (markerp pos) (marker-buffer pos))
11061 (if (get-buffer-window (marker-buffer pos))
11062 (select-window (get-buffer-window (marker-buffer pos)))
11063 (org-switch-to-buffer-other-window (get-buffer-window
11064 (marker-buffer pos)))))
11065 (goto-char pos)
11066 (org-table-force-dataline)
11067 (when dest
11068 (setq name (substring dest 1))
11069 (cond
11070 ((string-match "^\\$[a-zA-Z][a-zA-Z0-9]*" dest)
11071 (setq e (assoc name org-table-named-field-locations))
11072 (goto-line (nth 1 e))
11073 (org-table-goto-column (nth 2 e)))
11074 ((string-match "^@\\([0-9]+\\)\\$\\([0-9]+\\)" dest)
11075 (let ((l (string-to-number (match-string 1 dest)))
11076 (c (string-to-number (match-string 2 dest))))
11077 (goto-line (aref org-table-dlines l))
11078 (org-table-goto-column c)))
11079 (t (org-table-goto-column (string-to-number name))))
11080 (move-marker pos (point))
11081 (org-table-highlight-rectangle nil nil face2))
11082 (cond
11083 ((equal dest match))
11084 ((not match))
11085 ((eq what 'range)
11086 (condition-case nil
11087 (save-excursion
11088 (org-table-get-range match nil nil 'highlight))
11089 (error nil)))
11090 ((setq e (assoc var org-table-named-field-locations))
11091 (goto-line (nth 1 e))
11092 (org-table-goto-column (nth 2 e))
11093 (org-table-highlight-rectangle (point) (point))
11094 (message "Named field, column %d of line %d" (nth 2 e) (nth 1 e)))
11095 ((setq e (assoc var org-table-column-names))
11096 (org-table-goto-column (string-to-number (cdr e)))
11097 (org-table-highlight-rectangle (point) (point))
11098 (goto-char (org-table-begin))
11099 (if (re-search-forward (concat "^[ \t]*| *! *.*?| *\\(" var "\\) *|")
11100 (org-table-end) t)
11101 (progn
11102 (goto-char (match-beginning 1))
11103 (org-table-highlight-rectangle)
11104 (message "Named column (column %s)" (cdr e)))
11105 (error "Column name not found")))
11106 ((eq what 'column)
11107 ;; column number
11108 (org-table-goto-column (string-to-number (substring match 1)))
11109 (org-table-highlight-rectangle (point) (point))
11110 (message "Column %s" (substring match 1)))
11111 ((setq e (assoc var org-table-local-parameters))
11112 (goto-char (org-table-begin))
11113 (if (re-search-forward (concat "^[ \t]*| *\\$ *.*?| *\\(" var "=\\)") nil t)
11114 (progn
11115 (goto-char (match-beginning 1))
11116 (org-table-highlight-rectangle)
11117 (message "Local parameter."))
11118 (error "Parameter not found")))
11120 (cond
11121 ((not var) (error "No reference at point"))
11122 ((setq e (assoc var org-table-formula-constants-local))
11123 (message "Local Constant: $%s=%s in #+CONSTANTS line."
11124 var (cdr e)))
11125 ((setq e (assoc var org-table-formula-constants))
11126 (message "Constant: $%s=%s in `org-table-formula-constants'."
11127 var (cdr e)))
11128 ((setq e (and (fboundp 'constants-get) (constants-get var)))
11129 (message "Constant: $%s=%s, from `constants.el'%s."
11130 var e (format " (%s units)" constants-unit-system)))
11131 (t (error "Undefined name $%s" var)))))
11132 (goto-char pos)
11133 (when (and org-show-positions
11134 (not (memq this-command '(org-table-fedit-scroll
11135 org-table-fedit-scroll-down))))
11136 (push pos org-show-positions)
11137 (push org-table-current-begin-pos org-show-positions)
11138 (let ((min (apply 'min org-show-positions))
11139 (max (apply 'max org-show-positions)))
11140 (goto-char min) (recenter 0)
11141 (goto-char max)
11142 (or (pos-visible-in-window-p max) (recenter -1))))
11143 (select-window win))))
11145 (defun org-table-force-dataline ()
11146 "Make sure the cursor is in a dataline in a table."
11147 (unless (save-excursion
11148 (beginning-of-line 1)
11149 (looking-at org-table-dataline-regexp))
11150 (let* ((re org-table-dataline-regexp)
11151 (p1 (save-excursion (re-search-forward re nil 'move)))
11152 (p2 (save-excursion (re-search-backward re nil 'move))))
11153 (cond ((and p1 p2)
11154 (goto-char (if (< (abs (- p1 (point))) (abs (- p2 (point))))
11155 p1 p2)))
11156 ((or p1 p2) (goto-char (or p1 p2)))
11157 (t (error "No table dataline around here"))))))
11159 (defun org-table-fedit-line-up ()
11160 "Move cursor one line up in the window showing the table."
11161 (interactive)
11162 (org-table-fedit-move 'previous-line))
11164 (defun org-table-fedit-line-down ()
11165 "Move cursor one line down in the window showing the table."
11166 (interactive)
11167 (org-table-fedit-move 'next-line))
11169 (defun org-table-fedit-move (command)
11170 "Move the cursor in the window shoinw the table.
11171 Use COMMAND to do the motion, repeat if necessary to end up in a data line."
11172 (let ((org-table-allow-automatic-line-recalculation nil)
11173 (pos org-pos) (win (selected-window)) p)
11174 (select-window (get-buffer-window (marker-buffer org-pos)))
11175 (setq p (point))
11176 (call-interactively command)
11177 (while (and (org-at-table-p)
11178 (org-at-table-hline-p))
11179 (call-interactively command))
11180 (or (org-at-table-p) (goto-char p))
11181 (move-marker pos (point))
11182 (select-window win)))
11184 (defun org-table-fedit-scroll (N)
11185 (interactive "p")
11186 (let ((other-window-scroll-buffer (marker-buffer org-pos)))
11187 (scroll-other-window N)))
11189 (defun org-table-fedit-scroll-down (N)
11190 (interactive "p")
11191 (org-table-fedit-scroll (- N)))
11193 (defvar org-table-rectangle-overlays nil)
11195 (defun org-table-add-rectangle-overlay (beg end &optional face)
11196 "Add a new overlay."
11197 (let ((ov (org-make-overlay beg end)))
11198 (org-overlay-put ov 'face (or face 'secondary-selection))
11199 (push ov org-table-rectangle-overlays)))
11201 (defun org-table-highlight-rectangle (&optional beg end face)
11202 "Highlight rectangular region in a table."
11203 (setq beg (or beg (point)) end (or end (point)))
11204 (let ((b (min beg end))
11205 (e (max beg end))
11206 l1 c1 l2 c2 tmp)
11207 (and (boundp 'org-show-positions)
11208 (setq org-show-positions (cons b (cons e org-show-positions))))
11209 (goto-char (min beg end))
11210 (setq l1 (org-current-line)
11211 c1 (org-table-current-column))
11212 (goto-char (max beg end))
11213 (setq l2 (org-current-line)
11214 c2 (org-table-current-column))
11215 (if (> c1 c2) (setq tmp c1 c1 c2 c2 tmp))
11216 (goto-line l1)
11217 (beginning-of-line 1)
11218 (loop for line from l1 to l2 do
11219 (when (looking-at org-table-dataline-regexp)
11220 (org-table-goto-column c1)
11221 (skip-chars-backward "^|\n") (setq beg (point))
11222 (org-table-goto-column c2)
11223 (skip-chars-forward "^|\n") (setq end (point))
11224 (org-table-add-rectangle-overlay beg end face))
11225 (beginning-of-line 2))
11226 (goto-char b))
11227 (add-hook 'before-change-functions 'org-table-remove-rectangle-highlight))
11229 (defun org-table-remove-rectangle-highlight (&rest ignore)
11230 "Remove the rectangle overlays."
11231 (unless org-inhibit-highlight-removal
11232 (remove-hook 'before-change-functions 'org-table-remove-rectangle-highlight)
11233 (mapc 'org-delete-overlay org-table-rectangle-overlays)
11234 (setq org-table-rectangle-overlays nil)))
11236 (defvar org-table-coordinate-overlays nil
11237 "Collects the cooordinate grid overlays, so that they can be removed.")
11238 (make-variable-buffer-local 'org-table-coordinate-overlays)
11240 (defun org-table-overlay-coordinates ()
11241 "Add overlays to the table at point, to show row/column coordinates."
11242 (interactive)
11243 (mapc 'org-delete-overlay org-table-coordinate-overlays)
11244 (setq org-table-coordinate-overlays nil)
11245 (save-excursion
11246 (let ((id 0) (ih 0) hline eol s1 s2 str ic ov beg)
11247 (goto-char (org-table-begin))
11248 (while (org-at-table-p)
11249 (setq eol (point-at-eol))
11250 (setq ov (org-make-overlay (point-at-bol) (1+ (point-at-bol))))
11251 (push ov org-table-coordinate-overlays)
11252 (setq hline (looking-at org-table-hline-regexp))
11253 (setq str (if hline (format "I*%-2d" (setq ih (1+ ih)))
11254 (format "%4d" (setq id (1+ id)))))
11255 (org-overlay-before-string ov str 'org-special-keyword 'evaporate)
11256 (when hline
11257 (setq ic 0)
11258 (while (re-search-forward "[+|]\\(-+\\)" eol t)
11259 (setq beg (1+ (match-beginning 0))
11260 ic (1+ ic)
11261 s1 (concat "$" (int-to-string ic))
11262 s2 (org-number-to-letters ic)
11263 str (if (eq org-table-use-standard-references t) s2 s1))
11264 (setq ov (org-make-overlay beg (+ beg (length str))))
11265 (push ov org-table-coordinate-overlays)
11266 (org-overlay-display ov str 'org-special-keyword 'evaporate)))
11267 (beginning-of-line 2)))))
11269 (defun org-table-toggle-coordinate-overlays ()
11270 "Toggle the display of Row/Column numbers in tables."
11271 (interactive)
11272 (setq org-table-overlay-coordinates (not org-table-overlay-coordinates))
11273 (message "Row/Column number display turned %s"
11274 (if org-table-overlay-coordinates "on" "off"))
11275 (if (and (org-at-table-p) org-table-overlay-coordinates)
11276 (org-table-align))
11277 (unless org-table-overlay-coordinates
11278 (mapc 'org-delete-overlay org-table-coordinate-overlays)
11279 (setq org-table-coordinate-overlays nil)))
11281 (defun org-table-toggle-formula-debugger ()
11282 "Toggle the formula debugger in tables."
11283 (interactive)
11284 (setq org-table-formula-debug (not org-table-formula-debug))
11285 (message "Formula debugging has been turned %s"
11286 (if org-table-formula-debug "on" "off")))
11288 ;;; The orgtbl minor mode
11290 ;; Define a minor mode which can be used in other modes in order to
11291 ;; integrate the org-mode table editor.
11293 ;; This is really a hack, because the org-mode table editor uses several
11294 ;; keys which normally belong to the major mode, for example the TAB and
11295 ;; RET keys. Here is how it works: The minor mode defines all the keys
11296 ;; necessary to operate the table editor, but wraps the commands into a
11297 ;; function which tests if the cursor is currently inside a table. If that
11298 ;; is the case, the table editor command is executed. However, when any of
11299 ;; those keys is used outside a table, the function uses `key-binding' to
11300 ;; look up if the key has an associated command in another currently active
11301 ;; keymap (minor modes, major mode, global), and executes that command.
11302 ;; There might be problems if any of the keys used by the table editor is
11303 ;; otherwise used as a prefix key.
11305 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
11306 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
11307 ;; addresses this by checking explicitly for both bindings.
11309 ;; The optimized version (see variable `orgtbl-optimized') takes over
11310 ;; all keys which are bound to `self-insert-command' in the *global map*.
11311 ;; Some modes bind other commands to simple characters, for example
11312 ;; AUCTeX binds the double quote to `Tex-insert-quote'. With orgtbl-mode
11313 ;; active, this binding is ignored inside tables and replaced with a
11314 ;; modified self-insert.
11316 (defvar orgtbl-mode nil
11317 "Variable controlling `orgtbl-mode', a minor mode enabling the `org-mode'
11318 table editor in arbitrary modes.")
11319 (make-variable-buffer-local 'orgtbl-mode)
11321 (defvar orgtbl-mode-map (make-keymap)
11322 "Keymap for `orgtbl-mode'.")
11324 ;;;###autoload
11325 (defun turn-on-orgtbl ()
11326 "Unconditionally turn on `orgtbl-mode'."
11327 (orgtbl-mode 1))
11329 (defvar org-old-auto-fill-inhibit-regexp nil
11330 "Local variable used by `orgtbl-mode'")
11332 (defconst orgtbl-line-start-regexp "[ \t]*\\(|\\|#\\+\\(TBLFM\\|ORGTBL\\):\\)"
11333 "Matches a line belonging to an orgtbl.")
11335 (defconst orgtbl-extra-font-lock-keywords
11336 (list (list (concat "^" orgtbl-line-start-regexp ".*")
11337 0 (quote 'org-table) 'prepend))
11338 "Extra font-lock-keywords to be added when orgtbl-mode is active.")
11340 ;;;###autoload
11341 (defun orgtbl-mode (&optional arg)
11342 "The `org-mode' table editor as a minor mode for use in other modes."
11343 (interactive)
11344 (if (org-mode-p)
11345 ;; Exit without error, in case some hook functions calls this
11346 ;; by accident in org-mode.
11347 (message "Orgtbl-mode is not useful in org-mode, command ignored")
11348 (setq orgtbl-mode
11349 (if arg (> (prefix-numeric-value arg) 0) (not orgtbl-mode)))
11350 (if orgtbl-mode
11351 (progn
11352 (and (orgtbl-setup) (defun orgtbl-setup () nil))
11353 ;; Make sure we are first in minor-mode-map-alist
11354 (let ((c (assq 'orgtbl-mode minor-mode-map-alist)))
11355 (and c (setq minor-mode-map-alist
11356 (cons c (delq c minor-mode-map-alist)))))
11357 (org-set-local (quote org-table-may-need-update) t)
11358 (org-add-hook 'before-change-functions 'org-before-change-function
11359 nil 'local)
11360 (org-set-local 'org-old-auto-fill-inhibit-regexp
11361 auto-fill-inhibit-regexp)
11362 (org-set-local 'auto-fill-inhibit-regexp
11363 (if auto-fill-inhibit-regexp
11364 (concat orgtbl-line-start-regexp "\\|"
11365 auto-fill-inhibit-regexp)
11366 orgtbl-line-start-regexp))
11367 (org-add-to-invisibility-spec '(org-cwidth))
11368 (when (fboundp 'font-lock-add-keywords)
11369 (font-lock-add-keywords nil orgtbl-extra-font-lock-keywords)
11370 (org-restart-font-lock))
11371 (easy-menu-add orgtbl-mode-menu)
11372 (run-hooks 'orgtbl-mode-hook))
11373 (setq auto-fill-inhibit-regexp org-old-auto-fill-inhibit-regexp)
11374 (org-cleanup-narrow-column-properties)
11375 (org-remove-from-invisibility-spec '(org-cwidth))
11376 (remove-hook 'before-change-functions 'org-before-change-function t)
11377 (when (fboundp 'font-lock-remove-keywords)
11378 (font-lock-remove-keywords nil orgtbl-extra-font-lock-keywords)
11379 (org-restart-font-lock))
11380 (easy-menu-remove orgtbl-mode-menu)
11381 (force-mode-line-update 'all))))
11383 (defun org-cleanup-narrow-column-properties ()
11384 "Remove all properties related to narrow-column invisibility."
11385 (let ((s 1))
11386 (while (setq s (text-property-any s (point-max)
11387 'display org-narrow-column-arrow))
11388 (remove-text-properties s (1+ s) '(display t)))
11389 (setq s 1)
11390 (while (setq s (text-property-any s (point-max) 'org-cwidth 1))
11391 (remove-text-properties s (1+ s) '(org-cwidth t)))
11392 (setq s 1)
11393 (while (setq s (text-property-any s (point-max) 'invisible 'org-cwidth))
11394 (remove-text-properties s (1+ s) '(invisible t)))))
11396 ;; Install it as a minor mode.
11397 (put 'orgtbl-mode :included t)
11398 (put 'orgtbl-mode :menu-tag "Org Table Mode")
11399 (add-minor-mode 'orgtbl-mode " OrgTbl" orgtbl-mode-map)
11401 (defun orgtbl-make-binding (fun n &rest keys)
11402 "Create a function for binding in the table minor mode.
11403 FUN is the command to call inside a table. N is used to create a unique
11404 command name. KEYS are keys that should be checked in for a command
11405 to execute outside of tables."
11406 (eval
11407 (list 'defun
11408 (intern (concat "orgtbl-hijacker-command-" (int-to-string n)))
11409 '(arg)
11410 (concat "In tables, run `" (symbol-name fun) "'.\n"
11411 "Outside of tables, run the binding of `"
11412 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
11413 "'.")
11414 '(interactive "p")
11415 (list 'if
11416 '(org-at-table-p)
11417 (list 'call-interactively (list 'quote fun))
11418 (list 'let '(orgtbl-mode)
11419 (list 'call-interactively
11420 (append '(or)
11421 (mapcar (lambda (k)
11422 (list 'key-binding k))
11423 keys)
11424 '('orgtbl-error))))))))
11426 (defun orgtbl-error ()
11427 "Error when there is no default binding for a table key."
11428 (interactive)
11429 (error "This key has no function outside tables"))
11431 (defun orgtbl-setup ()
11432 "Setup orgtbl keymaps."
11433 (let ((nfunc 0)
11434 (bindings
11435 (list
11436 '([(meta shift left)] org-table-delete-column)
11437 '([(meta left)] org-table-move-column-left)
11438 '([(meta right)] org-table-move-column-right)
11439 '([(meta shift right)] org-table-insert-column)
11440 '([(meta shift up)] org-table-kill-row)
11441 '([(meta shift down)] org-table-insert-row)
11442 '([(meta up)] org-table-move-row-up)
11443 '([(meta down)] org-table-move-row-down)
11444 '("\C-c\C-w" org-table-cut-region)
11445 '("\C-c\M-w" org-table-copy-region)
11446 '("\C-c\C-y" org-table-paste-rectangle)
11447 '("\C-c-" org-table-insert-hline)
11448 '("\C-c}" org-table-toggle-coordinate-overlays)
11449 '("\C-c{" org-table-toggle-formula-debugger)
11450 '("\C-m" org-table-next-row)
11451 '([(shift return)] org-table-copy-down)
11452 '("\C-c\C-q" org-table-wrap-region)
11453 '("\C-c?" org-table-field-info)
11454 '("\C-c " org-table-blank-field)
11455 '("\C-c+" org-table-sum)
11456 '("\C-c=" org-table-eval-formula)
11457 '("\C-c'" org-table-edit-formulas)
11458 '("\C-c`" org-table-edit-field)
11459 '("\C-c*" org-table-recalculate)
11460 '("\C-c|" org-table-create-or-convert-from-region)
11461 '("\C-c^" org-table-sort-lines)
11462 '([(control ?#)] org-table-rotate-recalc-marks)))
11463 elt key fun cmd)
11464 (while (setq elt (pop bindings))
11465 (setq nfunc (1+ nfunc))
11466 (setq key (org-key (car elt))
11467 fun (nth 1 elt)
11468 cmd (orgtbl-make-binding fun nfunc key))
11469 (org-defkey orgtbl-mode-map key cmd))
11471 ;; Special treatment needed for TAB and RET
11472 (org-defkey orgtbl-mode-map [(return)]
11473 (orgtbl-make-binding 'orgtbl-ret 100 [(return)] "\C-m"))
11474 (org-defkey orgtbl-mode-map "\C-m"
11475 (orgtbl-make-binding 'orgtbl-ret 101 "\C-m" [(return)]))
11477 (org-defkey orgtbl-mode-map [(tab)]
11478 (orgtbl-make-binding 'orgtbl-tab 102 [(tab)] "\C-i"))
11479 (org-defkey orgtbl-mode-map "\C-i"
11480 (orgtbl-make-binding 'orgtbl-tab 103 "\C-i" [(tab)]))
11482 (org-defkey orgtbl-mode-map [(shift tab)]
11483 (orgtbl-make-binding 'org-table-previous-field 104
11484 [(shift tab)] [(tab)] "\C-i"))
11486 (org-defkey orgtbl-mode-map "\M-\C-m"
11487 (orgtbl-make-binding 'org-table-wrap-region 105
11488 "\M-\C-m" [(meta return)]))
11489 (org-defkey orgtbl-mode-map [(meta return)]
11490 (orgtbl-make-binding 'org-table-wrap-region 106
11491 [(meta return)] "\M-\C-m"))
11493 (org-defkey orgtbl-mode-map "\C-c\C-c" 'orgtbl-ctrl-c-ctrl-c)
11494 (when orgtbl-optimized
11495 ;; If the user wants maximum table support, we need to hijack
11496 ;; some standard editing functions
11497 (org-remap orgtbl-mode-map
11498 'self-insert-command 'orgtbl-self-insert-command
11499 'delete-char 'org-delete-char
11500 'delete-backward-char 'org-delete-backward-char)
11501 (org-defkey orgtbl-mode-map "|" 'org-force-self-insert))
11502 (easy-menu-define orgtbl-mode-menu orgtbl-mode-map "OrgTbl menu"
11503 '("OrgTbl"
11504 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p) :keys "C-c C-c"]
11505 ["Next Field" org-cycle :active (org-at-table-p) :keys "TAB"]
11506 ["Previous Field" org-shifttab :active (org-at-table-p) :keys "S-TAB"]
11507 ["Next Row" org-return :active (org-at-table-p) :keys "RET"]
11508 "--"
11509 ["Blank Field" org-table-blank-field :active (org-at-table-p) :keys "C-c SPC"]
11510 ["Edit Field" org-table-edit-field :active (org-at-table-p) :keys "C-c ` "]
11511 ["Copy Field from Above"
11512 org-table-copy-down :active (org-at-table-p) :keys "S-RET"]
11513 "--"
11514 ("Column"
11515 ["Move Column Left" org-metaleft :active (org-at-table-p) :keys "M-<left>"]
11516 ["Move Column Right" org-metaright :active (org-at-table-p) :keys "M-<right>"]
11517 ["Delete Column" org-shiftmetaleft :active (org-at-table-p) :keys "M-S-<left>"]
11518 ["Insert Column" org-shiftmetaright :active (org-at-table-p) :keys "M-S-<right>"])
11519 ("Row"
11520 ["Move Row Up" org-metaup :active (org-at-table-p) :keys "M-<up>"]
11521 ["Move Row Down" org-metadown :active (org-at-table-p) :keys "M-<down>"]
11522 ["Delete Row" org-shiftmetaup :active (org-at-table-p) :keys "M-S-<up>"]
11523 ["Insert Row" org-shiftmetadown :active (org-at-table-p) :keys "M-S-<down>"]
11524 ["Sort lines in region" org-table-sort-lines (org-at-table-p) :keys "C-c ^"]
11525 "--"
11526 ["Insert Hline" org-table-insert-hline :active (org-at-table-p) :keys "C-c -"])
11527 ("Rectangle"
11528 ["Copy Rectangle" org-copy-special :active (org-at-table-p)]
11529 ["Cut Rectangle" org-cut-special :active (org-at-table-p)]
11530 ["Paste Rectangle" org-paste-special :active (org-at-table-p)]
11531 ["Fill Rectangle" org-table-wrap-region :active (org-at-table-p)])
11532 "--"
11533 ("Radio tables"
11534 ["Insert table template" orgtbl-insert-radio-table
11535 (assq major-mode orgtbl-radio-table-templates)]
11536 ["Comment/uncomment table" orgtbl-toggle-comment t])
11537 "--"
11538 ["Set Column Formula" org-table-eval-formula :active (org-at-table-p) :keys "C-c ="]
11539 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
11540 ["Edit Formulas" org-table-edit-formulas :active (org-at-table-p) :keys "C-c '"]
11541 ["Recalculate line" org-table-recalculate :active (org-at-table-p) :keys "C-c *"]
11542 ["Recalculate all" (org-table-recalculate '(4)) :active (org-at-table-p) :keys "C-u C-c *"]
11543 ["Iterate all" (org-table-recalculate '(16)) :active (org-at-table-p) :keys "C-u C-u C-c *"]
11544 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks :active (org-at-table-p) :keys "C-c #"]
11545 ["Sum Column/Rectangle" org-table-sum
11546 :active (or (org-at-table-p) (org-region-active-p)) :keys "C-c +"]
11547 ["Which Column?" org-table-current-column :active (org-at-table-p) :keys "C-c ?"]
11548 ["Debug Formulas"
11549 org-table-toggle-formula-debugger :active (org-at-table-p)
11550 :keys "C-c {"
11551 :style toggle :selected org-table-formula-debug]
11552 ["Show Col/Row Numbers"
11553 org-table-toggle-coordinate-overlays :active (org-at-table-p)
11554 :keys "C-c }"
11555 :style toggle :selected org-table-overlay-coordinates]
11559 (defun orgtbl-ctrl-c-ctrl-c (arg)
11560 "If the cursor is inside a table, realign the table.
11561 It it is a table to be sent away to a receiver, do it.
11562 With prefix arg, also recompute table."
11563 (interactive "P")
11564 (let ((pos (point)) action)
11565 (save-excursion
11566 (beginning-of-line 1)
11567 (setq action (cond ((looking-at "#\\+ORGTBL:.*\n[ \t]*|") (match-end 0))
11568 ((looking-at "[ \t]*|") pos)
11569 ((looking-at "#\\+TBLFM:") 'recalc))))
11570 (cond
11571 ((integerp action)
11572 (goto-char action)
11573 (org-table-maybe-eval-formula)
11574 (if arg
11575 (call-interactively 'org-table-recalculate)
11576 (org-table-maybe-recalculate-line))
11577 (call-interactively 'org-table-align)
11578 (orgtbl-send-table 'maybe))
11579 ((eq action 'recalc)
11580 (save-excursion
11581 (beginning-of-line 1)
11582 (skip-chars-backward " \r\n\t")
11583 (if (org-at-table-p)
11584 (org-call-with-arg 'org-table-recalculate t))))
11585 (t (let (orgtbl-mode)
11586 (call-interactively (key-binding "\C-c\C-c")))))))
11588 (defun orgtbl-tab (arg)
11589 "Justification and field motion for `orgtbl-mode'."
11590 (interactive "P")
11591 (if arg (org-table-edit-field t)
11592 (org-table-justify-field-maybe)
11593 (org-table-next-field)))
11595 (defun orgtbl-ret ()
11596 "Justification and field motion for `orgtbl-mode'."
11597 (interactive)
11598 (org-table-justify-field-maybe)
11599 (org-table-next-row))
11601 (defun orgtbl-self-insert-command (N)
11602 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
11603 If the cursor is in a table looking at whitespace, the whitespace is
11604 overwritten, and the table is not marked as requiring realignment."
11605 (interactive "p")
11606 (if (and (org-at-table-p)
11608 (and org-table-auto-blank-field
11609 (member last-command
11610 '(orgtbl-hijacker-command-100
11611 orgtbl-hijacker-command-101
11612 orgtbl-hijacker-command-102
11613 orgtbl-hijacker-command-103
11614 orgtbl-hijacker-command-104
11615 orgtbl-hijacker-command-105))
11616 (org-table-blank-field))
11618 (eq N 1)
11619 (looking-at "[^|\n]* +|"))
11620 (let (org-table-may-need-update)
11621 (goto-char (1- (match-end 0)))
11622 (delete-backward-char 1)
11623 (goto-char (match-beginning 0))
11624 (self-insert-command N))
11625 (setq org-table-may-need-update t)
11626 (let (orgtbl-mode)
11627 (call-interactively (key-binding (vector last-input-event))))))
11629 (defun org-force-self-insert (N)
11630 "Needed to enforce self-insert under remapping."
11631 (interactive "p")
11632 (self-insert-command N))
11634 (defvar orgtbl-exp-regexp "^\\([-+]?[0-9][0-9.]*\\)[eE]\\([-+]?[0-9]+\\)$"
11635 "Regula expression matching exponentials as produced by calc.")
11637 (defvar org-table-clean-did-remove-column nil)
11639 (defun orgtbl-export (table target)
11640 (let ((func (intern (concat "orgtbl-to-" (symbol-name target))))
11641 (lines (org-split-string table "[ \t]*\n[ \t]*"))
11642 org-table-last-alignment org-table-last-column-widths
11643 maxcol column)
11644 (if (not (fboundp func))
11645 (error "Cannot export orgtbl table to %s" target))
11646 (setq lines (org-table-clean-before-export lines))
11647 (setq table
11648 (mapcar
11649 (lambda (x)
11650 (if (string-match org-table-hline-regexp x)
11651 'hline
11652 (org-split-string (org-trim x) "\\s-*|\\s-*")))
11653 lines))
11654 (setq maxcol (apply 'max (mapcar (lambda (x) (if (listp x) (length x) 0))
11655 table)))
11656 (loop for i from (1- maxcol) downto 0 do
11657 (setq column (mapcar (lambda (x) (if (listp x) (nth i x) nil)) table))
11658 (setq column (delq nil column))
11659 (push (apply 'max (mapcar 'string-width column)) org-table-last-column-widths)
11660 (push (> (/ (apply '+ (mapcar (lambda (x) (if (string-match org-table-number-regexp x) 1 0)) column)) maxcol) org-table-number-fraction) org-table-last-alignment))
11661 (funcall func table nil)))
11663 (defun orgtbl-send-table (&optional maybe)
11664 "Send a tranformed version of this table to the receiver position.
11665 With argument MAYBE, fail quietly if no transformation is defined for
11666 this table."
11667 (interactive)
11668 (catch 'exit
11669 (unless (org-at-table-p) (error "Not at a table"))
11670 ;; when non-interactive, we assume align has just happened.
11671 (when (interactive-p) (org-table-align))
11672 (save-excursion
11673 (goto-char (org-table-begin))
11674 (beginning-of-line 0)
11675 (unless (looking-at "#\\+ORGTBL: *SEND +\\([a-zA-Z0-9_]+\\) +\\([^ \t\r\n]+\\)\\( +.*\\)?")
11676 (if maybe
11677 (throw 'exit nil)
11678 (error "Don't know how to transform this table."))))
11679 (let* ((name (match-string 1))
11681 (transform (intern (match-string 2)))
11682 (params (if (match-end 3) (read (concat "(" (match-string 3) ")"))))
11683 (skip (plist-get params :skip))
11684 (skipcols (plist-get params :skipcols))
11685 (txt (buffer-substring-no-properties
11686 (org-table-begin) (org-table-end)))
11687 (lines (nthcdr (or skip 0) (org-split-string txt "[ \t]*\n[ \t]*")))
11688 (lines (org-table-clean-before-export lines))
11689 (i0 (if org-table-clean-did-remove-column 2 1))
11690 (table (mapcar
11691 (lambda (x)
11692 (if (string-match org-table-hline-regexp x)
11693 'hline
11694 (org-remove-by-index
11695 (org-split-string (org-trim x) "\\s-*|\\s-*")
11696 skipcols i0)))
11697 lines))
11698 (fun (if (= i0 2) 'cdr 'identity))
11699 (org-table-last-alignment
11700 (org-remove-by-index (funcall fun org-table-last-alignment)
11701 skipcols i0))
11702 (org-table-last-column-widths
11703 (org-remove-by-index (funcall fun org-table-last-column-widths)
11704 skipcols i0)))
11706 (unless (fboundp transform)
11707 (error "No such transformation function %s" transform))
11708 (setq txt (funcall transform table params))
11709 ;; Find the insertion place
11710 (save-excursion
11711 (goto-char (point-min))
11712 (unless (re-search-forward
11713 (concat "BEGIN RECEIVE ORGTBL +" name "\\([ \t]\\|$\\)") nil t)
11714 (error "Don't know where to insert translated table"))
11715 (goto-char (match-beginning 0))
11716 (beginning-of-line 2)
11717 (setq beg (point))
11718 (unless (re-search-forward (concat "END RECEIVE ORGTBL +" name) nil t)
11719 (error "Cannot find end of insertion region"))
11720 (beginning-of-line 1)
11721 (delete-region beg (point))
11722 (goto-char beg)
11723 (insert txt "\n"))
11724 (message "Table converted and installed at receiver location"))))
11726 (defun org-remove-by-index (list indices &optional i0)
11727 "Remove the elements in LIST with indices in INDICES.
11728 First element has index 0, or I0 if given."
11729 (if (not indices)
11730 list
11731 (if (integerp indices) (setq indices (list indices)))
11732 (setq i0 (1- (or i0 0)))
11733 (delq :rm (mapcar (lambda (x)
11734 (setq i0 (1+ i0))
11735 (if (memq i0 indices) :rm x))
11736 list))))
11738 (defun orgtbl-toggle-comment ()
11739 "Comment or uncomment the orgtbl at point."
11740 (interactive)
11741 (let* ((re1 (concat "^" (regexp-quote comment-start) orgtbl-line-start-regexp))
11742 (re2 (concat "^" orgtbl-line-start-regexp))
11743 (commented (save-excursion (beginning-of-line 1)
11744 (cond ((looking-at re1) t)
11745 ((looking-at re2) nil)
11746 (t (error "Not at an org table")))))
11747 (re (if commented re1 re2))
11748 beg end)
11749 (save-excursion
11750 (beginning-of-line 1)
11751 (while (looking-at re) (beginning-of-line 0))
11752 (beginning-of-line 2)
11753 (setq beg (point))
11754 (while (looking-at re) (beginning-of-line 2))
11755 (setq end (point)))
11756 (comment-region beg end (if commented '(4) nil))))
11758 (defun orgtbl-insert-radio-table ()
11759 "Insert a radio table template appropriate for this major mode."
11760 (interactive)
11761 (let* ((e (assq major-mode orgtbl-radio-table-templates))
11762 (txt (nth 1 e))
11763 name pos)
11764 (unless e (error "No radio table setup defined for %s" major-mode))
11765 (setq name (read-string "Table name: "))
11766 (while (string-match "%n" txt)
11767 (setq txt (replace-match name t t txt)))
11768 (or (bolp) (insert "\n"))
11769 (setq pos (point))
11770 (insert txt)
11771 (goto-char pos)))
11773 (defun org-get-param (params header i sym &optional hsym)
11774 "Get parameter value for symbol SYM.
11775 If this is a header line, actually get the value for the symbol with an
11776 additional \"h\" inserted after the colon.
11777 If the value is a protperty list, get the element for the current column.
11778 Assumes variables VAL, PARAMS, HEAD and I to be scoped into the function."
11779 (let ((val (plist-get params sym)))
11780 (and hsym header (setq val (or (plist-get params hsym) val)))
11781 (if (consp val) (plist-get val i) val)))
11783 (defun orgtbl-to-generic (table params)
11784 "Convert the orgtbl-mode TABLE to some other format.
11785 This generic routine can be used for many standard cases.
11786 TABLE is a list, each entry either the symbol `hline' for a horizontal
11787 separator line, or a list of fields for that line.
11788 PARAMS is a property list of parameters that can influence the conversion.
11789 For the generic converter, some parameters are obligatory: You need to
11790 specify either :lfmt, or all of (:lstart :lend :sep). If you do not use
11791 :splice, you must have :tstart and :tend.
11793 Valid parameters are
11795 :tstart String to start the table. Ignored when :splice is t.
11796 :tend String to end the table. Ignored when :splice is t.
11798 :splice When set to t, return only table body lines, don't wrap
11799 them into :tstart and :tend. Default is nil.
11801 :hline String to be inserted on horizontal separation lines.
11802 May be nil to ignore hlines.
11804 :lstart String to start a new table line.
11805 :lend String to end a table line
11806 :sep Separator between two fields
11807 :lfmt Format for entire line, with enough %s to capture all fields.
11808 If this is present, :lstart, :lend, and :sep are ignored.
11809 :fmt A format to be used to wrap the field, should contain
11810 %s for the original field value. For example, to wrap
11811 everything in dollars, you could use :fmt \"$%s$\".
11812 This may also be a property list with column numbers and
11813 formats. For example :fmt (2 \"$%s$\" 4 \"%s%%\")
11815 :hlstart :hlend :hlsep :hlfmt :hfmt
11816 Same as above, specific for the header lines in the table.
11817 All lines before the first hline are treated as header.
11818 If any of these is not present, the data line value is used.
11820 :efmt Use this format to print numbers with exponentials.
11821 The format should have %s twice for inserting mantissa
11822 and exponent, for example \"%s\\\\times10^{%s}\". This
11823 may also be a property list with column numbers and
11824 formats. :fmt will still be applied after :efmt.
11826 In addition to this, the parameters :skip and :skipcols are always handled
11827 directly by `orgtbl-send-table'. See manual."
11828 (interactive)
11829 (let* ((p params)
11830 (splicep (plist-get p :splice))
11831 (hline (plist-get p :hline))
11832 rtn line i fm efm lfmt h)
11834 ;; Do we have a header?
11835 (if (and (not splicep) (listp (car table)) (memq 'hline table))
11836 (setq h t))
11838 ;; Put header
11839 (unless splicep
11840 (push (or (plist-get p :tstart) "ERROR: no :tstart") rtn))
11842 ;; Now loop over all lines
11843 (while (setq line (pop table))
11844 (if (eq line 'hline)
11845 ;; A horizontal separator line
11846 (progn (if hline (push hline rtn))
11847 (setq h nil)) ; no longer in header
11848 ;; A normal line. Convert the fields, push line onto the result list
11849 (setq i 0)
11850 (setq line
11851 (mapcar
11852 (lambda (f)
11853 (setq i (1+ i)
11854 fm (org-get-param p h i :fmt :hfmt)
11855 efm (org-get-param p h i :efmt))
11856 (if (and efm (string-match orgtbl-exp-regexp f))
11857 (setq f (format
11858 efm (match-string 1 f) (match-string 2 f))))
11859 (if fm (setq f (format fm f)))
11861 line))
11862 (if (setq lfmt (org-get-param p h i :lfmt :hlfmt))
11863 (push (apply 'format lfmt line) rtn)
11864 (push (concat
11865 (org-get-param p h i :lstart :hlstart)
11866 (mapconcat 'identity line (org-get-param p h i :sep :hsep))
11867 (org-get-param p h i :lend :hlend))
11868 rtn))))
11870 (unless splicep
11871 (push (or (plist-get p :tend) "ERROR: no :tend") rtn))
11873 (mapconcat 'identity (nreverse rtn) "\n")))
11875 (defun orgtbl-to-latex (table params)
11876 "Convert the orgtbl-mode TABLE to LaTeX.
11877 TABLE is a list, each entry either the symbol `hline' for a horizontal
11878 separator line, or a list of fields for that line.
11879 PARAMS is a property list of parameters that can influence the conversion.
11880 Supports all parameters from `orgtbl-to-generic'. Most important for
11881 LaTeX are:
11883 :splice When set to t, return only table body lines, don't wrap
11884 them into a tabular environment. Default is nil.
11886 :fmt A format to be used to wrap the field, should contain %s for the
11887 original field value. For example, to wrap everything in dollars,
11888 use :fmt \"$%s$\". This may also be a property list with column
11889 numbers and formats. For example :fmt (2 \"$%s$\" 4 \"%s%%\")
11891 :efmt Format for transforming numbers with exponentials. The format
11892 should have %s twice for inserting mantissa and exponent, for
11893 example \"%s\\\\times10^{%s}\". LaTeX default is \"%s\\\\,(%s)\".
11894 This may also be a property list with column numbers and formats.
11896 The general parameters :skip and :skipcols have already been applied when
11897 this function is called."
11898 (let* ((alignment (mapconcat (lambda (x) (if x "r" "l"))
11899 org-table-last-alignment ""))
11900 (params2
11901 (list
11902 :tstart (concat "\\begin{tabular}{" alignment "}")
11903 :tend "\\end{tabular}"
11904 :lstart "" :lend " \\\\" :sep " & "
11905 :efmt "%s\\,(%s)" :hline "\\hline")))
11906 (orgtbl-to-generic table (org-combine-plists params2 params))))
11908 (defun orgtbl-to-html (table params)
11909 "Convert the orgtbl-mode TABLE to LaTeX.
11910 TABLE is a list, each entry either the symbol `hline' for a horizontal
11911 separator line, or a list of fields for that line.
11912 PARAMS is a property list of parameters that can influence the conversion.
11913 Currently this function recognizes the following parameters:
11915 :splice When set to t, return only table body lines, don't wrap
11916 them into a <table> environment. Default is nil.
11918 The general parameters :skip and :skipcols have already been applied when
11919 this function is called. The function does *not* use `orgtbl-to-generic',
11920 so you cannot specify parameters for it."
11921 (let* ((splicep (plist-get params :splice))
11922 html)
11923 ;; Just call the formatter we already have
11924 ;; We need to make text lines for it, so put the fields back together.
11925 (setq html (org-format-org-table-html
11926 (mapcar
11927 (lambda (x)
11928 (if (eq x 'hline)
11929 "|----+----|"
11930 (concat "| " (mapconcat 'identity x " | ") " |")))
11931 table)
11932 splicep))
11933 (if (string-match "\n+\\'" html)
11934 (setq html (replace-match "" t t html)))
11935 html))
11937 (defun orgtbl-to-texinfo (table params)
11938 "Convert the orgtbl-mode TABLE to TeXInfo.
11939 TABLE is a list, each entry either the symbol `hline' for a horizontal
11940 separator line, or a list of fields for that line.
11941 PARAMS is a property list of parameters that can influence the conversion.
11942 Supports all parameters from `orgtbl-to-generic'. Most important for
11943 TeXInfo are:
11945 :splice nil/t When set to t, return only table body lines, don't wrap
11946 them into a multitable environment. Default is nil.
11948 :fmt fmt A format to be used to wrap the field, should contain
11949 %s for the original field value. For example, to wrap
11950 everything in @kbd{}, you could use :fmt \"@kbd{%s}\".
11951 This may also be a property list with column numbers and
11952 formats. For example :fmt (2 \"@kbd{%s}\" 4 \"@code{%s}\").
11954 :cf \"f1 f2..\" The column fractions for the table. By default these
11955 are computed automatically from the width of the columns
11956 under org-mode.
11958 The general parameters :skip and :skipcols have already been applied when
11959 this function is called."
11960 (let* ((total (float (apply '+ org-table-last-column-widths)))
11961 (colfrac (or (plist-get params :cf)
11962 (mapconcat
11963 (lambda (x) (format "%.3f" (/ (float x) total)))
11964 org-table-last-column-widths " ")))
11965 (params2
11966 (list
11967 :tstart (concat "@multitable @columnfractions " colfrac)
11968 :tend "@end multitable"
11969 :lstart "@item " :lend "" :sep " @tab "
11970 :hlstart "@headitem ")))
11971 (orgtbl-to-generic table (org-combine-plists params2 params))))
11973 ;;;; Link Stuff
11975 ;;; Link abbreviations
11977 (defun org-link-expand-abbrev (link)
11978 "Apply replacements as defined in `org-link-abbrev-alist."
11979 (if (string-match "^\\([a-zA-Z][-_a-zA-Z0-9]*\\)\\(::?\\(.*\\)\\)?$" link)
11980 (let* ((key (match-string 1 link))
11981 (as (or (assoc key org-link-abbrev-alist-local)
11982 (assoc key org-link-abbrev-alist)))
11983 (tag (and (match-end 2) (match-string 3 link)))
11984 rpl)
11985 (if (not as)
11986 link
11987 (setq rpl (cdr as))
11988 (cond
11989 ((symbolp rpl) (funcall rpl tag))
11990 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
11991 (t (concat rpl tag)))))
11992 link))
11994 ;;; Storing and inserting links
11996 (defvar org-insert-link-history nil
11997 "Minibuffer history for links inserted with `org-insert-link'.")
11999 (defvar org-stored-links nil
12000 "Contains the links stored with `org-store-link'.")
12002 (defvar org-store-link-plist nil
12003 "Plist with info about the most recently link created with `org-store-link'.")
12005 (defvar org-link-protocols nil
12006 "Link protocols added to Org-mode using `org-add-link-type'.")
12008 (defvar org-store-link-functions nil
12009 "List of functions that are called to create and store a link.
12010 Each function will be called in turn until one returns a non-nil
12011 value. Each function should check if it is responsible for creating
12012 this link (for example by looking at the major mode).
12013 If not, it must exit and return nil.
12014 If yes, it should return a non-nil value after a calling
12015 `org-store-link-props' with a list of properties and values.
12016 Special properties are:
12018 :type The link prefix. like \"http\". This must be given.
12019 :link The link, like \"http://www.astro.uva.nl/~dominik\".
12020 This is obligatory as well.
12021 :description Optional default description for the second pair
12022 of brackets in an Org-mode link. The user can still change
12023 this when inserting this link into an Org-mode buffer.
12025 In addition to these, any additional properties can be specified
12026 and then used in remember templates.")
12028 (defun org-add-link-type (type &optional follow publish)
12029 "Add TYPE to the list of `org-link-types'.
12030 Re-compute all regular expressions depending on `org-link-types'
12031 FOLLOW and PUBLISH are two functions. Both take the link path as
12032 an argument.
12033 FOLLOW should do whatever is necessary to follow the link, for example
12034 to find a file or display a mail message.
12036 PUBLISH takes the path and retuns the string that should be used when
12037 this document is published. FIMXE: This is actually not yet implemented."
12038 (add-to-list 'org-link-types type t)
12039 (org-make-link-regexps)
12040 (add-to-list 'org-link-protocols
12041 (list type follow publish)))
12043 (defun org-add-agenda-custom-command (entry)
12044 "Replace or add a command in `org-agenda-custom-commands'.
12045 This is mostly for hacking and trying a new command - once the command
12046 works you probably want to add it to `org-agenda-custom-commands' for good."
12047 (let ((ass (assoc (car entry) org-agenda-custom-commands)))
12048 (if ass
12049 (setcdr ass (cdr entry))
12050 (push entry org-agenda-custom-commands))))
12052 ;;;###autoload
12053 (defun org-store-link (arg)
12054 "\\<org-mode-map>Store an org-link to the current location.
12055 This link is added to `org-stored-links' and can later be inserted
12056 into an org-buffer with \\[org-insert-link].
12058 For some link types, a prefix arg is interpreted:
12059 For links to usenet articles, arg negates `org-usenet-links-prefer-google'.
12060 For file links, arg negates `org-context-in-file-links'."
12061 (interactive "P")
12062 (setq org-store-link-plist nil) ; reset
12063 (let (link cpltxt desc description search txt)
12064 (cond
12066 ((run-hook-with-args-until-success 'org-store-link-functions)
12067 (setq link (plist-get org-store-link-plist :link)
12068 desc (or (plist-get org-store-link-plist :description) link)))
12070 ((eq major-mode 'bbdb-mode)
12071 (let ((name (bbdb-record-name (bbdb-current-record)))
12072 (company (bbdb-record-getprop (bbdb-current-record) 'company)))
12073 (setq cpltxt (concat "bbdb:" (or name company))
12074 link (org-make-link cpltxt))
12075 (org-store-link-props :type "bbdb" :name name :company company)))
12077 ((eq major-mode 'Info-mode)
12078 (setq link (org-make-link "info:"
12079 (file-name-nondirectory Info-current-file)
12080 ":" Info-current-node))
12081 (setq cpltxt (concat (file-name-nondirectory Info-current-file)
12082 ":" Info-current-node))
12083 (org-store-link-props :type "info" :file Info-current-file
12084 :node Info-current-node))
12086 ((eq major-mode 'calendar-mode)
12087 (let ((cd (calendar-cursor-to-date)))
12088 (setq link
12089 (format-time-string
12090 (car org-time-stamp-formats)
12091 (apply 'encode-time
12092 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
12093 nil nil nil))))
12094 (org-store-link-props :type "calendar" :date cd)))
12096 ((or (eq major-mode 'vm-summary-mode)
12097 (eq major-mode 'vm-presentation-mode))
12098 (and (eq major-mode 'vm-presentation-mode) (vm-summarize))
12099 (vm-follow-summary-cursor)
12100 (save-excursion
12101 (vm-select-folder-buffer)
12102 (let* ((message (car vm-message-pointer))
12103 (folder buffer-file-name)
12104 (subject (vm-su-subject message))
12105 (to (vm-get-header-contents message "To"))
12106 (from (vm-get-header-contents message "From"))
12107 (message-id (vm-su-message-id message)))
12108 (org-store-link-props :type "vm" :from from :to to :subject subject
12109 :message-id message-id)
12110 (setq message-id (org-remove-angle-brackets message-id))
12111 (setq folder (abbreviate-file-name folder))
12112 (if (string-match (concat "^" (regexp-quote vm-folder-directory))
12113 folder)
12114 (setq folder (replace-match "" t t folder)))
12115 (setq cpltxt (org-email-link-description))
12116 (setq link (org-make-link "vm:" folder "#" message-id)))))
12118 ((eq major-mode 'wl-summary-mode)
12119 (let* ((msgnum (wl-summary-message-number))
12120 (message-id (elmo-message-field wl-summary-buffer-elmo-folder
12121 msgnum 'message-id))
12122 (wl-message-entity
12123 (if (fboundp 'elmo-message-entity)
12124 (elmo-message-entity
12125 wl-summary-buffer-elmo-folder msgnum)
12126 (elmo-msgdb-overview-get-entity
12127 msgnum (wl-summary-buffer-msgdb))))
12128 (from (wl-summary-line-from))
12129 (to (car (elmo-message-entity-field wl-message-entity 'to)))
12130 (subject (let (wl-thr-indent-string wl-parent-message-entity)
12131 (wl-summary-line-subject))))
12132 (org-store-link-props :type "wl" :from from :to to
12133 :subject subject :message-id message-id)
12134 (setq message-id (org-remove-angle-brackets message-id))
12135 (setq cpltxt (org-email-link-description))
12136 (setq link (org-make-link "wl:" wl-summary-buffer-folder-name
12137 "#" message-id))))
12139 ((or (equal major-mode 'mh-folder-mode)
12140 (equal major-mode 'mh-show-mode))
12141 (let ((from (org-mhe-get-header "From:"))
12142 (to (org-mhe-get-header "To:"))
12143 (message-id (org-mhe-get-header "Message-Id:"))
12144 (subject (org-mhe-get-header "Subject:")))
12145 (org-store-link-props :type "mh" :from from :to to
12146 :subject subject :message-id message-id)
12147 (setq cpltxt (org-email-link-description))
12148 (setq link (org-make-link "mhe:" (org-mhe-get-message-real-folder) "#"
12149 (org-remove-angle-brackets message-id)))))
12151 ((or (eq major-mode 'rmail-mode)
12152 (eq major-mode 'rmail-summary-mode))
12153 (save-window-excursion
12154 (save-restriction
12155 (when (eq major-mode 'rmail-summary-mode)
12156 (rmail-show-message rmail-current-message))
12157 (rmail-narrow-to-non-pruned-header)
12158 (let ((folder buffer-file-name)
12159 (message-id (mail-fetch-field "message-id"))
12160 (from (mail-fetch-field "from"))
12161 (to (mail-fetch-field "to"))
12162 (subject (mail-fetch-field "subject")))
12163 (org-store-link-props
12164 :type "rmail" :from from :to to
12165 :subject subject :message-id message-id)
12166 (setq message-id (org-remove-angle-brackets message-id))
12167 (setq cpltxt (org-email-link-description))
12168 (setq link (org-make-link "rmail:" folder "#" message-id)))
12169 (rmail-show-message rmail-current-message))))
12171 ((eq major-mode 'gnus-group-mode)
12172 (let ((group (cond ((fboundp 'gnus-group-group-name) ; depending on Gnus
12173 (gnus-group-group-name)) ; version
12174 ((fboundp 'gnus-group-name)
12175 (gnus-group-name))
12176 (t "???"))))
12177 (unless group (error "Not on a group"))
12178 (org-store-link-props :type "gnus" :group group)
12179 (setq cpltxt (concat
12180 (if (org-xor arg org-usenet-links-prefer-google)
12181 "http://groups.google.com/groups?group="
12182 "gnus:")
12183 group)
12184 link (org-make-link cpltxt))))
12186 ((memq major-mode '(gnus-summary-mode gnus-article-mode))
12187 (and (eq major-mode 'gnus-article-mode) (gnus-article-show-summary))
12188 (let* ((group gnus-newsgroup-name)
12189 (article (gnus-summary-article-number))
12190 (header (gnus-summary-article-header article))
12191 (from (mail-header-from header))
12192 (message-id (mail-header-id header))
12193 (date (mail-header-date header))
12194 (subject (gnus-summary-subject-string)))
12195 (org-store-link-props :type "gnus" :from from :subject subject
12196 :message-id message-id :group group)
12197 (setq cpltxt (org-email-link-description))
12198 (if (org-xor arg org-usenet-links-prefer-google)
12199 (setq link
12200 (concat
12201 cpltxt "\n "
12202 (format "http://groups.google.com/groups?as_umsgid=%s"
12203 (org-fixup-message-id-for-http message-id))))
12204 (setq link (org-make-link "gnus:" group
12205 "#" (number-to-string article))))))
12207 ((eq major-mode 'w3-mode)
12208 (setq cpltxt (url-view-url t)
12209 link (org-make-link cpltxt))
12210 (org-store-link-props :type "w3" :url (url-view-url t)))
12212 ((eq major-mode 'w3m-mode)
12213 (setq cpltxt (or w3m-current-title w3m-current-url)
12214 link (org-make-link w3m-current-url))
12215 (org-store-link-props :type "w3m" :url (url-view-url t)))
12217 ((setq search (run-hook-with-args-until-success
12218 'org-create-file-search-functions))
12219 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
12220 "::" search))
12221 (setq cpltxt (or description link)))
12223 ((eq major-mode 'image-mode)
12224 (setq cpltxt (concat "file:"
12225 (abbreviate-file-name buffer-file-name))
12226 link (org-make-link cpltxt))
12227 (org-store-link-props :type "image" :file buffer-file-name))
12229 ((eq major-mode 'dired-mode)
12230 ;; link to the file in the current line
12231 (setq cpltxt (concat "file:"
12232 (abbreviate-file-name
12233 (expand-file-name
12234 (dired-get-filename nil t))))
12235 link (org-make-link cpltxt)))
12237 ((and buffer-file-name (org-mode-p))
12238 ;; Just link to current headline
12239 (setq cpltxt (concat "file:"
12240 (abbreviate-file-name buffer-file-name)))
12241 ;; Add a context search string
12242 (when (org-xor org-context-in-file-links arg)
12243 ;; Check if we are on a target
12244 (if (org-in-regexp "<<\\(.*?\\)>>")
12245 (setq cpltxt (concat cpltxt "::" (match-string 1)))
12246 (setq txt (cond
12247 ((org-on-heading-p) nil)
12248 ((org-region-active-p)
12249 (buffer-substring (region-beginning) (region-end)))
12250 (t (buffer-substring (point-at-bol) (point-at-eol)))))
12251 (when (or (null txt) (string-match "\\S-" txt))
12252 (setq cpltxt
12253 (concat cpltxt "::" (org-make-org-heading-search-string txt))
12254 desc "NONE"))))
12255 (if (string-match "::\\'" cpltxt)
12256 (setq cpltxt (substring cpltxt 0 -2)))
12257 (setq link (org-make-link cpltxt)))
12259 ((buffer-file-name (buffer-base-buffer))
12260 ;; Just link to this file here.
12261 (setq cpltxt (concat "file:"
12262 (abbreviate-file-name
12263 (buffer-file-name (buffer-base-buffer)))))
12264 ;; Add a context string
12265 (when (org-xor org-context-in-file-links arg)
12266 (setq txt (if (org-region-active-p)
12267 (buffer-substring (region-beginning) (region-end))
12268 (buffer-substring (point-at-bol) (point-at-eol))))
12269 ;; Only use search option if there is some text.
12270 (when (string-match "\\S-" txt)
12271 (setq cpltxt
12272 (concat cpltxt "::" (org-make-org-heading-search-string txt))
12273 desc "NONE")))
12274 (setq link (org-make-link cpltxt)))
12276 ((interactive-p)
12277 (error "Cannot link to a buffer which is not visiting a file"))
12279 (t (setq link nil)))
12281 (if (consp link) (setq cpltxt (car link) link (cdr link)))
12282 (setq link (or link cpltxt)
12283 desc (or desc cpltxt))
12284 (if (equal desc "NONE") (setq desc nil))
12286 (if (and (interactive-p) link)
12287 (progn
12288 (setq org-stored-links
12289 (cons (list link desc) org-stored-links))
12290 (message "Stored: %s" (or desc link)))
12291 (and link (org-make-link-string link desc)))))
12293 (defun org-store-link-props (&rest plist)
12294 "Store link properties, extract names and addresses."
12295 (let (x adr)
12296 (when (setq x (plist-get plist :from))
12297 (setq adr (mail-extract-address-components x))
12298 (plist-put plist :fromname (car adr))
12299 (plist-put plist :fromaddress (nth 1 adr)))
12300 (when (setq x (plist-get plist :to))
12301 (setq adr (mail-extract-address-components x))
12302 (plist-put plist :toname (car adr))
12303 (plist-put plist :toaddress (nth 1 adr))))
12304 (let ((from (plist-get plist :from))
12305 (to (plist-get plist :to)))
12306 (when (and from to org-from-is-user-regexp)
12307 (plist-put plist :fromto
12308 (if (string-match org-from-is-user-regexp from)
12309 (concat "to %t")
12310 (concat "from %f")))))
12311 (setq org-store-link-plist plist))
12313 (defun org-email-link-description (&optional fmt)
12314 "Return the description part of an email link.
12315 This takes information from `org-store-link-plist' and formats it
12316 according to FMT (default from `org-email-link-description-format')."
12317 (setq fmt (or fmt org-email-link-description-format))
12318 (let* ((p org-store-link-plist)
12319 (to (plist-get p :toaddress))
12320 (from (plist-get p :fromaddress))
12321 (table
12322 (list
12323 (cons "%c" (plist-get p :fromto))
12324 (cons "%F" (plist-get p :from))
12325 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
12326 (cons "%T" (plist-get p :to))
12327 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
12328 (cons "%s" (plist-get p :subject))
12329 (cons "%m" (plist-get p :message-id)))))
12330 (when (string-match "%c" fmt)
12331 ;; Check if the user wrote this message
12332 (if (and org-from-is-user-regexp from to
12333 (save-match-data (string-match org-from-is-user-regexp from)))
12334 (setq fmt (replace-match "to %t" t t fmt))
12335 (setq fmt (replace-match "from %f" t t fmt))))
12336 (org-replace-escapes fmt table)))
12338 (defun org-make-org-heading-search-string (&optional string heading)
12339 "Make search string for STRING or current headline."
12340 (interactive)
12341 (let ((s (or string (org-get-heading))))
12342 (unless (and string (not heading))
12343 ;; We are using a headline, clean up garbage in there.
12344 (if (string-match org-todo-regexp s)
12345 (setq s (replace-match "" t t s)))
12346 (if (string-match (org-re ":[[:alnum:]_@:]+:[ \t]*$") s)
12347 (setq s (replace-match "" t t s)))
12348 (setq s (org-trim s))
12349 (if (string-match (concat "^\\(" org-quote-string "\\|"
12350 org-comment-string "\\)") s)
12351 (setq s (replace-match "" t t s)))
12352 (while (string-match org-ts-regexp s)
12353 (setq s (replace-match "" t t s))))
12354 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
12355 (setq s (replace-match " " t t s)))
12356 (or string (setq s (concat "*" s))) ; Add * for headlines
12357 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
12359 (defun org-make-link (&rest strings)
12360 "Concatenate STRINGS."
12361 (apply 'concat strings))
12363 (defun org-make-link-string (link &optional description)
12364 "Make a link with brackets, consisting of LINK and DESCRIPTION."
12365 (unless (string-match "\\S-" link)
12366 (error "Empty link"))
12367 (when (stringp description)
12368 ;; Remove brackets from the description, they are fatal.
12369 (while (string-match "\\[" description)
12370 (setq description (replace-match "{" t t description)))
12371 (while (string-match "\\]" description)
12372 (setq description (replace-match "}" t t description))))
12373 (when (equal (org-link-escape link) description)
12374 ;; No description needed, it is identical
12375 (setq description nil))
12376 (when (and (not description)
12377 (not (equal link (org-link-escape link))))
12378 (setq description link))
12379 (concat "[[" (org-link-escape link) "]"
12380 (if description (concat "[" description "]") "")
12381 "]"))
12383 (defconst org-link-escape-chars
12384 '((?\ . "%20")
12385 (?\[ . "%5B")
12386 (?\] . "%5D")
12387 (?\340 . "%E0") ; `a
12388 (?\342 . "%E2") ; ^a
12389 (?\347 . "%E7") ; ,c
12390 (?\350 . "%E8") ; `e
12391 (?\351 . "%E9") ; 'e
12392 (?\352 . "%EA") ; ^e
12393 (?\356 . "%EE") ; ^i
12394 (?\364 . "%F4") ; ^o
12395 (?\371 . "%F9") ; `u
12396 (?\373 . "%FB") ; ^u
12397 (?\; . "%3B")
12398 (?? . "%3F")
12399 (?= . "%3D")
12400 (?+ . "%2B")
12402 "Association list of escapes for some characters problematic in links.
12403 This is the list that is used for internal purposes.")
12405 (defconst org-link-escape-chars-browser
12406 '((?\ . "%20")) ; 32 for the SPC char
12407 "Association list of escapes for some characters problematic in links.
12408 This is the list that is used before handing over to the browser.")
12410 (defun org-link-escape (text &optional table)
12411 "Escape charaters in TEXT that are problematic for links."
12412 (setq table (or table org-link-escape-chars))
12413 (when text
12414 (let ((re (mapconcat (lambda (x) (regexp-quote
12415 (char-to-string (car x))))
12416 table "\\|")))
12417 (while (string-match re text)
12418 (setq text
12419 (replace-match
12420 (cdr (assoc (string-to-char (match-string 0 text))
12421 table))
12422 t t text)))
12423 text)))
12425 (defun org-link-unescape (text &optional table)
12426 "Reverse the action of `org-link-escape'."
12427 (setq table (or table org-link-escape-chars))
12428 (when text
12429 (let ((re (mapconcat (lambda (x) (regexp-quote (cdr x)))
12430 table "\\|")))
12431 (while (string-match re text)
12432 (setq text
12433 (replace-match
12434 (char-to-string (car (rassoc (match-string 0 text) table)))
12435 t t text)))
12436 text)))
12438 (defun org-xor (a b)
12439 "Exclusive or."
12440 (if a (not b) b))
12442 (defun org-get-header (header)
12443 "Find a header field in the current buffer."
12444 (save-excursion
12445 (goto-char (point-min))
12446 (let ((case-fold-search t) s)
12447 (cond
12448 ((eq header 'from)
12449 (if (re-search-forward "^From:\\s-+\\(.*\\)" nil t)
12450 (setq s (match-string 1)))
12451 (while (string-match "\"" s)
12452 (setq s (replace-match "" t t s)))
12453 (if (string-match "[<(].*" s)
12454 (setq s (replace-match "" t t s))))
12455 ((eq header 'message-id)
12456 (if (re-search-forward "^message-id:\\s-+\\(.*\\)" nil t)
12457 (setq s (match-string 1))))
12458 ((eq header 'subject)
12459 (if (re-search-forward "^subject:\\s-+\\(.*\\)" nil t)
12460 (setq s (match-string 1)))))
12461 (if (string-match "\\`[ \t\]+" s) (setq s (replace-match "" t t s)))
12462 (if (string-match "[ \t\]+\\'" s) (setq s (replace-match "" t t s)))
12463 s)))
12466 (defun org-fixup-message-id-for-http (s)
12467 "Replace special characters in a message id, so it can be used in an http query."
12468 (while (string-match "<" s)
12469 (setq s (replace-match "%3C" t t s)))
12470 (while (string-match ">" s)
12471 (setq s (replace-match "%3E" t t s)))
12472 (while (string-match "@" s)
12473 (setq s (replace-match "%40" t t s)))
12476 ;;;###autoload
12477 (defun org-insert-link-global ()
12478 "Insert a link like Org-mode does.
12479 This command can be called in any mode to insert a link in Org-mode syntax."
12480 (interactive)
12481 (org-run-like-in-org-mode 'org-insert-link))
12483 (defun org-insert-link (&optional complete-file)
12484 "Insert a link. At the prompt, enter the link.
12486 Completion can be used to select a link previously stored with
12487 `org-store-link'. When the empty string is entered (i.e. if you just
12488 press RET at the prompt), the link defaults to the most recently
12489 stored link. As SPC triggers completion in the minibuffer, you need to
12490 use M-SPC or C-q SPC to force the insertion of a space character.
12492 You will also be prompted for a description, and if one is given, it will
12493 be displayed in the buffer instead of the link.
12495 If there is already a link at point, this command will allow you to edit link
12496 and description parts.
12498 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can be
12499 selected using completion. The path to the file will be relative to
12500 the current directory if the file is in the current directory or a
12501 subdirectory. Otherwise, the link will be the absolute path as
12502 completed in the minibuffer (i.e. normally ~/path/to/file).
12504 With two \\[universal-argument] prefixes, enforce an absolute path even if the file
12505 is in the current directory or below.
12506 With three \\[universal-argument] prefixes, negate the meaning of
12507 `org-keep-stored-link-after-insertion'."
12508 (interactive "P")
12509 (let* ((wcf (current-window-configuration))
12510 (region (if (org-region-active-p)
12511 (buffer-substring (region-beginning) (region-end))))
12512 (remove (and region (list (region-beginning) (region-end))))
12513 (desc region)
12514 tmphist ; byte-compile incorrectly complains about this
12515 link entry file)
12516 (cond
12517 ((org-in-regexp org-bracket-link-regexp 1)
12518 ;; We do have a link at point, and we are going to edit it.
12519 (setq remove (list (match-beginning 0) (match-end 0)))
12520 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
12521 (setq link (read-string "Link: "
12522 (org-link-unescape
12523 (org-match-string-no-properties 1)))))
12524 ((or (org-in-regexp org-angle-link-re)
12525 (org-in-regexp org-plain-link-re))
12526 ;; Convert to bracket link
12527 (setq remove (list (match-beginning 0) (match-end 0))
12528 link (read-string "Link: "
12529 (org-remove-angle-brackets (match-string 0)))))
12530 ((equal complete-file '(4))
12531 ;; Completing read for file names.
12532 (setq file (read-file-name "File: "))
12533 (let ((pwd (file-name-as-directory (expand-file-name ".")))
12534 (pwd1 (file-name-as-directory (abbreviate-file-name
12535 (expand-file-name ".")))))
12536 (cond
12537 ((equal complete-file '(16))
12538 (setq link (org-make-link
12539 "file:"
12540 (abbreviate-file-name (expand-file-name file)))))
12541 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
12542 (setq link (org-make-link "file:" (match-string 1 file))))
12543 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
12544 (expand-file-name file))
12545 (setq link (org-make-link
12546 "file:" (match-string 1 (expand-file-name file)))))
12547 (t (setq link (org-make-link "file:" file))))))
12549 ;; Read link, with completion for stored links.
12550 (with-output-to-temp-buffer "*Org Links*"
12551 (princ "Insert a link. Use TAB to complete valid link prefixes.\n")
12552 (when org-stored-links
12553 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
12554 (princ (mapconcat
12555 (lambda (x)
12556 (if (nth 1 x) (concat (car x) " (" (nth 1 x) ")") (car x)))
12557 (reverse org-stored-links) "\n"))))
12558 (let ((cw (selected-window)))
12559 (select-window (get-buffer-window "*Org Links*"))
12560 (shrink-window-if-larger-than-buffer)
12561 (setq truncate-lines t)
12562 (select-window cw))
12563 ;; Fake a link history, containing the stored links.
12564 (setq tmphist (append (mapcar 'car org-stored-links)
12565 org-insert-link-history))
12566 (unwind-protect
12567 (setq link (org-completing-read
12568 "Link: "
12569 (append
12570 (mapcar (lambda (x) (list (concat (car x) ":")))
12571 (append org-link-abbrev-alist-local org-link-abbrev-alist))
12572 (mapcar (lambda (x) (list (concat x ":")))
12573 org-link-types))
12574 nil nil nil
12575 'tmphist
12576 (or (car (car org-stored-links)))))
12577 (set-window-configuration wcf)
12578 (kill-buffer "*Org Links*"))
12579 (setq entry (assoc link org-stored-links))
12580 (or entry (push link org-insert-link-history))
12581 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
12582 (not org-keep-stored-link-after-insertion))
12583 (setq org-stored-links (delq (assoc link org-stored-links)
12584 org-stored-links)))
12585 (setq desc (or desc (nth 1 entry)))))
12587 (if (string-match org-plain-link-re link)
12588 ;; URL-like link, normalize the use of angular brackets.
12589 (setq link (org-make-link (org-remove-angle-brackets link))))
12591 ;; Check if we are linking to the current file with a search option
12592 ;; If yes, simplify the link by using only the search option.
12593 (when (and buffer-file-name
12594 (string-match "\\<file:\\(.+?\\)::\\([^>]+\\)" link))
12595 (let* ((path (match-string 1 link))
12596 (case-fold-search nil)
12597 (search (match-string 2 link)))
12598 (save-match-data
12599 (if (equal (file-truename buffer-file-name) (file-truename path))
12600 ;; We are linking to this same file, with a search option
12601 (setq link search)))))
12603 ;; Check if we can/should use a relative path. If yes, simplify the link
12604 (when (string-match "\\<file:\\(.*\\)" link)
12605 (let* ((path (match-string 1 link))
12606 (origpath path)
12607 (case-fold-search nil))
12608 (cond
12609 ((eq org-link-file-path-type 'absolute)
12610 (setq path (abbreviate-file-name (expand-file-name path))))
12611 ((eq org-link-file-path-type 'noabbrev)
12612 (setq path (expand-file-name path)))
12613 ((eq org-link-file-path-type 'relative)
12614 (setq path (file-relative-name path)))
12616 (save-match-data
12617 (if (string-match (concat "^" (regexp-quote
12618 (file-name-as-directory
12619 (expand-file-name "."))))
12620 (expand-file-name path))
12621 ;; We are linking a file with relative path name.
12622 (setq path (substring (expand-file-name path)
12623 (match-end 0)))))))
12624 (setq link (concat "file:" path))
12625 (if (equal desc origpath)
12626 (setq desc path))))
12628 (setq desc (read-string "Description: " desc))
12629 (unless (string-match "\\S-" desc) (setq desc nil))
12630 (if remove (apply 'delete-region remove))
12631 (insert (org-make-link-string link desc))))
12633 (defun org-completing-read (&rest args)
12634 (let ((minibuffer-local-completion-map
12635 (copy-keymap minibuffer-local-completion-map)))
12636 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
12637 (apply 'completing-read args)))
12639 ;;; Opening/following a link
12640 (defvar org-link-search-failed nil)
12642 (defun org-next-link ()
12643 "Move forward to the next link.
12644 If the link is in hidden text, expose it."
12645 (interactive)
12646 (when (and org-link-search-failed (eq this-command last-command))
12647 (goto-char (point-min))
12648 (message "Link search wrapped back to beginning of buffer"))
12649 (setq org-link-search-failed nil)
12650 (let* ((pos (point))
12651 (ct (org-context))
12652 (a (assoc :link ct)))
12653 (if a (goto-char (nth 2 a)))
12654 (if (re-search-forward org-any-link-re nil t)
12655 (progn
12656 (goto-char (match-beginning 0))
12657 (if (org-invisible-p) (org-show-context)))
12658 (goto-char pos)
12659 (setq org-link-search-failed t)
12660 (error "No further link found"))))
12662 (defun org-previous-link ()
12663 "Move backward to the previous link.
12664 If the link is in hidden text, expose it."
12665 (interactive)
12666 (when (and org-link-search-failed (eq this-command last-command))
12667 (goto-char (point-max))
12668 (message "Link search wrapped back to end of buffer"))
12669 (setq org-link-search-failed nil)
12670 (let* ((pos (point))
12671 (ct (org-context))
12672 (a (assoc :link ct)))
12673 (if a (goto-char (nth 1 a)))
12674 (if (re-search-backward org-any-link-re nil t)
12675 (progn
12676 (goto-char (match-beginning 0))
12677 (if (org-invisible-p) (org-show-context)))
12678 (goto-char pos)
12679 (setq org-link-search-failed t)
12680 (error "No further link found"))))
12682 (defun org-find-file-at-mouse (ev)
12683 "Open file link or URL at mouse."
12684 (interactive "e")
12685 (mouse-set-point ev)
12686 (org-open-at-point 'in-emacs))
12688 (defun org-open-at-mouse (ev)
12689 "Open file link or URL at mouse."
12690 (interactive "e")
12691 (mouse-set-point ev)
12692 (org-open-at-point))
12694 (defvar org-window-config-before-follow-link nil
12695 "The window configuration before following a link.
12696 This is saved in case the need arises to restore it.")
12698 (defvar org-open-link-marker (make-marker)
12699 "Marker pointing to the location where `org-open-at-point; was called.")
12701 ;;;###autoload
12702 (defun org-open-at-point-global ()
12703 "Follow a link like Org-mode does.
12704 This command can be called in any mode to follow a link that has
12705 Org-mode syntax."
12706 (interactive)
12707 (org-run-like-in-org-mode 'org-open-at-point))
12709 (defun org-open-at-point (&optional in-emacs)
12710 "Open link at or after point.
12711 If there is no link at point, this function will search forward up to
12712 the end of the current subtree.
12713 Normally, files will be opened by an appropriate application. If the
12714 optional argument IN-EMACS is non-nil, Emacs will visit the file."
12715 (interactive "P")
12716 (catch 'abort
12717 (move-marker org-open-link-marker (point))
12718 (setq org-window-config-before-follow-link (current-window-configuration))
12719 (org-remove-occur-highlights nil nil t)
12720 (if (org-at-timestamp-p t)
12721 (org-follow-timestamp-link)
12722 (let (type path link line search (pos (point)))
12723 (catch 'match
12724 (save-excursion
12725 (skip-chars-forward "^]\n\r")
12726 (when (org-in-regexp org-bracket-link-regexp)
12727 (setq link (org-link-unescape (org-match-string-no-properties 1)))
12728 (while (string-match " *\n *" link)
12729 (setq link (replace-match " " t t link)))
12730 (setq link (org-link-expand-abbrev link))
12731 (if (string-match org-link-re-with-space2 link)
12732 (setq type (match-string 1 link) path (match-string 2 link))
12733 (setq type "thisfile" path link))
12734 (throw 'match t)))
12736 (when (get-text-property (point) 'org-linked-text)
12737 (setq type "thisfile"
12738 pos (if (get-text-property (1+ (point)) 'org-linked-text)
12739 (1+ (point)) (point))
12740 path (buffer-substring
12741 (previous-single-property-change pos 'org-linked-text)
12742 (next-single-property-change pos 'org-linked-text)))
12743 (throw 'match t))
12745 (save-excursion
12746 (when (or (org-in-regexp org-angle-link-re)
12747 (org-in-regexp org-plain-link-re))
12748 (setq type (match-string 1) path (match-string 2))
12749 (throw 'match t)))
12750 (when (org-in-regexp "\\<\\([^><\n]+\\)\\>")
12751 (setq type "tree-match"
12752 path (match-string 1))
12753 (throw 'match t))
12754 (save-excursion
12755 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@:]+\\):[ \t]*$"))
12756 (setq type "tags"
12757 path (match-string 1))
12758 (while (string-match ":" path)
12759 (setq path (replace-match "+" t t path)))
12760 (throw 'match t))))
12761 (unless path
12762 (error "No link found"))
12763 ;; Remove any trailing spaces in path
12764 (if (string-match " +\\'" path)
12765 (setq path (replace-match "" t t path)))
12767 (cond
12769 ((assoc type org-link-protocols)
12770 (funcall (nth 1 (assoc type org-link-protocols)) path))
12772 ((equal type "mailto")
12773 (let ((cmd (car org-link-mailto-program))
12774 (args (cdr org-link-mailto-program)) args1
12775 (address path) (subject "") a)
12776 (if (string-match "\\(.*\\)::\\(.*\\)" path)
12777 (setq address (match-string 1 path)
12778 subject (org-link-escape (match-string 2 path))))
12779 (while args
12780 (cond
12781 ((not (stringp (car args))) (push (pop args) args1))
12782 (t (setq a (pop args))
12783 (if (string-match "%a" a)
12784 (setq a (replace-match address t t a)))
12785 (if (string-match "%s" a)
12786 (setq a (replace-match subject t t a)))
12787 (push a args1))))
12788 (apply cmd (nreverse args1))))
12790 ((member type '("http" "https" "ftp" "news"))
12791 (browse-url (concat type ":" (org-link-escape
12792 path org-link-escape-chars-browser))))
12794 ((member type '("message"))
12795 (browse-url (concat type ":" path)))
12797 ((string= type "tags")
12798 (org-tags-view in-emacs path))
12799 ((string= type "thisfile")
12800 (if in-emacs
12801 (switch-to-buffer-other-window
12802 (org-get-buffer-for-internal-link (current-buffer)))
12803 (org-mark-ring-push))
12804 (let ((cmd `(org-link-search
12805 ,path
12806 ,(cond ((equal in-emacs '(4)) 'occur)
12807 ((equal in-emacs '(16)) 'org-occur)
12808 (t nil))
12809 ,pos)))
12810 (condition-case nil (eval cmd)
12811 (error (progn (widen) (eval cmd))))))
12813 ((string= type "tree-match")
12814 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
12816 ((string= type "file")
12817 (if (string-match "::\\([0-9]+\\)\\'" path)
12818 (setq line (string-to-number (match-string 1 path))
12819 path (substring path 0 (match-beginning 0)))
12820 (if (string-match "::\\(.+\\)\\'" path)
12821 (setq search (match-string 1 path)
12822 path (substring path 0 (match-beginning 0)))))
12823 (if (string-match "[*?{]" (file-name-nondirectory path))
12824 (dired path)
12825 (org-open-file path in-emacs line search)))
12827 ((string= type "news")
12828 (org-follow-gnus-link path))
12830 ((string= type "bbdb")
12831 (org-follow-bbdb-link path))
12833 ((string= type "info")
12834 (org-follow-info-link path))
12836 ((string= type "gnus")
12837 (let (group article)
12838 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
12839 (error "Error in Gnus link"))
12840 (setq group (match-string 1 path)
12841 article (match-string 3 path))
12842 (org-follow-gnus-link group article)))
12844 ((string= type "vm")
12845 (let (folder article)
12846 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
12847 (error "Error in VM link"))
12848 (setq folder (match-string 1 path)
12849 article (match-string 3 path))
12850 ;; in-emacs is the prefix arg, will be interpreted as read-only
12851 (org-follow-vm-link folder article in-emacs)))
12853 ((string= type "wl")
12854 (let (folder article)
12855 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
12856 (error "Error in Wanderlust link"))
12857 (setq folder (match-string 1 path)
12858 article (match-string 3 path))
12859 (org-follow-wl-link folder article)))
12861 ((string= type "mhe")
12862 (let (folder article)
12863 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
12864 (error "Error in MHE link"))
12865 (setq folder (match-string 1 path)
12866 article (match-string 3 path))
12867 (org-follow-mhe-link folder article)))
12869 ((string= type "rmail")
12870 (let (folder article)
12871 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
12872 (error "Error in RMAIL link"))
12873 (setq folder (match-string 1 path)
12874 article (match-string 3 path))
12875 (org-follow-rmail-link folder article)))
12877 ((string= type "shell")
12878 (let ((cmd path))
12879 (if (or (not org-confirm-shell-link-function)
12880 (funcall org-confirm-shell-link-function
12881 (format "Execute \"%s\" in shell? "
12882 (org-add-props cmd nil
12883 'face 'org-warning))))
12884 (progn
12885 (message "Executing %s" cmd)
12886 (shell-command cmd))
12887 (error "Abort"))))
12889 ((string= type "elisp")
12890 (let ((cmd path))
12891 (if (or (not org-confirm-elisp-link-function)
12892 (funcall org-confirm-elisp-link-function
12893 (format "Execute \"%s\" as elisp? "
12894 (org-add-props cmd nil
12895 'face 'org-warning))))
12896 (message "%s => %s" cmd (eval (read cmd)))
12897 (error "Abort"))))
12900 (browse-url-at-point)))))
12901 (move-marker org-open-link-marker nil)))
12903 ;;; File search
12905 (defvar org-create-file-search-functions nil
12906 "List of functions to construct the right search string for a file link.
12907 These functions are called in turn with point at the location to
12908 which the link should point.
12910 A function in the hook should first test if it would like to
12911 handle this file type, for example by checking the major-mode or
12912 the file extension. If it decides not to handle this file, it
12913 should just return nil to give other functions a chance. If it
12914 does handle the file, it must return the search string to be used
12915 when following the link. The search string will be part of the
12916 file link, given after a double colon, and `org-open-at-point'
12917 will automatically search for it. If special measures must be
12918 taken to make the search successful, another function should be
12919 added to the companion hook `org-execute-file-search-functions',
12920 which see.
12922 A function in this hook may also use `setq' to set the variable
12923 `description' to provide a suggestion for the descriptive text to
12924 be used for this link when it gets inserted into an Org-mode
12925 buffer with \\[org-insert-link].")
12927 (defvar org-execute-file-search-functions nil
12928 "List of functions to execute a file search triggered by a link.
12930 Functions added to this hook must accept a single argument, the
12931 search string that was part of the file link, the part after the
12932 double colon. The function must first check if it would like to
12933 handle this search, for example by checking the major-mode or the
12934 file extension. If it decides not to handle this search, it
12935 should just return nil to give other functions a chance. If it
12936 does handle the search, it must return a non-nil value to keep
12937 other functions from trying.
12939 Each function can access the current prefix argument through the
12940 variable `current-prefix-argument'. Note that a single prefix is
12941 used to force opening a link in Emacs, so it may be good to only
12942 use a numeric or double prefix to guide the search function.
12944 In case this is needed, a function in this hook can also restore
12945 the window configuration before `org-open-at-point' was called using:
12947 (set-window-configuration org-window-config-before-follow-link)")
12949 (defun org-link-search (s &optional type avoid-pos)
12950 "Search for a link search option.
12951 If S is surrounded by forward slashes, it is interpreted as a
12952 regular expression. In org-mode files, this will create an `org-occur'
12953 sparse tree. In ordinary files, `occur' will be used to list matches.
12954 If the current buffer is in `dired-mode', grep will be used to search
12955 in all files. If AVOID-POS is given, ignore matches near that position."
12956 (let ((case-fold-search t)
12957 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
12958 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
12959 (append '(("") (" ") ("\t") ("\n"))
12960 org-emphasis-alist)
12961 "\\|") "\\)"))
12962 (pos (point))
12963 (pre "") (post "")
12964 words re0 re1 re2 re3 re4 re5 re2a reall)
12965 (cond
12966 ;; First check if there are any special
12967 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
12968 ;; Now try the builtin stuff
12969 ((save-excursion
12970 (goto-char (point-min))
12971 (and
12972 (re-search-forward
12973 (concat "<<" (regexp-quote s0) ">>") nil t)
12974 (setq pos (match-beginning 0))))
12975 ;; There is an exact target for this
12976 (goto-char pos))
12977 ((string-match "^/\\(.*\\)/$" s)
12978 ;; A regular expression
12979 (cond
12980 ((org-mode-p)
12981 (org-occur (match-string 1 s)))
12982 ;;((eq major-mode 'dired-mode)
12983 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
12984 (t (org-do-occur (match-string 1 s)))))
12986 ;; A normal search strings
12987 (when (equal (string-to-char s) ?*)
12988 ;; Anchor on headlines, post may include tags.
12989 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
12990 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@:+]:[ \t]*\\)?$")
12991 s (substring s 1)))
12992 (remove-text-properties
12993 0 (length s)
12994 '(face nil mouse-face nil keymap nil fontified nil) s)
12995 ;; Make a series of regular expressions to find a match
12996 (setq words (org-split-string s "[ \n\r\t]+")
12997 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
12998 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
12999 "\\)" markers)
13000 re2a (concat "[ \t\r\n]\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
13001 re4 (concat "[^a-zA-Z_]\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
13002 re1 (concat pre re2 post)
13003 re3 (concat pre re4 post)
13004 re5 (concat pre ".*" re4)
13005 re2 (concat pre re2)
13006 re2a (concat pre re2a)
13007 re4 (concat pre re4)
13008 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
13009 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
13010 re5 "\\)"
13012 (cond
13013 ((eq type 'org-occur) (org-occur reall))
13014 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
13015 (t (goto-char (point-min))
13016 (if (or (org-search-not-self 1 re0 nil t)
13017 (org-search-not-self 1 re1 nil t)
13018 (org-search-not-self 1 re2 nil t)
13019 (org-search-not-self 1 re2a nil t)
13020 (org-search-not-self 1 re3 nil t)
13021 (org-search-not-self 1 re4 nil t)
13022 (org-search-not-self 1 re5 nil t)
13024 (goto-char (match-beginning 1))
13025 (goto-char pos)
13026 (error "No match")))))
13028 ;; Normal string-search
13029 (goto-char (point-min))
13030 (if (search-forward s nil t)
13031 (goto-char (match-beginning 0))
13032 (error "No match"))))
13033 (and (org-mode-p) (org-show-context 'link-search))))
13035 (defun org-search-not-self (group &rest args)
13036 "Execute `re-search-forward', but only accept matches that do not
13037 enclose the position of `org-open-link-marker'."
13038 (let ((m org-open-link-marker))
13039 (catch 'exit
13040 (while (apply 're-search-forward args)
13041 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
13042 (goto-char (match-end group))
13043 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
13044 (> (match-beginning 0) (marker-position m))
13045 (< (match-end 0) (marker-position m)))
13046 (save-match-data
13047 (or (not (org-in-regexp
13048 org-bracket-link-analytic-regexp 1))
13049 (not (match-end 4)) ; no description
13050 (and (<= (match-beginning 4) (point))
13051 (>= (match-end 4) (point))))))
13052 (throw 'exit (point))))))))
13054 (defun org-get-buffer-for-internal-link (buffer)
13055 "Return a buffer to be used for displaying the link target of internal links."
13056 (cond
13057 ((not org-display-internal-link-with-indirect-buffer)
13058 buffer)
13059 ((string-match "(Clone)$" (buffer-name buffer))
13060 (message "Buffer is already a clone, not making another one")
13061 ;; we also do not modify visibility in this case
13062 buffer)
13063 (t ; make a new indirect buffer for displaying the link
13064 (let* ((bn (buffer-name buffer))
13065 (ibn (concat bn "(Clone)"))
13066 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
13067 (with-current-buffer ib (org-overview))
13068 ib))))
13070 (defun org-do-occur (regexp &optional cleanup)
13071 "Call the Emacs command `occur'.
13072 If CLEANUP is non-nil, remove the printout of the regular expression
13073 in the *Occur* buffer. This is useful if the regex is long and not useful
13074 to read."
13075 (occur regexp)
13076 (when cleanup
13077 (let ((cwin (selected-window)) win beg end)
13078 (when (setq win (get-buffer-window "*Occur*"))
13079 (select-window win))
13080 (goto-char (point-min))
13081 (when (re-search-forward "match[a-z]+" nil t)
13082 (setq beg (match-end 0))
13083 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
13084 (setq end (1- (match-beginning 0)))))
13085 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
13086 (goto-char (point-min))
13087 (select-window cwin))))
13089 ;;; The mark ring for links jumps
13091 (defvar org-mark-ring nil
13092 "Mark ring for positions before jumps in Org-mode.")
13093 (defvar org-mark-ring-last-goto nil
13094 "Last position in the mark ring used to go back.")
13095 ;; Fill and close the ring
13096 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
13097 (loop for i from 1 to org-mark-ring-length do
13098 (push (make-marker) org-mark-ring))
13099 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
13100 org-mark-ring)
13102 (defun org-mark-ring-push (&optional pos buffer)
13103 "Put the current position or POS into the mark ring and rotate it."
13104 (interactive)
13105 (setq pos (or pos (point)))
13106 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
13107 (move-marker (car org-mark-ring)
13108 (or pos (point))
13109 (or buffer (current-buffer)))
13110 (message "%s"
13111 (substitute-command-keys
13112 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
13114 (defun org-mark-ring-goto (&optional n)
13115 "Jump to the previous position in the mark ring.
13116 With prefix arg N, jump back that many stored positions. When
13117 called several times in succession, walk through the entire ring.
13118 Org-mode commands jumping to a different position in the current file,
13119 or to another Org-mode file, automatically push the old position
13120 onto the ring."
13121 (interactive "p")
13122 (let (p m)
13123 (if (eq last-command this-command)
13124 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
13125 (setq p org-mark-ring))
13126 (setq org-mark-ring-last-goto p)
13127 (setq m (car p))
13128 (switch-to-buffer (marker-buffer m))
13129 (goto-char m)
13130 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
13132 (defun org-remove-angle-brackets (s)
13133 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
13134 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
13136 (defun org-add-angle-brackets (s)
13137 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
13138 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
13141 ;;; Following specific links
13143 (defun org-follow-timestamp-link ()
13144 (cond
13145 ((org-at-date-range-p t)
13146 (let ((org-agenda-start-on-weekday)
13147 (t1 (match-string 1))
13148 (t2 (match-string 2)))
13149 (setq t1 (time-to-days (org-time-string-to-time t1))
13150 t2 (time-to-days (org-time-string-to-time t2)))
13151 (org-agenda-list nil t1 (1+ (- t2 t1)))))
13152 ((org-at-timestamp-p t)
13153 (org-agenda-list nil (time-to-days (org-time-string-to-time
13154 (substring (match-string 1) 0 10)))
13156 (t (error "This should not happen"))))
13159 (defun org-follow-bbdb-link (name)
13160 "Follow a BBDB link to NAME."
13161 (require 'bbdb)
13162 (let ((inhibit-redisplay (not debug-on-error))
13163 (bbdb-electric-p nil))
13164 (catch 'exit
13165 ;; Exact match on name
13166 (bbdb-name (concat "\\`" name "\\'") nil)
13167 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
13168 ;; Exact match on name
13169 (bbdb-company (concat "\\`" name "\\'") nil)
13170 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
13171 ;; Partial match on name
13172 (bbdb-name name nil)
13173 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
13174 ;; Partial match on company
13175 (bbdb-company name nil)
13176 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
13177 ;; General match including network address and notes
13178 (bbdb name nil)
13179 (when (= 0 (buffer-size (get-buffer "*BBDB*")))
13180 (delete-window (get-buffer-window "*BBDB*"))
13181 (error "No matching BBDB record")))))
13183 (defun org-follow-info-link (name)
13184 "Follow an info file & node link to NAME."
13185 (if (or (string-match "\\(.*\\)::?\\(.*\\)" name)
13186 (string-match "\\(.*\\)" name))
13187 (progn
13188 (require 'info)
13189 (if (match-string 2 name) ; If there isn't a node, choose "Top"
13190 (Info-find-node (match-string 1 name) (match-string 2 name))
13191 (Info-find-node (match-string 1 name) "Top")))
13192 (message "Could not open: %s" name)))
13194 (defun org-follow-gnus-link (&optional group article)
13195 "Follow a Gnus link to GROUP and ARTICLE."
13196 (require 'gnus)
13197 (funcall (cdr (assq 'gnus org-link-frame-setup)))
13198 (if gnus-other-frame-object (select-frame gnus-other-frame-object))
13199 (cond ((and group article)
13200 (gnus-group-read-group 1 nil group)
13201 (gnus-summary-goto-article (string-to-number article) nil t))
13202 (group (gnus-group-jump-to-group group))))
13204 (defun org-follow-vm-link (&optional folder article readonly)
13205 "Follow a VM link to FOLDER and ARTICLE."
13206 (require 'vm)
13207 (setq article (org-add-angle-brackets article))
13208 (if (string-match "^//\\([a-zA-Z]+@\\)?\\([^:]+\\):\\(.*\\)" folder)
13209 ;; ange-ftp or efs or tramp access
13210 (let ((user (or (match-string 1 folder) (user-login-name)))
13211 (host (match-string 2 folder))
13212 (file (match-string 3 folder)))
13213 (cond
13214 ((featurep 'tramp)
13215 ;; use tramp to access the file
13216 (if (featurep 'xemacs)
13217 (setq folder (format "[%s@%s]%s" user host file))
13218 (setq folder (format "/%s@%s:%s" user host file))))
13220 ;; use ange-ftp or efs
13221 (require (if (featurep 'xemacs) 'efs 'ange-ftp))
13222 (setq folder (format "/%s@%s:%s" user host file))))))
13223 (when folder
13224 (funcall (cdr (assq 'vm org-link-frame-setup)) folder readonly)
13225 (sit-for 0.1)
13226 (when article
13227 (vm-select-folder-buffer)
13228 (widen)
13229 (let ((case-fold-search t))
13230 (goto-char (point-min))
13231 (if (not (re-search-forward
13232 (concat "^" "message-id: *" (regexp-quote article))))
13233 (error "Could not find the specified message in this folder"))
13234 (vm-isearch-update)
13235 (vm-isearch-narrow)
13236 (vm-beginning-of-message)
13237 (vm-summarize)))))
13239 (defun org-follow-wl-link (folder article)
13240 "Follow a Wanderlust link to FOLDER and ARTICLE."
13241 (if (and (string= folder "%")
13242 article
13243 (string-match "^\\([^#]+\\)\\(#\\(.*\\)\\)?" article))
13244 ;; XXX: imap-uw supports folders starting with '#' such as "#mh/inbox".
13245 ;; Thus, we recompose folder and article ids.
13246 (setq folder (format "%s#%s" folder (match-string 1 article))
13247 article (match-string 3 article)))
13248 (if (not (elmo-folder-exists-p (wl-folder-get-elmo-folder folder)))
13249 (error "No such folder: %s" folder))
13250 (wl-summary-goto-folder-subr folder 'no-sync t nil t nil nil)
13251 (and article
13252 (wl-summary-jump-to-msg-by-message-id (org-add-angle-brackets article))
13253 (wl-summary-redisplay)))
13255 (defun org-follow-rmail-link (folder article)
13256 "Follow an RMAIL link to FOLDER and ARTICLE."
13257 (setq article (org-add-angle-brackets article))
13258 (let (message-number)
13259 (save-excursion
13260 (save-window-excursion
13261 (rmail (if (string= folder "RMAIL") rmail-file-name folder))
13262 (setq message-number
13263 (save-restriction
13264 (widen)
13265 (goto-char (point-max))
13266 (if (re-search-backward
13267 (concat "^Message-ID:\\s-+" (regexp-quote
13268 (or article "")))
13269 nil t)
13270 (rmail-what-message))))))
13271 (if message-number
13272 (progn
13273 (rmail (if (string= folder "RMAIL") rmail-file-name folder))
13274 (rmail-show-message message-number)
13275 message-number)
13276 (error "Message not found"))))
13278 ;;; mh-e integration based on planner-mode
13279 (defun org-mhe-get-message-real-folder ()
13280 "Return the name of the current message real folder, so if you use
13281 sequences, it will now work."
13282 (save-excursion
13283 (let* ((folder
13284 (if (equal major-mode 'mh-folder-mode)
13285 mh-current-folder
13286 ;; Refer to the show buffer
13287 mh-show-folder-buffer))
13288 (end-index
13289 (if (boundp 'mh-index-folder)
13290 (min (length mh-index-folder) (length folder))))
13292 ;; a simple test on mh-index-data does not work, because
13293 ;; mh-index-data is always nil in a show buffer.
13294 (if (and (boundp 'mh-index-folder)
13295 (string= mh-index-folder (substring folder 0 end-index)))
13296 (if (equal major-mode 'mh-show-mode)
13297 (save-window-excursion
13298 (let (pop-up-frames)
13299 (when (buffer-live-p (get-buffer folder))
13300 (progn
13301 (pop-to-buffer folder)
13302 (org-mhe-get-message-folder-from-index)
13305 (org-mhe-get-message-folder-from-index)
13307 folder
13311 (defun org-mhe-get-message-folder-from-index ()
13312 "Returns the name of the message folder in a index folder buffer."
13313 (save-excursion
13314 (mh-index-previous-folder)
13315 (re-search-forward "^\\(+.*\\)$" nil t)
13316 (message "%s" (match-string 1))))
13318 (defun org-mhe-get-message-folder ()
13319 "Return the name of the current message folder. Be careful if you
13320 use sequences."
13321 (save-excursion
13322 (if (equal major-mode 'mh-folder-mode)
13323 mh-current-folder
13324 ;; Refer to the show buffer
13325 mh-show-folder-buffer)))
13327 (defun org-mhe-get-message-num ()
13328 "Return the number of the current message. Be careful if you
13329 use sequences."
13330 (save-excursion
13331 (if (equal major-mode 'mh-folder-mode)
13332 (mh-get-msg-num nil)
13333 ;; Refer to the show buffer
13334 (mh-show-buffer-message-number))))
13336 (defun org-mhe-get-header (header)
13337 "Return a header of the message in folder mode. This will create a
13338 show buffer for the corresponding message. If you have a more clever
13339 idea..."
13340 (let* ((folder (org-mhe-get-message-folder))
13341 (num (org-mhe-get-message-num))
13342 (buffer (get-buffer-create (concat "show-" folder)))
13343 (header-field))
13344 (with-current-buffer buffer
13345 (mh-display-msg num folder)
13346 (if (equal major-mode 'mh-folder-mode)
13347 (mh-header-display)
13348 (mh-show-header-display))
13349 (set-buffer buffer)
13350 (setq header-field (mh-get-header-field header))
13351 (if (equal major-mode 'mh-folder-mode)
13352 (mh-show)
13353 (mh-show-show))
13354 header-field)))
13356 (defun org-follow-mhe-link (folder article)
13357 "Follow an MHE link to FOLDER and ARTICLE.
13358 If ARTICLE is nil FOLDER is shown. If the configuration variable
13359 `org-mhe-search-all-folders' is t and `mh-searcher' is pick,
13360 ARTICLE is searched in all folders. Indexed searches (swish++,
13361 namazu, and others supported by MH-E) will always search in all
13362 folders."
13363 (require 'mh-e)
13364 (require 'mh-search)
13365 (require 'mh-utils)
13366 (mh-find-path)
13367 (if (not article)
13368 (mh-visit-folder (mh-normalize-folder-name folder))
13369 (setq article (org-add-angle-brackets article))
13370 (mh-search-choose)
13371 (if (equal mh-searcher 'pick)
13372 (progn
13373 (mh-search folder (list "--message-id" article))
13374 (when (and org-mhe-search-all-folders
13375 (not (org-mhe-get-message-real-folder)))
13376 (kill-this-buffer)
13377 (mh-search "+" (list "--message-id" article))))
13378 (mh-search "+" article))
13379 (if (org-mhe-get-message-real-folder)
13380 (mh-show-msg 1)
13381 (kill-this-buffer)
13382 (error "Message not found"))))
13384 ;;; BibTeX links
13386 ;; Use the custom search meachnism to construct and use search strings for
13387 ;; file links to BibTeX database entries.
13389 (defun org-create-file-search-in-bibtex ()
13390 "Create the search string and description for a BibTeX database entry."
13391 (when (eq major-mode 'bibtex-mode)
13392 ;; yes, we want to construct this search string.
13393 ;; Make a good description for this entry, using names, year and the title
13394 ;; Put it into the `description' variable which is dynamically scoped.
13395 (let ((bibtex-autokey-names 1)
13396 (bibtex-autokey-names-stretch 1)
13397 (bibtex-autokey-name-case-convert-function 'identity)
13398 (bibtex-autokey-name-separator " & ")
13399 (bibtex-autokey-additional-names " et al.")
13400 (bibtex-autokey-year-length 4)
13401 (bibtex-autokey-name-year-separator " ")
13402 (bibtex-autokey-titlewords 3)
13403 (bibtex-autokey-titleword-separator " ")
13404 (bibtex-autokey-titleword-case-convert-function 'identity)
13405 (bibtex-autokey-titleword-length 'infty)
13406 (bibtex-autokey-year-title-separator ": "))
13407 (setq description (bibtex-generate-autokey)))
13408 ;; Now parse the entry, get the key and return it.
13409 (save-excursion
13410 (bibtex-beginning-of-entry)
13411 (cdr (assoc "=key=" (bibtex-parse-entry))))))
13413 (defun org-execute-file-search-in-bibtex (s)
13414 "Find the link search string S as a key for a database entry."
13415 (when (eq major-mode 'bibtex-mode)
13416 ;; Yes, we want to do the search in this file.
13417 ;; We construct a regexp that searches for "@entrytype{" followed by the key
13418 (goto-char (point-min))
13419 (and (re-search-forward (concat "@[a-zA-Z]+[ \t\n]*{[ \t\n]*"
13420 (regexp-quote s) "[ \t\n]*,") nil t)
13421 (goto-char (match-beginning 0)))
13422 (if (and (match-beginning 0) (equal current-prefix-arg '(16)))
13423 ;; Use double prefix to indicate that any web link should be browsed
13424 (let ((b (current-buffer)) (p (point)))
13425 ;; Restore the window configuration because we just use the web link
13426 (set-window-configuration org-window-config-before-follow-link)
13427 (save-excursion (set-buffer b) (goto-char p)
13428 (bibtex-url)))
13429 (recenter 0)) ; Move entry start to beginning of window
13430 ;; return t to indicate that the search is done.
13433 ;; Finally add the functions to the right hooks.
13434 (add-hook 'org-create-file-search-functions 'org-create-file-search-in-bibtex)
13435 (add-hook 'org-execute-file-search-functions 'org-execute-file-search-in-bibtex)
13437 ;; end of Bibtex link setup
13439 ;;; Following file links
13441 (defun org-open-file (path &optional in-emacs line search)
13442 "Open the file at PATH.
13443 First, this expands any special file name abbreviations. Then the
13444 configuration variable `org-file-apps' is checked if it contains an
13445 entry for this file type, and if yes, the corresponding command is launched.
13446 If no application is found, Emacs simply visits the file.
13447 With optional argument IN-EMACS, Emacs will visit the file.
13448 Optional LINE specifies a line to go to, optional SEARCH a string to
13449 search for. If LINE or SEARCH is given, the file will always be
13450 opened in Emacs.
13451 If the file does not exist, an error is thrown."
13452 (setq in-emacs (or in-emacs line search))
13453 (let* ((file (if (equal path "")
13454 buffer-file-name
13455 (substitute-in-file-name (expand-file-name path))))
13456 (apps (append org-file-apps (org-default-apps)))
13457 (remp (and (assq 'remote apps) (org-file-remote-p file)))
13458 (dirp (if remp nil (file-directory-p file)))
13459 (dfile (downcase file))
13460 (old-buffer (current-buffer))
13461 (old-pos (point))
13462 (old-mode major-mode)
13463 ext cmd)
13464 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
13465 (setq ext (match-string 1 dfile))
13466 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
13467 (setq ext (match-string 1 dfile))))
13468 (if in-emacs
13469 (setq cmd 'emacs)
13470 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
13471 (and dirp (cdr (assoc 'directory apps)))
13472 (cdr (assoc ext apps))
13473 (cdr (assoc t apps)))))
13474 (when (eq cmd 'mailcap)
13475 (require 'mailcap)
13476 (mailcap-parse-mailcaps)
13477 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
13478 (command (mailcap-mime-info mime-type)))
13479 (if (stringp command)
13480 (setq cmd command)
13481 (setq cmd 'emacs))))
13482 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
13483 (not (file-exists-p file))
13484 (not org-open-non-existing-files))
13485 (error "No such file: %s" file))
13486 (cond
13487 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
13488 ;; Remove quotes around the file name - we'll use shell-quote-argument.
13489 (while (string-match "['\"]%s['\"]" cmd)
13490 (setq cmd (replace-match "%s" t t cmd)))
13491 (while (string-match "%s" cmd)
13492 (setq cmd (replace-match
13493 (save-match-data (shell-quote-argument file))
13494 t t cmd)))
13495 (save-window-excursion
13496 (start-process-shell-command cmd nil cmd)))
13497 ((or (stringp cmd)
13498 (eq cmd 'emacs))
13499 (funcall (cdr (assq 'file org-link-frame-setup)) file)
13500 (widen)
13501 (if line (goto-line line)
13502 (if search (org-link-search search))))
13503 ((consp cmd)
13504 (eval cmd))
13505 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
13506 (and (org-mode-p) (eq old-mode 'org-mode)
13507 (or (not (equal old-buffer (current-buffer)))
13508 (not (equal old-pos (point))))
13509 (org-mark-ring-push old-pos old-buffer))))
13511 (defun org-default-apps ()
13512 "Return the default applications for this operating system."
13513 (cond
13514 ((eq system-type 'darwin)
13515 org-file-apps-defaults-macosx)
13516 ((eq system-type 'windows-nt)
13517 org-file-apps-defaults-windowsnt)
13518 (t org-file-apps-defaults-gnu)))
13520 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
13521 (defun org-file-remote-p (file)
13522 "Test whether FILE specifies a location on a remote system.
13523 Return non-nil if the location is indeed remote.
13525 For example, the filename \"/user@host:/foo\" specifies a location
13526 on the system \"/user@host:\"."
13527 (cond ((fboundp 'file-remote-p)
13528 (file-remote-p file))
13529 ((fboundp 'tramp-handle-file-remote-p)
13530 (tramp-handle-file-remote-p file))
13531 ((and (boundp 'ange-ftp-name-format)
13532 (string-match (car ange-ftp-name-format) file))
13534 (t nil)))
13537 ;;;; Hooks for remember.el, and refiling
13539 (defvar annotation) ; from remember.el, dynamically scoped in `remember-mode'
13540 (defvar initial) ; from remember.el, dynamically scoped in `remember-mode'
13542 ;;;###autoload
13543 (defun org-remember-insinuate ()
13544 "Setup remember.el for use wiht Org-mode."
13545 (require 'remember)
13546 (setq remember-annotation-functions '(org-remember-annotation))
13547 (setq remember-handler-functions '(org-remember-handler))
13548 (add-hook 'remember-mode-hook 'org-remember-apply-template))
13550 ;;;###autoload
13551 (defun org-remember-annotation ()
13552 "Return a link to the current location as an annotation for remember.el.
13553 If you are using Org-mode files as target for data storage with
13554 remember.el, then the annotations should include a link compatible with the
13555 conventions in Org-mode. This function returns such a link."
13556 (org-store-link nil))
13558 (defconst org-remember-help
13559 "Select a destination location for the note.
13560 UP/DOWN=headline TAB=cycle visibility [Q]uit RET/<left>/<right>=Store
13561 RET on headline -> Store as sublevel entry to current headline
13562 RET at beg-of-buf -> Append to file as level 2 headline
13563 <left>/<right> -> before/after current headline, same headings level")
13565 (defvar org-remember-previous-location nil)
13566 (defvar org-force-remember-template-char) ;; dynamically scoped
13568 (defun org-select-remember-template (&optional use-char)
13569 (when org-remember-templates
13570 (let* ((templates (mapcar (lambda (x)
13571 (if (stringp (car x))
13572 (append (list (nth 1 x) (car x)) (cddr x))
13573 (append (list (car x) "") (cdr x))))
13574 org-remember-templates))
13575 (char (or use-char
13576 (cond
13577 ((= (length templates) 1)
13578 (caar templates))
13579 ((and (boundp 'org-force-remember-template-char)
13580 org-force-remember-template-char)
13581 (if (stringp org-force-remember-template-char)
13582 (string-to-char org-force-remember-template-char)
13583 org-force-remember-template-char))
13585 (message "Select template: %s"
13586 (mapconcat
13587 (lambda (x)
13588 (cond
13589 ((not (string-match "\\S-" (nth 1 x)))
13590 (format "[%c]" (car x)))
13591 ((equal (downcase (car x))
13592 (downcase (aref (nth 1 x) 0)))
13593 (format "[%c]%s" (car x)
13594 (substring (nth 1 x) 1)))
13595 (t (format "[%c]%s" (car x) (nth 1 x)))))
13596 templates " "))
13597 (let ((inhibit-quit t) (char0 (read-char-exclusive)))
13598 (when (equal char0 ?\C-g)
13599 (jump-to-register remember-register)
13600 (kill-buffer remember-buffer))
13601 char0))))))
13602 (cddr (assoc char templates)))))
13604 (defvar x-last-selected-text)
13605 (defvar x-last-selected-text-primary)
13607 ;;;###autoload
13608 (defun org-remember-apply-template (&optional use-char skip-interactive)
13609 "Initialize *remember* buffer with template, invoke `org-mode'.
13610 This function should be placed into `remember-mode-hook' and in fact requires
13611 to be run from that hook to function properly."
13612 (if org-remember-templates
13613 (let* ((entry (org-select-remember-template use-char))
13614 (tpl (car entry))
13615 (plist-p (if org-store-link-plist t nil))
13616 (file (if (and (nth 1 entry) (stringp (nth 1 entry))
13617 (string-match "\\S-" (nth 1 entry)))
13618 (nth 1 entry)
13619 org-default-notes-file))
13620 (headline (nth 2 entry))
13621 (v-c (or (and (eq window-system 'x)
13622 (fboundp 'x-cut-buffer-or-selection-value)
13623 (x-cut-buffer-or-selection-value))
13624 (org-bound-and-true-p x-last-selected-text)
13625 (org-bound-and-true-p x-last-selected-text-primary)
13626 (and (> (length kill-ring) 0) (current-kill 0))))
13627 (v-t (format-time-string (car org-time-stamp-formats) (org-current-time)))
13628 (v-T (format-time-string (cdr org-time-stamp-formats) (org-current-time)))
13629 (v-u (concat "[" (substring v-t 1 -1) "]"))
13630 (v-U (concat "[" (substring v-T 1 -1) "]"))
13631 ;; `initial' and `annotation' are bound in `remember'
13632 (v-i (if (boundp 'initial) initial))
13633 (v-a (if (and (boundp 'annotation) annotation)
13634 (if (equal annotation "[[]]") "" annotation)
13635 ""))
13636 (v-A (if (and v-a
13637 (string-match "\\[\\(\\[.*?\\]\\)\\(\\[.*?\\]\\)?\\]" v-a))
13638 (replace-match "[\\1[%^{Link description}]]" nil nil v-a)
13639 v-a))
13640 (v-n user-full-name)
13641 (org-startup-folded nil)
13642 org-time-was-given org-end-time-was-given x
13643 prompt completions char time pos default histvar)
13644 (setq org-store-link-plist
13645 (append (list :annotation v-a :initial v-i)
13646 org-store-link-plist))
13647 (unless tpl (setq tpl "") (message "No template") (ding) (sit-for 1))
13648 (erase-buffer)
13649 (insert (substitute-command-keys
13650 (format
13651 "## Filing location: Select interactively, default, or last used:
13652 ## %s to select file and header location interactively.
13653 ## %s \"%s\" -> \"* %s\"
13654 ## C-u C-u C-c C-c \"%s\" -> \"* %s\"
13655 ## To switch templates, use `\\[org-remember]'. To abort use `C-c C-k'.\n\n"
13656 (if org-remember-store-without-prompt " C-u C-c C-c" " C-c C-c")
13657 (if org-remember-store-without-prompt " C-c C-c" " C-u C-c C-c")
13658 (abbreviate-file-name (or file org-default-notes-file))
13659 (or headline "")
13660 (or (car org-remember-previous-location) "???")
13661 (or (cdr org-remember-previous-location) "???"))))
13662 (insert tpl) (goto-char (point-min))
13663 ;; Simple %-escapes
13664 (while (re-search-forward "%\\([tTuUaiAc]\\)" nil t)
13665 (when (and initial (equal (match-string 0) "%i"))
13666 (save-match-data
13667 (let* ((lead (buffer-substring
13668 (point-at-bol) (match-beginning 0))))
13669 (setq v-i (mapconcat 'identity
13670 (org-split-string initial "\n")
13671 (concat "\n" lead))))))
13672 (replace-match
13673 (or (eval (intern (concat "v-" (match-string 1)))) "")
13674 t t))
13676 ;; %[] Insert contents of a file.
13677 (goto-char (point-min))
13678 (while (re-search-forward "%\\[\\(.+\\)\\]" nil t)
13679 (let ((start (match-beginning 0))
13680 (end (match-end 0))
13681 (filename (expand-file-name (match-string 1))))
13682 (goto-char start)
13683 (delete-region start end)
13684 (condition-case error
13685 (insert-file-contents filename)
13686 (error (insert (format "%%![Couldn't insert %s: %s]"
13687 filename error))))))
13688 ;; %() embedded elisp
13689 (goto-char (point-min))
13690 (while (re-search-forward "%\\((.+)\\)" nil t)
13691 (goto-char (match-beginning 0))
13692 (let ((template-start (point)))
13693 (forward-char 1)
13694 (let ((result
13695 (condition-case error
13696 (eval (read (current-buffer)))
13697 (error (format "%%![Error: %s]" error)))))
13698 (delete-region template-start (point))
13699 (insert result))))
13701 ;; From the property list
13702 (when plist-p
13703 (goto-char (point-min))
13704 (while (re-search-forward "%\\(:[-a-zA-Z]+\\)" nil t)
13705 (and (setq x (or (plist-get org-store-link-plist
13706 (intern (match-string 1))) ""))
13707 (replace-match x t t))))
13709 ;; Turn on org-mode in the remember buffer, set local variables
13710 (org-mode)
13711 (org-set-local 'org-finish-function 'org-remember-finalize)
13712 (if (and file (string-match "\\S-" file) (not (file-directory-p file)))
13713 (org-set-local 'org-default-notes-file file))
13714 (if (and headline (stringp headline) (string-match "\\S-" headline))
13715 (org-set-local 'org-remember-default-headline headline))
13716 ;; Interactive template entries
13717 (goto-char (point-min))
13718 (while (re-search-forward "%^\\({\\([^}]*\\)}\\)?\\([gGuUtT]\\)?" nil t)
13719 (setq char (if (match-end 3) (match-string 3))
13720 prompt (if (match-end 2) (match-string 2)))
13721 (goto-char (match-beginning 0))
13722 (replace-match "")
13723 (setq completions nil default nil)
13724 (when prompt
13725 (setq completions (org-split-string prompt "|")
13726 prompt (pop completions)
13727 default (car completions)
13728 histvar (intern (concat
13729 "org-remember-template-prompt-history::"
13730 (or prompt "")))
13731 completions (mapcar 'list completions)))
13732 (cond
13733 ((member char '("G" "g"))
13734 (let* ((org-last-tags-completion-table
13735 (org-global-tags-completion-table
13736 (if (equal char "G") (org-agenda-files) (and file (list file)))))
13737 (org-add-colon-after-tag-completion t)
13738 (ins (completing-read
13739 (if prompt (concat prompt ": ") "Tags: ")
13740 'org-tags-completion-function nil nil nil
13741 'org-tags-history)))
13742 (setq ins (mapconcat 'identity
13743 (org-split-string ins (org-re "[^[:alnum:]_@]+"))
13744 ":"))
13745 (when (string-match "\\S-" ins)
13746 (or (equal (char-before) ?:) (insert ":"))
13747 (insert ins)
13748 (or (equal (char-after) ?:) (insert ":")))))
13749 (char
13750 (setq org-time-was-given (equal (upcase char) char))
13751 (setq time (org-read-date (equal (upcase char) "U") t nil
13752 prompt))
13753 (org-insert-time-stamp time org-time-was-given
13754 (member char '("u" "U"))
13755 nil nil (list org-end-time-was-given)))
13757 (insert (org-completing-read
13758 (concat (if prompt prompt "Enter string")
13759 (if default (concat " [" default "]"))
13760 ": ")
13761 completions nil nil nil histvar default)))))
13762 (goto-char (point-min))
13763 (if (re-search-forward "%\\?" nil t)
13764 (replace-match "")
13765 (and (re-search-forward "^[^#\n]" nil t) (backward-char 1))))
13766 (org-mode)
13767 (org-set-local 'org-finish-function 'org-remember-finalize))
13768 (when (save-excursion
13769 (goto-char (point-min))
13770 (re-search-forward "%!" nil t))
13771 (replace-match "")
13772 (add-hook 'post-command-hook 'org-remember-finish-immediately 'append)))
13774 (defun org-remember-finish-immediately ()
13775 "File remember note immediately.
13776 This should be run in `post-command-hook' and will remove itself
13777 from that hook."
13778 (remove-hook 'post-command-hook 'org-remember-finish-immediately)
13779 (when org-finish-function
13780 (funcall org-finish-function)))
13782 (defvar org-clock-marker) ; Defined below
13783 (defun org-remember-finalize ()
13784 "Finalize the remember process."
13785 (unless (fboundp 'remember-finalize)
13786 (defalias 'remember-finalize 'remember-buffer))
13787 (when (and org-clock-marker
13788 (equal (marker-buffer org-clock-marker) (current-buffer)))
13789 ;; FIXME: test this, this is w/o notetaking!
13790 (let (org-log-note-clock-out) (org-clock-out)))
13791 (when buffer-file-name
13792 (save-buffer)
13793 (setq buffer-file-name nil))
13794 (remember-finalize))
13796 ;;;###autoload
13797 (defun org-remember (&optional goto org-force-remember-template-char)
13798 "Call `remember'. If this is already a remember buffer, re-apply template.
13799 If there is an active region, make sure remember uses it as initial content
13800 of the remember buffer.
13802 When called interactively with a `C-u' prefix argument GOTO, don't remember
13803 anything, just go to the file/headline where the selected template usually
13804 stores its notes. With a double prefix arg `C-u C-u', go to the last
13805 note stored by remember.
13807 Lisp programs can set ORG-FORCE-REMEMBER-TEMPLATE-CHAR to a character
13808 associated with a template in `org-remember-templates'."
13809 (interactive "P")
13810 (cond
13811 ((equal goto '(4)) (org-go-to-remember-target))
13812 ((equal goto '(16)) (org-remember-goto-last-stored))
13814 (if (memq org-finish-function '(remember-buffer remember-finalize))
13815 (progn
13816 (when (< (length org-remember-templates) 2)
13817 (error "No other template available"))
13818 (erase-buffer)
13819 (let ((annotation (plist-get org-store-link-plist :annotation))
13820 (initial (plist-get org-store-link-plist :initial)))
13821 (org-remember-apply-template))
13822 (message "Press C-c C-c to remember data"))
13823 (if (org-region-active-p)
13824 (remember (buffer-substring (point) (mark)))
13825 (call-interactively 'remember))))))
13827 (defun org-remember-goto-last-stored ()
13828 "Go to the location where the last remember note was stored."
13829 (interactive)
13830 (bookmark-jump "org-remember-last-stored")
13831 (message "This is the last note stored by remember"))
13833 (defun org-go-to-remember-target (&optional template-key)
13834 "Go to the target location of a remember template.
13835 The user is queried for the template."
13836 (interactive)
13837 (let* ((entry (org-select-remember-template template-key))
13838 (file (nth 1 entry))
13839 (heading (nth 2 entry))
13840 visiting)
13841 (unless (and file (stringp file) (string-match "\\S-" file))
13842 (setq file org-default-notes-file))
13843 (unless (and heading (stringp heading) (string-match "\\S-" heading))
13844 (setq heading org-remember-default-headline))
13845 (setq visiting (org-find-base-buffer-visiting file))
13846 (if (not visiting) (find-file-noselect file))
13847 (switch-to-buffer (or visiting (get-file-buffer file)))
13848 (widen)
13849 (goto-char (point-min))
13850 (if (re-search-forward
13851 (concat "^\\*+[ \t]+" (regexp-quote heading)
13852 (org-re "\\([ \t]+:[[:alnum:]@_:]*\\)?[ \t]*$"))
13853 nil t)
13854 (goto-char (match-beginning 0))
13855 (error "Target headline not found: %s" heading))))
13857 (defvar org-note-abort nil) ; dynamically scoped
13859 ;;;###autoload
13860 (defun org-remember-handler ()
13861 "Store stuff from remember.el into an org file.
13862 First prompts for an org file. If the user just presses return, the value
13863 of `org-default-notes-file' is used.
13864 Then the command offers the headings tree of the selected file in order to
13865 file the text at a specific location.
13866 You can either immediately press RET to get the note appended to the
13867 file, or you can use vertical cursor motion and visibility cycling (TAB) to
13868 find a better place. Then press RET or <left> or <right> in insert the note.
13870 Key Cursor position Note gets inserted
13871 -----------------------------------------------------------------------------
13872 RET buffer-start as level 1 heading at end of file
13873 RET on headline as sublevel of the heading at cursor
13874 RET no heading at cursor position, level taken from context.
13875 Or use prefix arg to specify level manually.
13876 <left> on headline as same level, before current heading
13877 <right> on headline as same level, after current heading
13879 So the fastest way to store the note is to press RET RET to append it to
13880 the default file. This way your current train of thought is not
13881 interrupted, in accordance with the principles of remember.el.
13882 You can also get the fast execution without prompting by using
13883 C-u C-c C-c to exit the remember buffer. See also the variable
13884 `org-remember-store-without-prompt'.
13886 Before being stored away, the function ensures that the text has a
13887 headline, i.e. a first line that starts with a \"*\". If not, a headline
13888 is constructed from the current date and some additional data.
13890 If the variable `org-adapt-indentation' is non-nil, the entire text is
13891 also indented so that it starts in the same column as the headline
13892 \(i.e. after the stars).
13894 See also the variable `org-reverse-note-order'."
13895 (goto-char (point-min))
13896 (while (looking-at "^[ \t]*\n\\|^##.*\n")
13897 (replace-match ""))
13898 (goto-char (point-max))
13899 (beginning-of-line 1)
13900 (while (looking-at "[ \t]*$\\|##.*")
13901 (delete-region (1- (point)) (point-max))
13902 (beginning-of-line 1))
13903 (catch 'quit
13904 (if org-note-abort (throw 'quit nil))
13905 (let* ((txt (buffer-substring (point-min) (point-max)))
13906 (fastp (org-xor (equal current-prefix-arg '(4))
13907 org-remember-store-without-prompt))
13908 (file (cond
13909 (fastp org-default-notes-file)
13910 ((and (eq org-remember-interactive-interface 'refile)
13911 org-refile-targets)
13912 org-default-notes-file)
13913 ((not (and (equal current-prefix-arg '(16))
13914 org-remember-previous-location))
13915 (org-get-org-file))))
13916 (heading org-remember-default-headline)
13917 (visiting (and file (org-find-base-buffer-visiting file)))
13918 (org-startup-folded nil)
13919 (org-startup-align-all-tables nil)
13920 (org-goto-start-pos 1)
13921 spos exitcmd level indent reversed)
13922 (if (and (equal current-prefix-arg '(16)) org-remember-previous-location)
13923 (setq file (car org-remember-previous-location)
13924 heading (cdr org-remember-previous-location)
13925 fastp t))
13926 (setq current-prefix-arg nil)
13927 (if (string-match "[ \t\n]+\\'" txt)
13928 (setq txt (replace-match "" t t txt)))
13929 ;; Modify text so that it becomes a nice subtree which can be inserted
13930 ;; into an org tree.
13931 (let* ((lines (split-string txt "\n"))
13932 first)
13933 (setq first (car lines) lines (cdr lines))
13934 (if (string-match "^\\*+ " first)
13935 ;; Is already a headline
13936 (setq indent nil)
13937 ;; We need to add a headline: Use time and first buffer line
13938 (setq lines (cons first lines)
13939 first (concat "* " (current-time-string)
13940 " (" (remember-buffer-desc) ")")
13941 indent " "))
13942 (if (and org-adapt-indentation indent)
13943 (setq lines (mapcar
13944 (lambda (x)
13945 (if (string-match "\\S-" x)
13946 (concat indent x) x))
13947 lines)))
13948 (setq txt (concat first "\n"
13949 (mapconcat 'identity lines "\n"))))
13950 (if (string-match "\n[ \t]*\n[ \t\n]*\\'" txt)
13951 (setq txt (replace-match "\n\n" t t txt))
13952 (if (string-match "[ \t\n]*\\'" txt)
13953 (setq txt (replace-match "\n" t t txt))))
13954 ;; Put the modified text back into the remember buffer, for refile.
13955 (erase-buffer)
13956 (insert txt)
13957 (goto-char (point-min))
13958 (when (and (eq org-remember-interactive-interface 'refile)
13959 (not fastp))
13960 (org-refile nil (or visiting (find-file-noselect file)))
13961 (throw 'quit t))
13962 ;; Find the file
13963 (if (not visiting) (find-file-noselect file))
13964 (with-current-buffer (or visiting (get-file-buffer file))
13965 (unless (org-mode-p)
13966 (error "Target files for remember notes must be in Org-mode"))
13967 (save-excursion
13968 (save-restriction
13969 (widen)
13970 (and (goto-char (point-min))
13971 (not (re-search-forward "^\\* " nil t))
13972 (insert "\n* " (or heading "Notes") "\n"))
13973 (setq reversed (org-notes-order-reversed-p))
13975 ;; Find the default location
13976 (when (and heading (stringp heading) (string-match "\\S-" heading))
13977 (goto-char (point-min))
13978 (if (re-search-forward
13979 (concat "^\\*+[ \t]+" (regexp-quote heading)
13980 (org-re "\\([ \t]+:[[:alnum:]@_:]*\\)?[ \t]*$"))
13981 nil t)
13982 (setq org-goto-start-pos (match-beginning 0))
13983 (when fastp
13984 (goto-char (point-max))
13985 (unless (bolp) (newline))
13986 (insert "* " heading "\n")
13987 (setq org-goto-start-pos (point-at-bol 0)))))
13989 ;; Ask the User for a location, using the appropriate interface
13990 (cond
13991 (fastp (setq spos org-goto-start-pos
13992 exitcmd 'return))
13993 ((eq org-remember-interactive-interface 'outline)
13994 (setq spos (org-get-location (current-buffer)
13995 org-remember-help)
13996 exitcmd (cdr spos)
13997 spos (car spos)))
13998 ((eq org-remember-interactive-interface 'outline-path-completion)
13999 (let ((org-refile-targets '((nil . (:maxlevel . 10))))
14000 (org-refile-use-outline-path t))
14001 (setq spos (org-refile-get-location "Heading: ")
14002 exitcmd 'return
14003 spos (nth 3 spos))))
14004 (t (error "this should not hapen")))
14005 (if (not spos) (throw 'quit nil)) ; return nil to show we did
14006 ; not handle this note
14007 (goto-char spos)
14008 (cond ((org-on-heading-p t)
14009 (org-back-to-heading t)
14010 (setq level (funcall outline-level))
14011 (cond
14012 ((eq exitcmd 'return)
14013 ;; sublevel of current
14014 (setq org-remember-previous-location
14015 (cons (abbreviate-file-name file)
14016 (org-get-heading 'notags)))
14017 (if reversed
14018 (outline-next-heading)
14019 (org-end-of-subtree t)
14020 (if (not (bolp))
14021 (if (looking-at "[ \t]*\n")
14022 (beginning-of-line 2)
14023 (end-of-line 1)
14024 (insert "\n"))))
14025 (bookmark-set "org-remember-last-stored")
14026 (org-paste-subtree (org-get-legal-level level 1) txt))
14027 ((eq exitcmd 'left)
14028 ;; before current
14029 (bookmark-set "org-remember-last-stored")
14030 (org-paste-subtree level txt))
14031 ((eq exitcmd 'right)
14032 ;; after current
14033 (org-end-of-subtree t)
14034 (bookmark-set "org-remember-last-stored")
14035 (org-paste-subtree level txt))
14036 (t (error "This should not happen"))))
14038 ((and (bobp) (not reversed))
14039 ;; Put it at the end, one level below level 1
14040 (save-restriction
14041 (widen)
14042 (goto-char (point-max))
14043 (if (not (bolp)) (newline))
14044 (bookmark-set "org-remember-last-stored")
14045 (org-paste-subtree (org-get-legal-level 1 1) txt)))
14047 ((and (bobp) reversed)
14048 ;; Put it at the start, as level 1
14049 (save-restriction
14050 (widen)
14051 (goto-char (point-min))
14052 (re-search-forward "^\\*+ " nil t)
14053 (beginning-of-line 1)
14054 (bookmark-set "org-remember-last-stored")
14055 (org-paste-subtree 1 txt)))
14057 ;; Put it right there, with automatic level determined by
14058 ;; org-paste-subtree or from prefix arg
14059 (bookmark-set "org-remember-last-stored")
14060 (org-paste-subtree
14061 (if (numberp current-prefix-arg) current-prefix-arg)
14062 txt)))
14063 (when remember-save-after-remembering
14064 (save-buffer)
14065 (if (not visiting) (kill-buffer (current-buffer)))))))))
14067 t) ;; return t to indicate that we took care of this note.
14069 (defun org-get-org-file ()
14070 "Read a filename, with default directory `org-directory'."
14071 (let ((default (or org-default-notes-file remember-data-file)))
14072 (read-file-name (format "File name [%s]: " default)
14073 (file-name-as-directory org-directory)
14074 default)))
14076 (defun org-notes-order-reversed-p ()
14077 "Check if the current file should receive notes in reversed order."
14078 (cond
14079 ((not org-reverse-note-order) nil)
14080 ((eq t org-reverse-note-order) t)
14081 ((not (listp org-reverse-note-order)) nil)
14082 (t (catch 'exit
14083 (let ((all org-reverse-note-order)
14084 entry)
14085 (while (setq entry (pop all))
14086 (if (string-match (car entry) buffer-file-name)
14087 (throw 'exit (cdr entry))))
14088 nil)))))
14090 ;;; Refiling
14092 (defvar org-refile-target-table nil
14093 "The list of refile targets, created by `org-refile'.")
14095 (defvar org-agenda-new-buffers nil
14096 "Buffers created to visit agenda files.")
14098 (defun org-get-refile-targets (&optional default-buffer)
14099 "Produce a table with refile targets."
14100 (let ((entries (or org-refile-targets '((nil . (:level . 1)))))
14101 targets txt re files f desc descre)
14102 (with-current-buffer (or default-buffer (current-buffer))
14103 (while (setq entry (pop entries))
14104 (setq files (car entry) desc (cdr entry))
14105 (cond
14106 ((null files) (setq files (list (current-buffer))))
14107 ((eq files 'org-agenda-files)
14108 (setq files (org-agenda-files 'unrestricted)))
14109 ((and (symbolp files) (fboundp files))
14110 (setq files (funcall files)))
14111 ((and (symbolp files) (boundp files))
14112 (setq files (symbol-value files))))
14113 (if (stringp files) (setq files (list files)))
14114 (cond
14115 ((eq (car desc) :tag)
14116 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
14117 ((eq (car desc) :todo)
14118 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
14119 ((eq (car desc) :regexp)
14120 (setq descre (cdr desc)))
14121 ((eq (car desc) :level)
14122 (setq descre (concat "^\\*\\{" (number-to-string
14123 (if org-odd-levels-only
14124 (1- (* 2 (cdr desc)))
14125 (cdr desc)))
14126 "\\}[ \t]")))
14127 ((eq (car desc) :maxlevel)
14128 (setq descre (concat "^\\*\\{1," (number-to-string
14129 (if org-odd-levels-only
14130 (1- (* 2 (cdr desc)))
14131 (cdr desc)))
14132 "\\}[ \t]")))
14133 (t (error "Bad refiling target description %s" desc)))
14134 (while (setq f (pop files))
14135 (save-excursion
14136 (set-buffer (if (bufferp f) f (org-get-agenda-file-buffer f)))
14137 (if (bufferp f) (setq f (buffer-file-name (buffer-base-buffer f))))
14138 (save-excursion
14139 (save-restriction
14140 (widen)
14141 (goto-char (point-min))
14142 (while (re-search-forward descre nil t)
14143 (goto-char (point-at-bol))
14144 (when (looking-at org-complex-heading-regexp)
14145 (setq txt (match-string 4)
14146 re (concat "^" (regexp-quote
14147 (buffer-substring (match-beginning 1)
14148 (match-end 4)))))
14149 (if (match-end 5) (setq re (concat re "[ \t]+"
14150 (regexp-quote
14151 (match-string 5)))))
14152 (setq re (concat re "[ \t]*$"))
14153 (when org-refile-use-outline-path
14154 (setq txt (mapconcat 'identity
14155 (append
14156 (if (eq org-refile-use-outline-path 'file)
14157 (list (file-name-nondirectory
14158 (buffer-file-name (buffer-base-buffer))))
14159 (if (eq org-refile-use-outline-path 'full-file-path)
14160 (list (buffer-file-name (buffer-base-buffer)))))
14161 (org-get-outline-path)
14162 (list txt))
14163 "/")))
14164 (push (list txt f re (point)) targets))
14165 (goto-char (point-at-eol))))))))
14166 (nreverse targets))))
14168 (defun org-get-outline-path ()
14169 "Return the outline path to the current entry, as a list."
14170 (let (rtn)
14171 (save-excursion
14172 (while (org-up-heading-safe)
14173 (when (looking-at org-complex-heading-regexp)
14174 (push (org-match-string-no-properties 4) rtn)))
14175 rtn)))
14177 (defvar org-refile-history nil
14178 "History for refiling operations.")
14180 (defun org-refile (&optional goto default-buffer)
14181 "Move the entry at point to another heading.
14182 The list of target headings is compiled using the information in
14183 `org-refile-targets', which see. This list is created upon first use, and
14184 you can update it by calling this command with a double prefix (`C-u C-u').
14185 FIXME: Can we find a better way of updating?
14187 At the target location, the entry is filed as a subitem of the target heading.
14188 Depending on `org-reverse-note-order', the new subitem will either be the
14189 first of the last subitem.
14191 With prefix arg GOTO, the command will only visit the target location,
14192 not actually move anything.
14193 With a double prefix `C-c C-c', go to the location where the last refiling
14194 operation has put the subtree.
14196 With a double prefix argument, the command can be used to jump to any
14197 heading in the current buffer."
14198 (interactive "P")
14199 (let* ((cbuf (current-buffer))
14200 (filename (buffer-file-name (buffer-base-buffer cbuf)))
14201 pos it nbuf file re level reversed)
14202 (if (equal goto '(16))
14203 (org-refile-goto-last-stored)
14204 (when (setq it (org-refile-get-location
14205 (if goto "Goto: " "Refile to: ") default-buffer))
14206 (setq file (nth 1 it)
14207 re (nth 2 it)
14208 pos (nth 3 it))
14209 (setq nbuf (or (find-buffer-visiting file)
14210 (find-file-noselect file)))
14211 (if goto
14212 (progn
14213 (switch-to-buffer nbuf)
14214 (goto-char pos)
14215 (org-show-context 'org-goto))
14216 (org-copy-special)
14217 (save-excursion
14218 (set-buffer (setq nbuf (or (find-buffer-visiting file)
14219 (find-file-noselect file))))
14220 (setq reversed (org-notes-order-reversed-p))
14221 (save-excursion
14222 (save-restriction
14223 (widen)
14224 (goto-char pos)
14225 (looking-at outline-regexp)
14226 (setq level (org-get-legal-level (funcall outline-level) 1))
14227 (goto-char
14228 (if reversed
14229 (outline-next-heading)
14230 (or (save-excursion (outline-get-next-sibling))
14231 (org-end-of-subtree t t)
14232 (point-max))))
14233 (bookmark-set "org-refile-last-stored")
14234 (org-paste-subtree level))))
14235 (org-cut-special)
14236 (message "Entry refiled to \"%s\"" (car it)))))))
14238 (defun org-refile-goto-last-stored ()
14239 "Go to the location where the last refile was stored."
14240 (interactive)
14241 (bookmark-jump "org-refile-last-stored")
14242 (message "This is the location of the last refile"))
14244 (defun org-refile-get-location (&optional prompt default-buffer)
14245 "Prompt the user for a refile location, using PROMPT."
14246 (let ((org-refile-targets org-refile-targets)
14247 (org-refile-use-outline-path org-refile-use-outline-path))
14248 (setq org-refile-target-table (org-get-refile-targets default-buffer)))
14249 (unless org-refile-target-table
14250 (error "No refile targets"))
14251 (let* ((cbuf (current-buffer))
14252 (filename (buffer-file-name (buffer-base-buffer cbuf)))
14253 (fname (and filename (file-truename filename)))
14254 (tbl (mapcar
14255 (lambda (x)
14256 (if (not (equal fname (file-truename (nth 1 x))))
14257 (cons (concat (car x) " (" (file-name-nondirectory
14258 (nth 1 x)) ")")
14259 (cdr x))
14261 org-refile-target-table))
14262 (completion-ignore-case t))
14263 (assoc (completing-read prompt tbl nil t nil 'org-refile-history)
14264 tbl)))
14266 ;;;; Dynamic blocks
14268 (defun org-find-dblock (name)
14269 "Find the first dynamic block with name NAME in the buffer.
14270 If not found, stay at current position and return nil."
14271 (let (pos)
14272 (save-excursion
14273 (goto-char (point-min))
14274 (setq pos (and (re-search-forward (concat "^#\\+BEGIN:[ \t]+" name "\\>")
14275 nil t)
14276 (match-beginning 0))))
14277 (if pos (goto-char pos))
14278 pos))
14280 (defconst org-dblock-start-re
14281 "^#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
14282 "Matches the startline of a dynamic block, with parameters.")
14284 (defconst org-dblock-end-re "^#\\+END\\([: \t\r\n]\\|$\\)"
14285 "Matches the end of a dyhamic block.")
14287 (defun org-create-dblock (plist)
14288 "Create a dynamic block section, with parameters taken from PLIST.
14289 PLIST must containe a :name entry which is used as name of the block."
14290 (unless (bolp) (newline))
14291 (let ((name (plist-get plist :name)))
14292 (insert "#+BEGIN: " name)
14293 (while plist
14294 (if (eq (car plist) :name)
14295 (setq plist (cddr plist))
14296 (insert " " (prin1-to-string (pop plist)))))
14297 (insert "\n\n#+END:\n")
14298 (beginning-of-line -2)))
14300 (defun org-prepare-dblock ()
14301 "Prepare dynamic block for refresh.
14302 This empties the block, puts the cursor at the insert position and returns
14303 the property list including an extra property :name with the block name."
14304 (unless (looking-at org-dblock-start-re)
14305 (error "Not at a dynamic block"))
14306 (let* ((begdel (1+ (match-end 0)))
14307 (name (org-no-properties (match-string 1)))
14308 (params (append (list :name name)
14309 (read (concat "(" (match-string 3) ")")))))
14310 (unless (re-search-forward org-dblock-end-re nil t)
14311 (error "Dynamic block not terminated"))
14312 (delete-region begdel (match-beginning 0))
14313 (goto-char begdel)
14314 (open-line 1)
14315 params))
14317 (defun org-map-dblocks (&optional command)
14318 "Apply COMMAND to all dynamic blocks in the current buffer.
14319 If COMMAND is not given, use `org-update-dblock'."
14320 (let ((cmd (or command 'org-update-dblock))
14321 pos)
14322 (save-excursion
14323 (goto-char (point-min))
14324 (while (re-search-forward org-dblock-start-re nil t)
14325 (goto-char (setq pos (match-beginning 0)))
14326 (condition-case nil
14327 (funcall cmd)
14328 (error (message "Error during update of dynamic block")))
14329 (goto-char pos)
14330 (unless (re-search-forward org-dblock-end-re nil t)
14331 (error "Dynamic block not terminated"))))))
14333 (defun org-dblock-update (&optional arg)
14334 "User command for updating dynamic blocks.
14335 Update the dynamic block at point. With prefix ARG, update all dynamic
14336 blocks in the buffer."
14337 (interactive "P")
14338 (if arg
14339 (org-update-all-dblocks)
14340 (or (looking-at org-dblock-start-re)
14341 (org-beginning-of-dblock))
14342 (org-update-dblock)))
14344 (defun org-update-dblock ()
14345 "Update the dynamic block at point
14346 This means to empty the block, parse for parameters and then call
14347 the correct writing function."
14348 (save-window-excursion
14349 (let* ((pos (point))
14350 (line (org-current-line))
14351 (params (org-prepare-dblock))
14352 (name (plist-get params :name))
14353 (cmd (intern (concat "org-dblock-write:" name))))
14354 (message "Updating dynamic block `%s' at line %d..." name line)
14355 (funcall cmd params)
14356 (message "Updating dynamic block `%s' at line %d...done" name line)
14357 (goto-char pos))))
14359 (defun org-beginning-of-dblock ()
14360 "Find the beginning of the dynamic block at point.
14361 Error if there is no scuh block at point."
14362 (let ((pos (point))
14363 beg)
14364 (end-of-line 1)
14365 (if (and (re-search-backward org-dblock-start-re nil t)
14366 (setq beg (match-beginning 0))
14367 (re-search-forward org-dblock-end-re nil t)
14368 (> (match-end 0) pos))
14369 (goto-char beg)
14370 (goto-char pos)
14371 (error "Not in a dynamic block"))))
14373 (defun org-update-all-dblocks ()
14374 "Update all dynamic blocks in the buffer.
14375 This function can be used in a hook."
14376 (when (org-mode-p)
14377 (org-map-dblocks 'org-update-dblock)))
14380 ;;;; Completion
14382 (defconst org-additional-option-like-keywords
14383 '("BEGIN_HTML" "BEGIN_LaTeX" "END_HTML" "END_LaTeX"
14384 "ORGTBL" "HTML:" "LaTeX:" "BEGIN:" "END:" "DATE:" "TBLFM"
14385 "BEGIN_EXAMPLE" "END_EXAMPLE"))
14387 (defun org-complete (&optional arg)
14388 "Perform completion on word at point.
14389 At the beginning of a headline, this completes TODO keywords as given in
14390 `org-todo-keywords'.
14391 If the current word is preceded by a backslash, completes the TeX symbols
14392 that are supported for HTML support.
14393 If the current word is preceded by \"#+\", completes special words for
14394 setting file options.
14395 In the line after \"#+STARTUP:, complete valid keywords.\"
14396 At all other locations, this simply calls the value of
14397 `org-completion-fallback-command'."
14398 (interactive "P")
14399 (org-without-partial-completion
14400 (catch 'exit
14401 (let* ((end (point))
14402 (beg1 (save-excursion
14403 (skip-chars-backward (org-re "[:alnum:]_@"))
14404 (point)))
14405 (beg (save-excursion
14406 (skip-chars-backward "a-zA-Z0-9_:$")
14407 (point)))
14408 (confirm (lambda (x) (stringp (car x))))
14409 (searchhead (equal (char-before beg) ?*))
14410 (tag (and (equal (char-before beg1) ?:)
14411 (equal (char-after (point-at-bol)) ?*)))
14412 (prop (and (equal (char-before beg1) ?:)
14413 (not (equal (char-after (point-at-bol)) ?*))))
14414 (texp (equal (char-before beg) ?\\))
14415 (link (equal (char-before beg) ?\[))
14416 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
14417 beg)
14418 "#+"))
14419 (startup (string-match "^#\\+STARTUP:.*"
14420 (buffer-substring (point-at-bol) (point))))
14421 (completion-ignore-case opt)
14422 (type nil)
14423 (tbl nil)
14424 (table (cond
14425 (opt
14426 (setq type :opt)
14427 (append
14428 (mapcar
14429 (lambda (x)
14430 (string-match "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
14431 (cons (match-string 2 x) (match-string 1 x)))
14432 (org-split-string (org-get-current-options) "\n"))
14433 (mapcar 'list org-additional-option-like-keywords)))
14434 (startup
14435 (setq type :startup)
14436 org-startup-options)
14437 (link (append org-link-abbrev-alist-local
14438 org-link-abbrev-alist))
14439 (texp
14440 (setq type :tex)
14441 org-html-entities)
14442 ((string-match "\\`\\*+[ \t]+\\'"
14443 (buffer-substring (point-at-bol) beg))
14444 (setq type :todo)
14445 (mapcar 'list org-todo-keywords-1))
14446 (searchhead
14447 (setq type :searchhead)
14448 (save-excursion
14449 (goto-char (point-min))
14450 (while (re-search-forward org-todo-line-regexp nil t)
14451 (push (list
14452 (org-make-org-heading-search-string
14453 (match-string 3) t))
14454 tbl)))
14455 tbl)
14456 (tag (setq type :tag beg beg1)
14457 (or org-tag-alist (org-get-buffer-tags)))
14458 (prop (setq type :prop beg beg1)
14459 (mapcar 'list (org-buffer-property-keys nil t t)))
14460 (t (progn
14461 (call-interactively org-completion-fallback-command)
14462 (throw 'exit nil)))))
14463 (pattern (buffer-substring-no-properties beg end))
14464 (completion (try-completion pattern table confirm)))
14465 (cond ((eq completion t)
14466 (if (not (assoc (upcase pattern) table))
14467 (message "Already complete")
14468 (if (equal type :opt)
14469 (insert (substring (cdr (assoc (upcase pattern) table))
14470 (length pattern)))
14471 (if (memq type '(:tag :prop)) (insert ":")))))
14472 ((null completion)
14473 (message "Can't find completion for \"%s\"" pattern)
14474 (ding))
14475 ((not (string= pattern completion))
14476 (delete-region beg end)
14477 (if (string-match " +$" completion)
14478 (setq completion (replace-match "" t t completion)))
14479 (insert completion)
14480 (if (get-buffer-window "*Completions*")
14481 (delete-window (get-buffer-window "*Completions*")))
14482 (if (assoc completion table)
14483 (if (eq type :todo) (insert " ")
14484 (if (memq type '(:tag :prop)) (insert ":"))))
14485 (if (and (equal type :opt) (assoc completion table))
14486 (message "%s" (substitute-command-keys
14487 "Press \\[org-complete] again to insert example settings"))))
14489 (message "Making completion list...")
14490 (let ((list (sort (all-completions pattern table confirm)
14491 'string<)))
14492 (with-output-to-temp-buffer "*Completions*"
14493 (condition-case nil
14494 ;; Protection needed for XEmacs and emacs 21
14495 (display-completion-list list pattern)
14496 (error (display-completion-list list)))))
14497 (message "Making completion list...%s" "done")))))))
14499 ;;;; TODO, DEADLINE, Comments
14501 (defun org-toggle-comment ()
14502 "Change the COMMENT state of an entry."
14503 (interactive)
14504 (save-excursion
14505 (org-back-to-heading)
14506 (let (case-fold-search)
14507 (if (looking-at (concat outline-regexp
14508 "\\( *\\<" org-comment-string "\\>[ \t]*\\)"))
14509 (replace-match "" t t nil 1)
14510 (if (looking-at outline-regexp)
14511 (progn
14512 (goto-char (match-end 0))
14513 (insert org-comment-string " ")))))))
14515 (defvar org-last-todo-state-is-todo nil
14516 "This is non-nil when the last TODO state change led to a TODO state.
14517 If the last change removed the TODO tag or switched to DONE, then
14518 this is nil.")
14520 (defvar org-setting-tags nil) ; dynamically skiped
14522 ;; FIXME: better place
14523 (defun org-property-or-variable-value (var &optional inherit)
14524 "Check if there is a property fixing the value of VAR.
14525 If yes, return this value. If not, return the current value of the variable."
14526 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
14527 (if (and prop (stringp prop) (string-match "\\S-" prop))
14528 (read prop)
14529 (symbol-value var))))
14531 (defun org-parse-local-options (string var)
14532 "Parse STRING for startup setting relevant for variable VAR."
14533 (let ((rtn (symbol-value var))
14534 e opts)
14535 (save-match-data
14536 (if (or (not string) (not (string-match "\\S-" string)))
14538 (setq opts (delq nil (mapcar (lambda (x)
14539 (setq e (assoc x org-startup-options))
14540 (if (eq (nth 1 e) var) e nil))
14541 (org-split-string string "[ \t]+"))))
14542 (if (not opts)
14544 (setq rtn nil)
14545 (while (setq e (pop opts))
14546 (if (not (nth 3 e))
14547 (setq rtn (nth 2 e))
14548 (if (not (listp rtn)) (setq rtn nil))
14549 (push (nth 2 e) rtn)))
14550 rtn)))))
14552 (defvar org-blocker-hook nil
14553 "Hook for functions that are allowed to block a state change.
14555 Each function gets as its single argument a property list, see
14556 `org-trigger-hook' for more information about this list.
14558 If any of the functions in this hook returns nil, the state change
14559 is blocked.")
14561 (defvar org-trigger-hook nil
14562 "Hook for functions that are triggered by a state change.
14564 Each function gets as its single argument a property list with at least
14565 the following elements:
14567 (:type type-of-change :position pos-at-entry-start
14568 :from old-state :to new-state)
14570 Depending on the type, more properties may be present.
14572 This mechanism is currently implemented for:
14574 TODO state changes
14575 ------------------
14576 :type todo-state-change
14577 :from previous state (keyword as a string), or nil
14578 :to new state (keyword as a string), or nil")
14581 (defun org-todo (&optional arg)
14582 "Change the TODO state of an item.
14583 The state of an item is given by a keyword at the start of the heading,
14584 like
14585 *** TODO Write paper
14586 *** DONE Call mom
14588 The different keywords are specified in the variable `org-todo-keywords'.
14589 By default the available states are \"TODO\" and \"DONE\".
14590 So for this example: when the item starts with TODO, it is changed to DONE.
14591 When it starts with DONE, the DONE is removed. And when neither TODO nor
14592 DONE are present, add TODO at the beginning of the heading.
14594 With C-u prefix arg, use completion to determine the new state.
14595 With numeric prefix arg, switch to that state.
14597 For calling through lisp, arg is also interpreted in the following way:
14598 'none -> empty state
14599 \"\"(empty string) -> switch to empty state
14600 'done -> switch to DONE
14601 'nextset -> switch to the next set of keywords
14602 'previousset -> switch to the previous set of keywords
14603 \"WAITING\" -> switch to the specified keyword, but only if it
14604 really is a member of `org-todo-keywords'."
14605 (interactive "P")
14606 (save-excursion
14607 (catch 'exit
14608 (org-back-to-heading)
14609 (if (looking-at outline-regexp) (goto-char (1- (match-end 0))))
14610 (or (looking-at (concat " +" org-todo-regexp " *"))
14611 (looking-at " *"))
14612 (let* ((match-data (match-data))
14613 (startpos (point-at-bol))
14614 (logging (save-match-data (org-entry-get nil "LOGGING" t)))
14615 (org-log-done org-log-done)
14616 (org-log-repeat org-log-repeat)
14617 (org-todo-log-states org-todo-log-states)
14618 (this (match-string 1))
14619 (hl-pos (match-beginning 0))
14620 (head (org-get-todo-sequence-head this))
14621 (ass (assoc head org-todo-kwd-alist))
14622 (interpret (nth 1 ass))
14623 (done-word (nth 3 ass))
14624 (final-done-word (nth 4 ass))
14625 (last-state (or this ""))
14626 (completion-ignore-case t)
14627 (member (member this org-todo-keywords-1))
14628 (tail (cdr member))
14629 (state (cond
14630 ((and org-todo-key-trigger
14631 (or (and (equal arg '(4)) (eq org-use-fast-todo-selection 'prefix))
14632 (and (not arg) org-use-fast-todo-selection
14633 (not (eq org-use-fast-todo-selection 'prefix)))))
14634 ;; Use fast selection
14635 (org-fast-todo-selection))
14636 ((and (equal arg '(4))
14637 (or (not org-use-fast-todo-selection)
14638 (not org-todo-key-trigger)))
14639 ;; Read a state with completion
14640 (completing-read "State: " (mapcar (lambda(x) (list x))
14641 org-todo-keywords-1)
14642 nil t))
14643 ((eq arg 'right)
14644 (if this
14645 (if tail (car tail) nil)
14646 (car org-todo-keywords-1)))
14647 ((eq arg 'left)
14648 (if (equal member org-todo-keywords-1)
14650 (if this
14651 (nth (- (length org-todo-keywords-1) (length tail) 2)
14652 org-todo-keywords-1)
14653 (org-last org-todo-keywords-1))))
14654 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
14655 (setq arg nil))) ; hack to fall back to cycling
14656 (arg
14657 ;; user or caller requests a specific state
14658 (cond
14659 ((equal arg "") nil)
14660 ((eq arg 'none) nil)
14661 ((eq arg 'done) (or done-word (car org-done-keywords)))
14662 ((eq arg 'nextset)
14663 (or (car (cdr (member head org-todo-heads)))
14664 (car org-todo-heads)))
14665 ((eq arg 'previousset)
14666 (let ((org-todo-heads (reverse org-todo-heads)))
14667 (or (car (cdr (member head org-todo-heads)))
14668 (car org-todo-heads))))
14669 ((car (member arg org-todo-keywords-1)))
14670 ((nth (1- (prefix-numeric-value arg))
14671 org-todo-keywords-1))))
14672 ((null member) (or head (car org-todo-keywords-1)))
14673 ((equal this final-done-word) nil) ;; -> make empty
14674 ((null tail) nil) ;; -> first entry
14675 ((eq interpret 'sequence)
14676 (car tail))
14677 ((memq interpret '(type priority))
14678 (if (eq this-command last-command)
14679 (car tail)
14680 (if (> (length tail) 0)
14681 (or done-word (car org-done-keywords))
14682 nil)))
14683 (t nil)))
14684 (next (if state (concat " " state " ") " "))
14685 (change-plist (list :type 'todo-state-change :from this :to state
14686 :position startpos))
14687 dolog now-done-p)
14688 (when org-blocker-hook
14689 (unless (save-excursion
14690 (save-match-data
14691 (run-hook-with-args-until-failure
14692 'org-blocker-hook change-plist)))
14693 (if (interactive-p)
14694 (error "TODO state change from %s to %s blocked" this state)
14695 ;; fail silently
14696 (message "TODO state change from %s to %s blocked" this state)
14697 (throw 'exit nil))))
14698 (store-match-data match-data)
14699 (replace-match next t t)
14700 (unless (pos-visible-in-window-p hl-pos)
14701 (message "TODO state changed to %s" (org-trim next)))
14702 (unless head
14703 (setq head (org-get-todo-sequence-head state)
14704 ass (assoc head org-todo-kwd-alist)
14705 interpret (nth 1 ass)
14706 done-word (nth 3 ass)
14707 final-done-word (nth 4 ass)))
14708 (when (memq arg '(nextset previousset))
14709 (message "Keyword-Set %d/%d: %s"
14710 (- (length org-todo-sets) -1
14711 (length (memq (assoc state org-todo-sets) org-todo-sets)))
14712 (length org-todo-sets)
14713 (mapconcat 'identity (assoc state org-todo-sets) " ")))
14714 (setq org-last-todo-state-is-todo
14715 (not (member state org-done-keywords)))
14716 (setq now-done-p (and (member state org-done-keywords)
14717 (not (member this org-done-keywords))))
14718 (and logging (org-local-logging logging))
14719 (when (and (or org-todo-log-states org-log-done)
14720 (not (memq arg '(nextset previousset))))
14721 ;; we need to look at recording a time and note
14722 (setq dolog (or (nth 1 (assoc state org-todo-log-states))
14723 (nth 2 (assoc this org-todo-log-states))))
14724 (when (and state
14725 (member state org-not-done-keywords)
14726 (not (member this org-not-done-keywords)))
14727 ;; This is now a todo state and was not one before
14728 ;; If there was a CLOSED time stamp, get rid of it.
14729 (org-add-planning-info nil nil 'closed))
14730 (when (and now-done-p org-log-done)
14731 ;; It is now done, and it was not done before
14732 (org-add-planning-info 'closed (org-current-time))
14733 (if (and (not dolog) (eq 'note org-log-done))
14734 (org-add-log-maybe 'done state 'findpos 'note)))
14735 (when (and state dolog)
14736 ;; This is a non-nil state, and we need to log it
14737 (org-add-log-maybe 'state state 'findpos dolog)))
14738 ;; Fixup tag positioning
14739 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
14740 (run-hooks 'org-after-todo-state-change-hook)
14741 (if (and arg (not (member state org-done-keywords)))
14742 (setq head (org-get-todo-sequence-head state)))
14743 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
14744 ;; Do we need to trigger a repeat?
14745 (when now-done-p (org-auto-repeat-maybe state))
14746 ;; Fixup cursor location if close to the keyword
14747 (if (and (outline-on-heading-p)
14748 (not (bolp))
14749 (save-excursion (beginning-of-line 1)
14750 (looking-at org-todo-line-regexp))
14751 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
14752 (progn
14753 (goto-char (or (match-end 2) (match-end 1)))
14754 (just-one-space)))
14755 (when org-trigger-hook
14756 (save-excursion
14757 (run-hook-with-args 'org-trigger-hook change-plist)))))))
14759 (defun org-local-logging (value)
14760 "Get logging settings from a property VALUE."
14761 (let* (words w a)
14762 ;; directly set the variables, they are already local.
14763 (setq org-log-done nil
14764 org-log-repeat nil
14765 org-todo-log-states nil)
14766 (setq words (org-split-string value))
14767 (while (setq w (pop words))
14768 (cond
14769 ((setq a (assoc w org-startup-options))
14770 (and (member (nth 1 a) '(org-log-done org-log-repeat))
14771 (set (nth 1 a) (nth 2 a))))
14772 ((setq a (org-extract-log-state-settings w))
14773 (and (member (car a) org-todo-keywords-1)
14774 (push a org-todo-log-states)))))))
14776 (defun org-get-todo-sequence-head (kwd)
14777 "Return the head of the TODO sequence to which KWD belongs.
14778 If KWD is not set, check if there is a text property remembering the
14779 right sequence."
14780 (let (p)
14781 (cond
14782 ((not kwd)
14783 (or (get-text-property (point-at-bol) 'org-todo-head)
14784 (progn
14785 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
14786 nil (point-at-eol)))
14787 (get-text-property p 'org-todo-head))))
14788 ((not (member kwd org-todo-keywords-1))
14789 (car org-todo-keywords-1))
14790 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
14792 (defun org-fast-todo-selection ()
14793 "Fast TODO keyword selection with single keys.
14794 Returns the new TODO keyword, or nil if no state change should occur."
14795 (let* ((fulltable org-todo-key-alist)
14796 (done-keywords org-done-keywords) ;; needed for the faces.
14797 (maxlen (apply 'max (mapcar
14798 (lambda (x)
14799 (if (stringp (car x)) (string-width (car x)) 0))
14800 fulltable)))
14801 (expert nil)
14802 (fwidth (+ maxlen 3 1 3))
14803 (ncol (/ (- (window-width) 4) fwidth))
14804 tg cnt e c tbl
14805 groups ingroup)
14806 (save-window-excursion
14807 (if expert
14808 (set-buffer (get-buffer-create " *Org todo*"))
14809 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
14810 (erase-buffer)
14811 (org-set-local 'org-done-keywords done-keywords)
14812 (setq tbl fulltable cnt 0)
14813 (while (setq e (pop tbl))
14814 (cond
14815 ((equal e '(:startgroup))
14816 (push '() groups) (setq ingroup t)
14817 (when (not (= cnt 0))
14818 (setq cnt 0)
14819 (insert "\n"))
14820 (insert "{ "))
14821 ((equal e '(:endgroup))
14822 (setq ingroup nil cnt 0)
14823 (insert "}\n"))
14825 (setq tg (car e) c (cdr e))
14826 (if ingroup (push tg (car groups)))
14827 (setq tg (org-add-props tg nil 'face
14828 (org-get-todo-face tg)))
14829 (if (and (= cnt 0) (not ingroup)) (insert " "))
14830 (insert "[" c "] " tg (make-string
14831 (- fwidth 4 (length tg)) ?\ ))
14832 (when (= (setq cnt (1+ cnt)) ncol)
14833 (insert "\n")
14834 (if ingroup (insert " "))
14835 (setq cnt 0)))))
14836 (insert "\n")
14837 (goto-char (point-min))
14838 (if (and (not expert) (fboundp 'fit-window-to-buffer))
14839 (fit-window-to-buffer))
14840 (message "[a-z..]:Set [SPC]:clear")
14841 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
14842 (cond
14843 ((or (= c ?\C-g)
14844 (and (= c ?q) (not (rassoc c fulltable))))
14845 (setq quit-flag t))
14846 ((= c ?\ ) nil)
14847 ((setq e (rassoc c fulltable) tg (car e))
14849 (t (setq quit-flag t))))))
14851 (defun org-get-repeat ()
14852 "Check if tere is a deadline/schedule with repeater in this entry."
14853 (save-match-data
14854 (save-excursion
14855 (org-back-to-heading t)
14856 (if (re-search-forward
14857 org-repeat-re (save-excursion (outline-next-heading) (point)) t)
14858 (match-string 1)))))
14860 (defvar org-last-changed-timestamp)
14861 (defvar org-log-post-message)
14862 (defvar org-log-note-purpose)
14863 (defun org-auto-repeat-maybe (done-word)
14864 "Check if the current headline contains a repeated deadline/schedule.
14865 If yes, set TODO state back to what it was and change the base date
14866 of repeating deadline/scheduled time stamps to new date.
14867 This function is run automatically after each state change to a DONE state."
14868 ;; last-state is dynamically scoped into this function
14869 (let* ((repeat (org-get-repeat))
14870 (aa (assoc last-state org-todo-kwd-alist))
14871 (interpret (nth 1 aa))
14872 (head (nth 2 aa))
14873 (whata '(("d" . day) ("m" . month) ("y" . year)))
14874 (msg "Entry repeats: ")
14875 (org-log-done nil)
14876 (org-todo-log-states nil)
14877 re type n what ts)
14878 (when repeat
14879 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
14880 (org-todo (if (eq interpret 'type) last-state head))
14881 (when (and org-log-repeat
14882 (or (not (memq 'org-add-log-note
14883 (default-value 'post-command-hook)))
14884 (eq org-log-note-purpose 'done)))
14885 ;; Make sure a note is taken;
14886 (org-add-log-maybe 'state (or done-word (car org-done-keywords))
14887 'findpos org-log-repeat))
14888 (org-back-to-heading t)
14889 (org-add-planning-info nil nil 'closed)
14890 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
14891 org-deadline-time-regexp "\\)\\|\\("
14892 org-ts-regexp "\\)"))
14893 (while (re-search-forward
14894 re (save-excursion (outline-next-heading) (point)) t)
14895 (setq type (if (match-end 1) org-scheduled-string
14896 (if (match-end 3) org-deadline-string "Plain:"))
14897 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
14898 (when (string-match "\\([-+]?[0-9]+\\)\\([dwmy]\\)" ts)
14899 (setq n (string-to-number (match-string 1 ts))
14900 what (match-string 2 ts))
14901 (if (equal what "w") (setq n (* n 7) what "d"))
14902 (org-timestamp-change n (cdr (assoc what whata)))
14903 (setq msg (concat msg type org-last-changed-timestamp " "))))
14904 (setq org-log-post-message msg)
14905 (message "%s" msg))))
14907 (defun org-show-todo-tree (arg)
14908 "Make a compact tree which shows all headlines marked with TODO.
14909 The tree will show the lines where the regexp matches, and all higher
14910 headlines above the match.
14911 With a \\[universal-argument] prefix, also show the DONE entries.
14912 With a numeric prefix N, construct a sparse tree for the Nth element
14913 of `org-todo-keywords-1'."
14914 (interactive "P")
14915 (let ((case-fold-search nil)
14916 (kwd-re
14917 (cond ((null arg) org-not-done-regexp)
14918 ((equal arg '(4))
14919 (let ((kwd (completing-read "Keyword (or KWD1|KWD2|...): "
14920 (mapcar 'list org-todo-keywords-1))))
14921 (concat "\\("
14922 (mapconcat 'identity (org-split-string kwd "|") "\\|")
14923 "\\)\\>")))
14924 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
14925 (regexp-quote (nth (1- (prefix-numeric-value arg))
14926 org-todo-keywords-1)))
14927 (t (error "Invalid prefix argument: %s" arg)))))
14928 (message "%d TODO entries found"
14929 (org-occur (concat "^" outline-regexp " *" kwd-re )))))
14931 (defun org-deadline (&optional remove)
14932 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
14933 With argument REMOVE, remove any deadline from the item."
14934 (interactive "P")
14935 (if remove
14936 (progn
14937 (org-remove-timestamp-with-keyword org-deadline-string)
14938 (message "Item no longer has a deadline."))
14939 (org-add-planning-info 'deadline nil 'closed)))
14941 (defun org-schedule (&optional remove)
14942 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
14943 With argument REMOVE, remove any scheduling date from the item."
14944 (interactive "P")
14945 (if remove
14946 (progn
14947 (org-remove-timestamp-with-keyword org-scheduled-string)
14948 (message "Item is no longer scheduled."))
14949 (org-add-planning-info 'scheduled nil 'closed)))
14951 (defun org-remove-timestamp-with-keyword (keyword)
14952 "Remove all time stamps with KEYWORD in the current entry."
14953 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
14954 beg)
14955 (save-excursion
14956 (org-back-to-heading t)
14957 (setq beg (point))
14958 (org-end-of-subtree t t)
14959 (while (re-search-backward re beg t)
14960 (replace-match "")
14961 (unless (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
14962 (delete-region (point-at-bol) (min (1+ (point)) (point-max))))))))
14964 (defun org-add-planning-info (what &optional time &rest remove)
14965 "Insert new timestamp with keyword in the line directly after the headline.
14966 WHAT indicates what kind of time stamp to add. TIME indicated the time to use.
14967 If non is given, the user is prompted for a date.
14968 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
14969 be removed."
14970 (interactive)
14971 (let (org-time-was-given org-end-time-was-given)
14972 (when what (setq time (or time (org-read-date nil 'to-time))))
14973 (when (and org-insert-labeled-timestamps-at-point
14974 (member what '(scheduled deadline)))
14975 (insert
14976 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
14977 (org-insert-time-stamp time org-time-was-given
14978 nil nil nil (list org-end-time-was-given))
14979 (setq what nil))
14980 (save-excursion
14981 (save-restriction
14982 (let (col list elt ts buffer-invisibility-spec)
14983 (org-back-to-heading t)
14984 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
14985 (goto-char (match-end 1))
14986 (setq col (current-column))
14987 (goto-char (match-end 0))
14988 (if (eobp) (insert "\n") (forward-char 1))
14989 (if (and (not (looking-at outline-regexp))
14990 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
14991 "[^\r\n]*"))
14992 (not (equal (match-string 1) org-clock-string)))
14993 (narrow-to-region (match-beginning 0) (match-end 0))
14994 (insert-before-markers "\n")
14995 (backward-char 1)
14996 (narrow-to-region (point) (point))
14997 (indent-to-column col))
14998 ;; Check if we have to remove something.
14999 (setq list (cons what remove))
15000 (while list
15001 (setq elt (pop list))
15002 (goto-char (point-min))
15003 (when (or (and (eq elt 'scheduled)
15004 (re-search-forward org-scheduled-time-regexp nil t))
15005 (and (eq elt 'deadline)
15006 (re-search-forward org-deadline-time-regexp nil t))
15007 (and (eq elt 'closed)
15008 (re-search-forward org-closed-time-regexp nil t)))
15009 (replace-match "")
15010 (if (looking-at "--+<[^>]+>") (replace-match ""))
15011 (if (looking-at " +") (replace-match ""))))
15012 (goto-char (point-max))
15013 (when what
15014 (insert
15015 (if (not (equal (char-before) ?\ )) " " "")
15016 (cond ((eq what 'scheduled) org-scheduled-string)
15017 ((eq what 'deadline) org-deadline-string)
15018 ((eq what 'closed) org-closed-string))
15019 " ")
15020 (setq ts (org-insert-time-stamp
15021 time
15022 (or org-time-was-given
15023 (and (eq what 'closed) org-log-done-with-time))
15024 (eq what 'closed)
15025 nil nil (list org-end-time-was-given)))
15026 (end-of-line 1))
15027 (goto-char (point-min))
15028 (widen)
15029 (if (looking-at "[ \t]+\r?\n")
15030 (replace-match ""))
15031 ts)))))
15033 (defvar org-log-note-marker (make-marker))
15034 (defvar org-log-note-purpose nil)
15035 (defvar org-log-note-state nil)
15036 (defvar org-log-note-how nil)
15037 (defvar org-log-note-window-configuration nil)
15038 (defvar org-log-note-return-to (make-marker))
15039 (defvar org-log-post-message nil
15040 "Message to be displayed after a log note has been stored.
15041 The auto-repeater uses this.")
15043 (defun org-add-log-maybe (&optional purpose state findpos how)
15044 "Set up the post command hook to take a note.
15045 If this is about to TODO state change, the new state is expected in STATE.
15046 When FINDPOS is non-nil, find the correct position for the note in
15047 the current entry. If not, assume that it can be inserted at point."
15048 (save-excursion
15049 (when findpos
15050 (org-back-to-heading t)
15051 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"
15052 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
15053 "[^\r\n]*\\)?"))
15054 (goto-char (match-end 0))
15055 (unless org-log-states-order-reversed
15056 (and (= (char-after) ?\n) (forward-char 1))
15057 (org-skip-over-state-notes)
15058 (skip-chars-backward " \t\n\r")))
15059 (move-marker org-log-note-marker (point))
15060 (setq org-log-note-purpose purpose
15061 org-log-note-state state
15062 org-log-note-how how)
15063 (add-hook 'post-command-hook 'org-add-log-note 'append)))
15065 (defun org-skip-over-state-notes ()
15066 "Skip past the list of State notes in an entry."
15067 (if (looking-at "\n[ \t]*- State") (forward-char 1))
15068 (while (looking-at "[ \t]*- State")
15069 (condition-case nil
15070 (org-next-item)
15071 (error (org-end-of-item)))))
15073 (defun org-add-log-note (&optional purpose)
15074 "Pop up a window for taking a note, and add this note later at point."
15075 (remove-hook 'post-command-hook 'org-add-log-note)
15076 (setq org-log-note-window-configuration (current-window-configuration))
15077 (delete-other-windows)
15078 (move-marker org-log-note-return-to (point))
15079 (switch-to-buffer (marker-buffer org-log-note-marker))
15080 (goto-char org-log-note-marker)
15081 (org-switch-to-buffer-other-window "*Org Note*")
15082 (erase-buffer)
15083 (if (memq org-log-note-how '(time state)) ; FIXME: time or state????????????
15084 (org-store-log-note)
15085 (let ((org-inhibit-startup t)) (org-mode))
15086 (insert (format "# Insert note for %s.
15087 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
15088 (cond
15089 ((eq org-log-note-purpose 'clock-out) "stopped clock")
15090 ((eq org-log-note-purpose 'done) "closed todo item")
15091 ((eq org-log-note-purpose 'state)
15092 (format "state change to \"%s\"" org-log-note-state))
15093 (t (error "This should not happen")))))
15094 (org-set-local 'org-finish-function 'org-store-log-note)))
15096 (defun org-store-log-note ()
15097 "Finish taking a log note, and insert it to where it belongs."
15098 (let ((txt (buffer-string))
15099 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
15100 lines ind)
15101 (kill-buffer (current-buffer))
15102 (while (string-match "\\`#.*\n[ \t\n]*" txt)
15103 (setq txt (replace-match "" t t txt)))
15104 (if (string-match "\\s-+\\'" txt)
15105 (setq txt (replace-match "" t t txt)))
15106 (setq lines (org-split-string txt "\n"))
15107 (when (and note (string-match "\\S-" note))
15108 (setq note
15109 (org-replace-escapes
15110 note
15111 (list (cons "%u" (user-login-name))
15112 (cons "%U" user-full-name)
15113 (cons "%t" (format-time-string
15114 (org-time-stamp-format 'long 'inactive)
15115 (current-time)))
15116 (cons "%s" (if org-log-note-state
15117 (concat "\"" org-log-note-state "\"")
15118 "")))))
15119 (if lines (setq note (concat note " \\\\")))
15120 (push note lines))
15121 (when (or current-prefix-arg org-note-abort) (setq lines nil))
15122 (when lines
15123 (save-excursion
15124 (set-buffer (marker-buffer org-log-note-marker))
15125 (save-excursion
15126 (goto-char org-log-note-marker)
15127 (move-marker org-log-note-marker nil)
15128 (end-of-line 1)
15129 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
15130 (indent-relative nil)
15131 (insert "- " (pop lines))
15132 (org-indent-line-function)
15133 (beginning-of-line 1)
15134 (looking-at "[ \t]*")
15135 (setq ind (concat (match-string 0) " "))
15136 (end-of-line 1)
15137 (while lines (insert "\n" ind (pop lines)))))))
15138 (set-window-configuration org-log-note-window-configuration)
15139 (with-current-buffer (marker-buffer org-log-note-return-to)
15140 (goto-char org-log-note-return-to))
15141 (move-marker org-log-note-return-to nil)
15142 (and org-log-post-message (message "%s" org-log-post-message)))
15144 ;; FIXME: what else would be useful?
15145 ;; - priority
15146 ;; - date
15148 (defun org-sparse-tree (&optional arg)
15149 "Create a sparse tree, prompt for the details.
15150 This command can create sparse trees. You first need to select the type
15151 of match used to create the tree:
15153 t Show entries with a specific TODO keyword.
15154 T Show entries selected by a tags match.
15155 p Enter a property name and its value (both with completion on existing
15156 names/values) and show entries with that property.
15157 r Show entries matching a regular expression
15158 d Show deadlines due within `org-deadline-warning-days'."
15159 (interactive "P")
15160 (let (ans kwd value)
15161 (message "Sparse tree: [/]regexp [t]odo-kwd [T]ag [p]roperty [d]eadlines [b]efore-date")
15162 (setq ans (read-char-exclusive))
15163 (cond
15164 ((equal ans ?d)
15165 (call-interactively 'org-check-deadlines))
15166 ((equal ans ?b)
15167 (call-interactively 'org-check-before-date))
15168 ((equal ans ?t)
15169 (org-show-todo-tree '(4)))
15170 ((equal ans ?T)
15171 (call-interactively 'org-tags-sparse-tree))
15172 ((member ans '(?p ?P))
15173 (setq kwd (completing-read "Property: "
15174 (mapcar 'list (org-buffer-property-keys))))
15175 (setq value (completing-read "Value: "
15176 (mapcar 'list (org-property-values kwd))))
15177 (unless (string-match "\\`{.*}\\'" value)
15178 (setq value (concat "\"" value "\"")))
15179 (org-tags-sparse-tree arg (concat kwd "=" value)))
15180 ((member ans '(?r ?R ?/))
15181 (call-interactively 'org-occur))
15182 (t (error "No such sparse tree command \"%c\"" ans)))))
15184 (defvar org-occur-highlights nil)
15185 (make-variable-buffer-local 'org-occur-highlights)
15187 (defun org-occur (regexp &optional keep-previous callback)
15188 "Make a compact tree which shows all matches of REGEXP.
15189 The tree will show the lines where the regexp matches, and all higher
15190 headlines above the match. It will also show the heading after the match,
15191 to make sure editing the matching entry is easy.
15192 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
15193 call to `org-occur' will be kept, to allow stacking of calls to this
15194 command.
15195 If CALLBACK is non-nil, it is a function which is called to confirm
15196 that the match should indeed be shown."
15197 (interactive "sRegexp: \nP")
15198 (or keep-previous (org-remove-occur-highlights nil nil t))
15199 (let ((cnt 0))
15200 (save-excursion
15201 (goto-char (point-min))
15202 (if (or (not keep-previous) ; do not want to keep
15203 (not org-occur-highlights)) ; no previous matches
15204 ;; hide everything
15205 (org-overview))
15206 (while (re-search-forward regexp nil t)
15207 (when (or (not callback)
15208 (save-match-data (funcall callback)))
15209 (setq cnt (1+ cnt))
15210 (when org-highlight-sparse-tree-matches
15211 (org-highlight-new-match (match-beginning 0) (match-end 0)))
15212 (org-show-context 'occur-tree))))
15213 (when org-remove-highlights-with-change
15214 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
15215 nil 'local))
15216 (unless org-sparse-tree-open-archived-trees
15217 (org-hide-archived-subtrees (point-min) (point-max)))
15218 (run-hooks 'org-occur-hook)
15219 (if (interactive-p)
15220 (message "%d match(es) for regexp %s" cnt regexp))
15221 cnt))
15223 (defun org-show-context (&optional key)
15224 "Make sure point and context and visible.
15225 How much context is shown depends upon the variables
15226 `org-show-hierarchy-above', `org-show-following-heading'. and
15227 `org-show-siblings'."
15228 (let ((heading-p (org-on-heading-p t))
15229 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
15230 (following-p (org-get-alist-option org-show-following-heading key))
15231 (entry-p (org-get-alist-option org-show-entry-below key))
15232 (siblings-p (org-get-alist-option org-show-siblings key)))
15233 (catch 'exit
15234 ;; Show heading or entry text
15235 (if (and heading-p (not entry-p))
15236 (org-flag-heading nil) ; only show the heading
15237 (and (or entry-p (org-invisible-p) (org-invisible-p2))
15238 (org-show-hidden-entry))) ; show entire entry
15239 (when following-p
15240 ;; Show next sibling, or heading below text
15241 (save-excursion
15242 (and (if heading-p (org-goto-sibling) (outline-next-heading))
15243 (org-flag-heading nil))))
15244 (when siblings-p (org-show-siblings))
15245 (when hierarchy-p
15246 ;; show all higher headings, possibly with siblings
15247 (save-excursion
15248 (while (and (condition-case nil
15249 (progn (org-up-heading-all 1) t)
15250 (error nil))
15251 (not (bobp)))
15252 (org-flag-heading nil)
15253 (when siblings-p (org-show-siblings))))))))
15255 (defun org-reveal (&optional siblings)
15256 "Show current entry, hierarchy above it, and the following headline.
15257 This can be used to show a consistent set of context around locations
15258 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
15259 not t for the search context.
15261 With optional argument SIBLINGS, on each level of the hierarchy all
15262 siblings are shown. This repairs the tree structure to what it would
15263 look like when opened with hierarchical calls to `org-cycle'."
15264 (interactive "P")
15265 (let ((org-show-hierarchy-above t)
15266 (org-show-following-heading t)
15267 (org-show-siblings (if siblings t org-show-siblings)))
15268 (org-show-context nil)))
15270 (defun org-highlight-new-match (beg end)
15271 "Highlight from BEG to END and mark the highlight is an occur headline."
15272 (let ((ov (org-make-overlay beg end)))
15273 (org-overlay-put ov 'face 'secondary-selection)
15274 (push ov org-occur-highlights)))
15276 (defun org-remove-occur-highlights (&optional beg end noremove)
15277 "Remove the occur highlights from the buffer.
15278 BEG and END are ignored. If NOREMOVE is nil, remove this function
15279 from the `before-change-functions' in the current buffer."
15280 (interactive)
15281 (unless org-inhibit-highlight-removal
15282 (mapc 'org-delete-overlay org-occur-highlights)
15283 (setq org-occur-highlights nil)
15284 (unless noremove
15285 (remove-hook 'before-change-functions
15286 'org-remove-occur-highlights 'local))))
15288 ;;;; Priorities
15290 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
15291 "Regular expression matching the priority indicator.")
15293 (defvar org-remove-priority-next-time nil)
15295 (defun org-priority-up ()
15296 "Increase the priority of the current item."
15297 (interactive)
15298 (org-priority 'up))
15300 (defun org-priority-down ()
15301 "Decrease the priority of the current item."
15302 (interactive)
15303 (org-priority 'down))
15305 (defun org-priority (&optional action)
15306 "Change the priority of an item by ARG.
15307 ACTION can be `set', `up', `down', or a character."
15308 (interactive)
15309 (setq action (or action 'set))
15310 (let (current new news have remove)
15311 (save-excursion
15312 (org-back-to-heading)
15313 (if (looking-at org-priority-regexp)
15314 (setq current (string-to-char (match-string 2))
15315 have t)
15316 (setq current org-default-priority))
15317 (cond
15318 ((or (eq action 'set) (integerp action))
15319 (if (integerp action)
15320 (setq new action)
15321 (message "Priority %c-%c, SPC to remove: " org-highest-priority org-lowest-priority)
15322 (setq new (read-char-exclusive)))
15323 (if (and (= (upcase org-highest-priority) org-highest-priority)
15324 (= (upcase org-lowest-priority) org-lowest-priority))
15325 (setq new (upcase new)))
15326 (cond ((equal new ?\ ) (setq remove t))
15327 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
15328 (error "Priority must be between `%c' and `%c'"
15329 org-highest-priority org-lowest-priority))))
15330 ((eq action 'up)
15331 (if (and (not have) (eq last-command this-command))
15332 (setq new org-lowest-priority)
15333 (setq new (if (and org-priority-start-cycle-with-default (not have))
15334 org-default-priority (1- current)))))
15335 ((eq action 'down)
15336 (if (and (not have) (eq last-command this-command))
15337 (setq new org-highest-priority)
15338 (setq new (if (and org-priority-start-cycle-with-default (not have))
15339 org-default-priority (1+ current)))))
15340 (t (error "Invalid action")))
15341 (if (or (< (upcase new) org-highest-priority)
15342 (> (upcase new) org-lowest-priority))
15343 (setq remove t))
15344 (setq news (format "%c" new))
15345 (if have
15346 (if remove
15347 (replace-match "" t t nil 1)
15348 (replace-match news t t nil 2))
15349 (if remove
15350 (error "No priority cookie found in line")
15351 (looking-at org-todo-line-regexp)
15352 (if (match-end 2)
15353 (progn
15354 (goto-char (match-end 2))
15355 (insert " [#" news "]"))
15356 (goto-char (match-beginning 3))
15357 (insert "[#" news "] ")))))
15358 (org-preserve-lc (org-set-tags nil 'align))
15359 (if remove
15360 (message "Priority removed")
15361 (message "Priority of current item set to %s" news))))
15364 (defun org-get-priority (s)
15365 "Find priority cookie and return priority."
15366 (save-match-data
15367 (if (not (string-match org-priority-regexp s))
15368 (* 1000 (- org-lowest-priority org-default-priority))
15369 (* 1000 (- org-lowest-priority
15370 (string-to-char (match-string 2 s)))))))
15372 ;;;; Tags
15374 (defun org-scan-tags (action matcher &optional todo-only)
15375 "Scan headline tags with inheritance and produce output ACTION.
15376 ACTION can be `sparse-tree' or `agenda'. MATCHER is a Lisp form to be
15377 evaluated, testing if a given set of tags qualifies a headline for
15378 inclusion. When TODO-ONLY is non-nil, only lines with a TODO keyword
15379 are included in the output."
15380 (let* ((re (concat "[\n\r]" outline-regexp " *\\(\\<\\("
15381 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
15382 (org-re
15383 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*$")))
15384 (props (list 'face nil
15385 'done-face 'org-done
15386 'undone-face nil
15387 'mouse-face 'highlight
15388 'org-not-done-regexp org-not-done-regexp
15389 'org-todo-regexp org-todo-regexp
15390 'keymap org-agenda-keymap
15391 'help-echo
15392 (format "mouse-2 or RET jump to org file %s"
15393 (abbreviate-file-name
15394 (or (buffer-file-name (buffer-base-buffer))
15395 (buffer-name (buffer-base-buffer)))))))
15396 (case-fold-search nil)
15397 lspos
15398 tags tags-list tags-alist (llast 0) rtn level category i txt
15399 todo marker entry priority)
15400 (save-excursion
15401 (goto-char (point-min))
15402 (when (eq action 'sparse-tree)
15403 (org-overview)
15404 (org-remove-occur-highlights))
15405 (while (re-search-forward re nil t)
15406 (catch :skip
15407 (setq todo (if (match-end 1) (match-string 2))
15408 tags (if (match-end 4) (match-string 4)))
15409 (goto-char (setq lspos (1+ (match-beginning 0))))
15410 (setq level (org-reduced-level (funcall outline-level))
15411 category (org-get-category))
15412 (setq i llast llast level)
15413 ;; remove tag lists from same and sublevels
15414 (while (>= i level)
15415 (when (setq entry (assoc i tags-alist))
15416 (setq tags-alist (delete entry tags-alist)))
15417 (setq i (1- i)))
15418 ;; add the nex tags
15419 (when tags
15420 (setq tags (mapcar 'downcase (org-split-string tags ":"))
15421 tags-alist
15422 (cons (cons level tags) tags-alist)))
15423 ;; compile tags for current headline
15424 (setq tags-list
15425 (if org-use-tag-inheritance
15426 (apply 'append (mapcar 'cdr tags-alist))
15427 tags))
15428 (when (and (or (not todo-only) (member todo org-not-done-keywords))
15429 (eval matcher)
15430 (or (not org-agenda-skip-archived-trees)
15431 (not (member org-archive-tag tags-list))))
15432 (and (eq action 'agenda) (org-agenda-skip))
15433 ;; list this headline
15435 (if (eq action 'sparse-tree)
15436 (progn
15437 (and org-highlight-sparse-tree-matches
15438 (org-get-heading) (match-end 0)
15439 (org-highlight-new-match
15440 (match-beginning 0) (match-beginning 1)))
15441 (org-show-context 'tags-tree))
15442 (setq txt (org-format-agenda-item
15444 (concat
15445 (if org-tags-match-list-sublevels
15446 (make-string (1- level) ?.) "")
15447 (org-get-heading))
15448 category tags-list)
15449 priority (org-get-priority txt))
15450 (goto-char lspos)
15451 (setq marker (org-agenda-new-marker))
15452 (org-add-props txt props
15453 'org-marker marker 'org-hd-marker marker 'org-category category
15454 'priority priority 'type "tagsmatch")
15455 (push txt rtn))
15456 ;; if we are to skip sublevels, jump to end of subtree
15457 (or org-tags-match-list-sublevels (org-end-of-subtree t))))))
15458 (when (and (eq action 'sparse-tree)
15459 (not org-sparse-tree-open-archived-trees))
15460 (org-hide-archived-subtrees (point-min) (point-max)))
15461 (nreverse rtn)))
15463 (defvar todo-only) ;; dynamically scoped
15465 (defun org-tags-sparse-tree (&optional todo-only match)
15466 "Create a sparse tree according to tags string MATCH.
15467 MATCH can contain positive and negative selection of tags, like
15468 \"+WORK+URGENT-WITHBOSS\".
15469 If optional argument TODO_ONLY is non-nil, only select lines that are
15470 also TODO lines."
15471 (interactive "P")
15472 (org-prepare-agenda-buffers (list (current-buffer)))
15473 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
15475 (defvar org-cached-props nil)
15476 (defun org-cached-entry-get (pom property)
15477 (if (or (eq t org-use-property-inheritance)
15478 (member property org-use-property-inheritance))
15479 ;; Caching is not possible, check it directly
15480 (org-entry-get pom property 'inherit)
15481 ;; Get all properties, so that we can do complicated checks easily
15482 (cdr (assoc property (or org-cached-props
15483 (setq org-cached-props
15484 (org-entry-properties pom)))))))
15486 (defun org-global-tags-completion-table (&optional files)
15487 "Return the list of all tags in all agenda buffer/files."
15488 (save-excursion
15489 (org-uniquify
15490 (delq nil
15491 (apply 'append
15492 (mapcar
15493 (lambda (file)
15494 (set-buffer (find-file-noselect file))
15495 (append (org-get-buffer-tags)
15496 (mapcar (lambda (x) (if (stringp (car-safe x))
15497 (list (car-safe x)) nil))
15498 org-tag-alist)))
15499 (if (and files (car files))
15500 files
15501 (org-agenda-files))))))))
15503 (defun org-make-tags-matcher (match)
15504 "Create the TAGS//TODO matcher form for the selection string MATCH."
15505 ;; todo-only is scoped dynamically into this function, and the function
15506 ;; may change it it the matcher asksk for it.
15507 (unless match
15508 ;; Get a new match request, with completion
15509 (let ((org-last-tags-completion-table
15510 (org-global-tags-completion-table)))
15511 (setq match (completing-read
15512 "Match: " 'org-tags-completion-function nil nil nil
15513 'org-tags-history))))
15515 ;; Parse the string and create a lisp form
15516 (let ((match0 match)
15517 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL=\\([0-9]+\\)\\|\\([[:alnum:]_]+\\)=\\({[^}]+}\\|\"[^\"]*\"\\)\\|[[:alnum:]_@]+\\)"))
15518 minus tag mm
15519 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
15520 orterms term orlist re-p level-p prop-p pn pv cat-p gv)
15521 (if (string-match "/+" match)
15522 ;; match contains also a todo-matching request
15523 (progn
15524 (setq tagsmatch (substring match 0 (match-beginning 0))
15525 todomatch (substring match (match-end 0)))
15526 (if (string-match "^!" todomatch)
15527 (setq todo-only t todomatch (substring todomatch 1)))
15528 (if (string-match "^\\s-*$" todomatch)
15529 (setq todomatch nil)))
15530 ;; only matching tags
15531 (setq tagsmatch match todomatch nil))
15533 ;; Make the tags matcher
15534 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
15535 (setq tagsmatcher t)
15536 (setq orterms (org-split-string tagsmatch "|") orlist nil)
15537 (while (setq term (pop orterms))
15538 (while (and (equal (substring term -1) "\\") orterms)
15539 (setq term (concat term "|" (pop orterms)))) ; repair bad split
15540 (while (string-match re term)
15541 (setq minus (and (match-end 1)
15542 (equal (match-string 1 term) "-"))
15543 tag (match-string 2 term)
15544 re-p (equal (string-to-char tag) ?{)
15545 level-p (match-end 3)
15546 prop-p (match-end 4)
15547 mm (cond
15548 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
15549 (level-p `(= level ,(string-to-number
15550 (match-string 3 term))))
15551 (prop-p
15552 (setq pn (match-string 4 term)
15553 pv (match-string 5 term)
15554 cat-p (equal pn "CATEGORY")
15555 re-p (equal (string-to-char pv) ?{)
15556 pv (substring pv 1 -1))
15557 (if (equal pn "CATEGORY")
15558 (setq gv '(get-text-property (point) 'org-category))
15559 (setq gv `(org-cached-entry-get nil ,pn)))
15560 (if re-p
15561 `(string-match ,pv (or ,gv ""))
15562 `(equal ,pv (or ,gv ""))))
15563 (t `(member ,(downcase tag) tags-list)))
15564 mm (if minus (list 'not mm) mm)
15565 term (substring term (match-end 0)))
15566 (push mm tagsmatcher))
15567 (push (if (> (length tagsmatcher) 1)
15568 (cons 'and tagsmatcher)
15569 (car tagsmatcher))
15570 orlist)
15571 (setq tagsmatcher nil))
15572 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
15573 (setq tagsmatcher
15574 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
15576 ;; Make the todo matcher
15577 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
15578 (setq todomatcher t)
15579 (setq orterms (org-split-string todomatch "|") orlist nil)
15580 (while (setq term (pop orterms))
15581 (while (string-match re term)
15582 (setq minus (and (match-end 1)
15583 (equal (match-string 1 term) "-"))
15584 kwd (match-string 2 term)
15585 re-p (equal (string-to-char kwd) ?{)
15586 term (substring term (match-end 0))
15587 mm (if re-p
15588 `(string-match ,(substring kwd 1 -1) todo)
15589 (list 'equal 'todo kwd))
15590 mm (if minus (list 'not mm) mm))
15591 (push mm todomatcher))
15592 (push (if (> (length todomatcher) 1)
15593 (cons 'and todomatcher)
15594 (car todomatcher))
15595 orlist)
15596 (setq todomatcher nil))
15597 (setq todomatcher (if (> (length orlist) 1)
15598 (cons 'or orlist) (car orlist))))
15600 ;; Return the string and lisp forms of the matcher
15601 (setq matcher (if todomatcher
15602 (list 'and tagsmatcher todomatcher)
15603 tagsmatcher))
15604 (cons match0 matcher)))
15606 (defun org-match-any-p (re list)
15607 "Does re match any element of list?"
15608 (setq list (mapcar (lambda (x) (string-match re x)) list))
15609 (delq nil list))
15611 (defvar org-add-colon-after-tag-completion nil) ;; dynamically skoped param
15612 (defvar org-tags-overlay (org-make-overlay 1 1))
15613 (org-detach-overlay org-tags-overlay)
15615 (defun org-align-tags-here (to-col)
15616 ;; Assumes that this is a headline
15617 (let ((pos (point)) (col (current-column)) tags)
15618 (beginning-of-line 1)
15619 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
15620 (< pos (match-beginning 2)))
15621 (progn
15622 (setq tags (match-string 2))
15623 (goto-char (match-beginning 1))
15624 (insert " ")
15625 (delete-region (point) (1+ (match-end 0)))
15626 (backward-char 1)
15627 (move-to-column
15628 (max (1+ (current-column))
15629 (1+ col)
15630 (if (> to-col 0)
15631 to-col
15632 (- (abs to-col) (length tags))))
15634 (insert tags)
15635 (move-to-column (min (current-column) col) t))
15636 (goto-char pos))))
15638 (defun org-set-tags (&optional arg just-align)
15639 "Set the tags for the current headline.
15640 With prefix ARG, realign all tags in headings in the current buffer."
15641 (interactive "P")
15642 (let* ((re (concat "^" outline-regexp))
15643 (current (org-get-tags-string))
15644 (col (current-column))
15645 (org-setting-tags t)
15646 table current-tags inherited-tags ; computed below when needed
15647 tags p0 c0 c1 rpl)
15648 (if arg
15649 (save-excursion
15650 (goto-char (point-min))
15651 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
15652 (while (re-search-forward re nil t)
15653 (org-set-tags nil t)
15654 (end-of-line 1)))
15655 (message "All tags realigned to column %d" org-tags-column))
15656 (if just-align
15657 (setq tags current)
15658 ;; Get a new set of tags from the user
15659 (save-excursion
15660 (setq table (or org-tag-alist (org-get-buffer-tags))
15661 org-last-tags-completion-table table
15662 current-tags (org-split-string current ":")
15663 inherited-tags (nreverse
15664 (nthcdr (length current-tags)
15665 (nreverse (org-get-tags-at))))
15666 tags
15667 (if (or (eq t org-use-fast-tag-selection)
15668 (and org-use-fast-tag-selection
15669 (delq nil (mapcar 'cdr table))))
15670 (org-fast-tag-selection
15671 current-tags inherited-tags table
15672 (if org-fast-tag-selection-include-todo org-todo-key-alist))
15673 (let ((org-add-colon-after-tag-completion t))
15674 (org-trim
15675 (org-without-partial-completion
15676 (completing-read "Tags: " 'org-tags-completion-function
15677 nil nil current 'org-tags-history)))))))
15678 (while (string-match "[-+&]+" tags)
15679 ;; No boolean logic, just a list
15680 (setq tags (replace-match ":" t t tags))))
15682 (if (string-match "\\`[\t ]*\\'" tags)
15683 (setq tags "")
15684 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
15685 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
15687 ;; Insert new tags at the correct column
15688 (beginning-of-line 1)
15689 (cond
15690 ((and (equal current "") (equal tags "")))
15691 ((re-search-forward
15692 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
15693 (point-at-eol) t)
15694 (if (equal tags "")
15695 (setq rpl "")
15696 (goto-char (match-beginning 0))
15697 (setq c0 (current-column) p0 (point)
15698 c1 (max (1+ c0) (if (> org-tags-column 0)
15699 org-tags-column
15700 (- (- org-tags-column) (length tags))))
15701 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
15702 (replace-match rpl t t)
15703 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
15704 tags)
15705 (t (error "Tags alignment failed")))
15706 (move-to-column col)
15707 (unless just-align
15708 (run-hooks 'org-after-tags-change-hook)))))
15710 (defun org-change-tag-in-region (beg end tag off)
15711 "Add or remove TAG for each entry in the region.
15712 This works in the agenda, and also in an org-mode buffer."
15713 (interactive
15714 (list (region-beginning) (region-end)
15715 (let ((org-last-tags-completion-table
15716 (if (org-mode-p)
15717 (org-get-buffer-tags)
15718 (org-global-tags-completion-table))))
15719 (completing-read
15720 "Tag: " 'org-tags-completion-function nil nil nil
15721 'org-tags-history))
15722 (progn
15723 (message "[s]et or [r]emove? ")
15724 (equal (read-char-exclusive) ?r))))
15725 (if (fboundp 'deactivate-mark) (deactivate-mark))
15726 (let ((agendap (equal major-mode 'org-agenda-mode))
15727 l1 l2 m buf pos newhead (cnt 0))
15728 (goto-char end)
15729 (setq l2 (1- (org-current-line)))
15730 (goto-char beg)
15731 (setq l1 (org-current-line))
15732 (loop for l from l1 to l2 do
15733 (goto-line l)
15734 (setq m (get-text-property (point) 'org-hd-marker))
15735 (when (or (and (org-mode-p) (org-on-heading-p))
15736 (and agendap m))
15737 (setq buf (if agendap (marker-buffer m) (current-buffer))
15738 pos (if agendap m (point)))
15739 (with-current-buffer buf
15740 (save-excursion
15741 (save-restriction
15742 (goto-char pos)
15743 (setq cnt (1+ cnt))
15744 (org-toggle-tag tag (if off 'off 'on))
15745 (setq newhead (org-get-heading)))))
15746 (and agendap (org-agenda-change-all-lines newhead m))))
15747 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
15749 (defun org-tags-completion-function (string predicate &optional flag)
15750 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
15751 (confirm (lambda (x) (stringp (car x)))))
15752 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
15753 (setq s1 (match-string 1 string)
15754 s2 (match-string 2 string))
15755 (setq s1 "" s2 string))
15756 (cond
15757 ((eq flag nil)
15758 ;; try completion
15759 (setq rtn (try-completion s2 ctable confirm))
15760 (if (stringp rtn)
15761 (setq rtn
15762 (concat s1 s2 (substring rtn (length s2))
15763 (if (and org-add-colon-after-tag-completion
15764 (assoc rtn ctable))
15765 ":" ""))))
15766 rtn)
15767 ((eq flag t)
15768 ;; all-completions
15769 (all-completions s2 ctable confirm)
15771 ((eq flag 'lambda)
15772 ;; exact match?
15773 (assoc s2 ctable)))
15776 (defun org-fast-tag-insert (kwd tags face &optional end)
15777 "Insert KDW, and the TAGS, the latter with face FACE. Also inser END."
15778 (insert (format "%-12s" (concat kwd ":"))
15779 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
15780 (or end "")))
15782 (defun org-fast-tag-show-exit (flag)
15783 (save-excursion
15784 (goto-line 3)
15785 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
15786 (replace-match ""))
15787 (when flag
15788 (end-of-line 1)
15789 (move-to-column (- (window-width) 19) t)
15790 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
15792 (defun org-set-current-tags-overlay (current prefix)
15793 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
15794 (if (featurep 'xemacs)
15795 (org-overlay-display org-tags-overlay (concat prefix s)
15796 'secondary-selection)
15797 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
15798 (org-overlay-display org-tags-overlay (concat prefix s)))))
15800 (defun org-fast-tag-selection (current inherited table &optional todo-table)
15801 "Fast tag selection with single keys.
15802 CURRENT is the current list of tags in the headline, INHERITED is the
15803 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
15804 possibly with grouping information. TODO-TABLE is a similar table with
15805 TODO keywords, should these have keys assigned to them.
15806 If the keys are nil, a-z are automatically assigned.
15807 Returns the new tags string, or nil to not change the current settings."
15808 (let* ((fulltable (append table todo-table))
15809 (maxlen (apply 'max (mapcar
15810 (lambda (x)
15811 (if (stringp (car x)) (string-width (car x)) 0))
15812 fulltable)))
15813 (buf (current-buffer))
15814 (expert (eq org-fast-tag-selection-single-key 'expert))
15815 (buffer-tags nil)
15816 (fwidth (+ maxlen 3 1 3))
15817 (ncol (/ (- (window-width) 4) fwidth))
15818 (i-face 'org-done)
15819 (c-face 'org-todo)
15820 tg cnt e c char c1 c2 ntable tbl rtn
15821 ov-start ov-end ov-prefix
15822 (exit-after-next org-fast-tag-selection-single-key)
15823 (done-keywords org-done-keywords)
15824 groups ingroup)
15825 (save-excursion
15826 (beginning-of-line 1)
15827 (if (looking-at
15828 (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
15829 (setq ov-start (match-beginning 1)
15830 ov-end (match-end 1)
15831 ov-prefix "")
15832 (setq ov-start (1- (point-at-eol))
15833 ov-end (1+ ov-start))
15834 (skip-chars-forward "^\n\r")
15835 (setq ov-prefix
15836 (concat
15837 (buffer-substring (1- (point)) (point))
15838 (if (> (current-column) org-tags-column)
15840 (make-string (- org-tags-column (current-column)) ?\ ))))))
15841 (org-move-overlay org-tags-overlay ov-start ov-end)
15842 (save-window-excursion
15843 (if expert
15844 (set-buffer (get-buffer-create " *Org tags*"))
15845 (delete-other-windows)
15846 (split-window-vertically)
15847 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
15848 (erase-buffer)
15849 (org-set-local 'org-done-keywords done-keywords)
15850 (org-fast-tag-insert "Inherited" inherited i-face "\n")
15851 (org-fast-tag-insert "Current" current c-face "\n\n")
15852 (org-fast-tag-show-exit exit-after-next)
15853 (org-set-current-tags-overlay current ov-prefix)
15854 (setq tbl fulltable char ?a cnt 0)
15855 (while (setq e (pop tbl))
15856 (cond
15857 ((equal e '(:startgroup))
15858 (push '() groups) (setq ingroup t)
15859 (when (not (= cnt 0))
15860 (setq cnt 0)
15861 (insert "\n"))
15862 (insert "{ "))
15863 ((equal e '(:endgroup))
15864 (setq ingroup nil cnt 0)
15865 (insert "}\n"))
15867 (setq tg (car e) c2 nil)
15868 (if (cdr e)
15869 (setq c (cdr e))
15870 ;; automatically assign a character.
15871 (setq c1 (string-to-char
15872 (downcase (substring
15873 tg (if (= (string-to-char tg) ?@) 1 0)))))
15874 (if (or (rassoc c1 ntable) (rassoc c1 table))
15875 (while (or (rassoc char ntable) (rassoc char table))
15876 (setq char (1+ char)))
15877 (setq c2 c1))
15878 (setq c (or c2 char)))
15879 (if ingroup (push tg (car groups)))
15880 (setq tg (org-add-props tg nil 'face
15881 (cond
15882 ((not (assoc tg table))
15883 (org-get-todo-face tg))
15884 ((member tg current) c-face)
15885 ((member tg inherited) i-face)
15886 (t nil))))
15887 (if (and (= cnt 0) (not ingroup)) (insert " "))
15888 (insert "[" c "] " tg (make-string
15889 (- fwidth 4 (length tg)) ?\ ))
15890 (push (cons tg c) ntable)
15891 (when (= (setq cnt (1+ cnt)) ncol)
15892 (insert "\n")
15893 (if ingroup (insert " "))
15894 (setq cnt 0)))))
15895 (setq ntable (nreverse ntable))
15896 (insert "\n")
15897 (goto-char (point-min))
15898 (if (and (not expert) (fboundp 'fit-window-to-buffer))
15899 (fit-window-to-buffer))
15900 (setq rtn
15901 (catch 'exit
15902 (while t
15903 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free%s%s"
15904 (if groups " [!] no groups" " [!]groups")
15905 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
15906 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
15907 (cond
15908 ((= c ?\r) (throw 'exit t))
15909 ((= c ?!)
15910 (setq groups (not groups))
15911 (goto-char (point-min))
15912 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
15913 ((= c ?\C-c)
15914 (if (not expert)
15915 (org-fast-tag-show-exit
15916 (setq exit-after-next (not exit-after-next)))
15917 (setq expert nil)
15918 (delete-other-windows)
15919 (split-window-vertically)
15920 (org-switch-to-buffer-other-window " *Org tags*")
15921 (and (fboundp 'fit-window-to-buffer)
15922 (fit-window-to-buffer))))
15923 ((or (= c ?\C-g)
15924 (and (= c ?q) (not (rassoc c ntable))))
15925 (org-detach-overlay org-tags-overlay)
15926 (setq quit-flag t))
15927 ((= c ?\ )
15928 (setq current nil)
15929 (if exit-after-next (setq exit-after-next 'now)))
15930 ((= c ?\t)
15931 (condition-case nil
15932 (setq tg (completing-read
15933 "Tag: "
15934 (or buffer-tags
15935 (with-current-buffer buf
15936 (org-get-buffer-tags)))))
15937 (quit (setq tg "")))
15938 (when (string-match "\\S-" tg)
15939 (add-to-list 'buffer-tags (list tg))
15940 (if (member tg current)
15941 (setq current (delete tg current))
15942 (push tg current)))
15943 (if exit-after-next (setq exit-after-next 'now)))
15944 ((setq e (rassoc c todo-table) tg (car e))
15945 (with-current-buffer buf
15946 (save-excursion (org-todo tg)))
15947 (if exit-after-next (setq exit-after-next 'now)))
15948 ((setq e (rassoc c ntable) tg (car e))
15949 (if (member tg current)
15950 (setq current (delete tg current))
15951 (loop for g in groups do
15952 (if (member tg g)
15953 (mapc (lambda (x)
15954 (setq current (delete x current)))
15955 g)))
15956 (push tg current))
15957 (if exit-after-next (setq exit-after-next 'now))))
15959 ;; Create a sorted list
15960 (setq current
15961 (sort current
15962 (lambda (a b)
15963 (assoc b (cdr (memq (assoc a ntable) ntable))))))
15964 (if (eq exit-after-next 'now) (throw 'exit t))
15965 (goto-char (point-min))
15966 (beginning-of-line 2)
15967 (delete-region (point) (point-at-eol))
15968 (org-fast-tag-insert "Current" current c-face)
15969 (org-set-current-tags-overlay current ov-prefix)
15970 (while (re-search-forward
15971 (org-re "\\[.\\] \\([[:alnum:]_@]+\\)") nil t)
15972 (setq tg (match-string 1))
15973 (add-text-properties
15974 (match-beginning 1) (match-end 1)
15975 (list 'face
15976 (cond
15977 ((member tg current) c-face)
15978 ((member tg inherited) i-face)
15979 (t (get-text-property (match-beginning 1) 'face))))))
15980 (goto-char (point-min)))))
15981 (org-detach-overlay org-tags-overlay)
15982 (if rtn
15983 (mapconcat 'identity current ":")
15984 nil))))
15986 (defun org-get-tags-string ()
15987 "Get the TAGS string in the current headline."
15988 (unless (org-on-heading-p t)
15989 (error "Not on a heading"))
15990 (save-excursion
15991 (beginning-of-line 1)
15992 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
15993 (org-match-string-no-properties 1)
15994 "")))
15996 (defun org-get-tags ()
15997 "Get the list of tags specified in the current headline."
15998 (org-split-string (org-get-tags-string) ":"))
16000 (defun org-get-buffer-tags ()
16001 "Get a table of all tags used in the buffer, for completion."
16002 (let (tags)
16003 (save-excursion
16004 (goto-char (point-min))
16005 (while (re-search-forward
16006 (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t\r\n]") nil t)
16007 (when (equal (char-after (point-at-bol 0)) ?*)
16008 (mapc (lambda (x) (add-to-list 'tags x))
16009 (org-split-string (org-match-string-no-properties 1) ":")))))
16010 (mapcar 'list tags)))
16013 ;;;; Properties
16015 ;;; Setting and retrieving properties
16017 (defconst org-special-properties
16018 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "PRIORITY"
16019 "TIMESTAMP" "TIMESTAMP_IA")
16020 "The special properties valid in Org-mode.
16022 These are properties that are not defined in the property drawer,
16023 but in some other way.")
16025 (defconst org-default-properties
16026 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION"
16027 "LOCATION" "LOGGING" "COLUMNS")
16028 "Some properties that are used by Org-mode for various purposes.
16029 Being in this list makes sure that they are offered for completion.")
16031 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
16032 "Regular expression matching the first line of a property drawer.")
16034 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
16035 "Regular expression matching the first line of a property drawer.")
16037 (defun org-property-action ()
16038 "Do an action on properties."
16039 (interactive)
16040 (let (c)
16041 (org-at-property-p)
16042 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
16043 (setq c (read-char-exclusive))
16044 (cond
16045 ((equal c ?s)
16046 (call-interactively 'org-set-property))
16047 ((equal c ?d)
16048 (call-interactively 'org-delete-property))
16049 ((equal c ?D)
16050 (call-interactively 'org-delete-property-globally))
16051 ((equal c ?c)
16052 (call-interactively 'org-compute-property-at-point))
16053 (t (error "No such property action %c" c)))))
16055 (defun org-at-property-p ()
16056 "Is the cursor in a property line?"
16057 ;; FIXME: Does not check if we are actually in the drawer.
16058 ;; FIXME: also returns true on any drawers.....
16059 ;; This is used by C-c C-c for property action.
16060 (save-excursion
16061 (beginning-of-line 1)
16062 (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))))
16064 (defmacro org-with-point-at (pom &rest body)
16065 "Move to buffer and point of point-or-marker POM for the duration of BODY."
16066 (declare (indent 1) (debug t))
16067 `(save-excursion
16068 (if (markerp pom) (set-buffer (marker-buffer pom)))
16069 (save-excursion
16070 (goto-char (or pom (point)))
16071 ,@body)))
16073 (defun org-get-property-block (&optional beg end force)
16074 "Return the (beg . end) range of the body of the property drawer.
16075 BEG and END can be beginning and end of subtree, if not given
16076 they will be found.
16077 If the drawer does not exist and FORCE is non-nil, create the drawer."
16078 (catch 'exit
16079 (save-excursion
16080 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
16081 (end (or end (progn (outline-next-heading) (point)))))
16082 (goto-char beg)
16083 (if (re-search-forward org-property-start-re end t)
16084 (setq beg (1+ (match-end 0)))
16085 (if force
16086 (save-excursion
16087 (org-insert-property-drawer)
16088 (setq end (progn (outline-next-heading) (point))))
16089 (throw 'exit nil))
16090 (goto-char beg)
16091 (if (re-search-forward org-property-start-re end t)
16092 (setq beg (1+ (match-end 0)))))
16093 (if (re-search-forward org-property-end-re end t)
16094 (setq end (match-beginning 0))
16095 (or force (throw 'exit nil))
16096 (goto-char beg)
16097 (setq end beg)
16098 (org-indent-line-function)
16099 (insert ":END:\n"))
16100 (cons beg end)))))
16102 (defun org-entry-properties (&optional pom which)
16103 "Get all properties of the entry at point-or-marker POM.
16104 This includes the TODO keyword, the tags, time strings for deadline,
16105 scheduled, and clocking, and any additional properties defined in the
16106 entry. The return value is an alist, keys may occur multiple times
16107 if the property key was used several times.
16108 POM may also be nil, in which case the current entry is used.
16109 If WHICH is nil or `all', get all properties. If WHICH is
16110 `special' or `standard', only get that subclass."
16111 (setq which (or which 'all))
16112 (org-with-point-at pom
16113 (let ((clockstr (substring org-clock-string 0 -1))
16114 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY"))
16115 beg end range props sum-props key value string clocksum)
16116 (save-excursion
16117 (when (condition-case nil (org-back-to-heading t) (error nil))
16118 (setq beg (point))
16119 (setq sum-props (get-text-property (point) 'org-summaries))
16120 (setq clocksum (get-text-property (point) :org-clock-minutes))
16121 (outline-next-heading)
16122 (setq end (point))
16123 (when (memq which '(all special))
16124 ;; Get the special properties, like TODO and tags
16125 (goto-char beg)
16126 (when (and (looking-at org-todo-line-regexp) (match-end 2))
16127 (push (cons "TODO" (org-match-string-no-properties 2)) props))
16128 (when (looking-at org-priority-regexp)
16129 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
16130 (when (and (setq value (org-get-tags-string))
16131 (string-match "\\S-" value))
16132 (push (cons "TAGS" value) props))
16133 (when (setq value (org-get-tags-at))
16134 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":") ":"))
16135 props))
16136 (while (re-search-forward org-maybe-keyword-time-regexp end t)
16137 (setq key (if (match-end 1) (substring (org-match-string-no-properties 1) 0 -1))
16138 string (if (equal key clockstr)
16139 (org-no-properties
16140 (org-trim
16141 (buffer-substring
16142 (match-beginning 3) (goto-char (point-at-eol)))))
16143 (substring (org-match-string-no-properties 3) 1 -1)))
16144 (unless key
16145 (if (= (char-after (match-beginning 3)) ?\[)
16146 (setq key "TIMESTAMP_IA")
16147 (setq key "TIMESTAMP")))
16148 (when (or (equal key clockstr) (not (assoc key props)))
16149 (push (cons key string) props)))
16153 (when (memq which '(all standard))
16154 ;; Get the standard properties, like :PORP: ...
16155 (setq range (org-get-property-block beg end))
16156 (when range
16157 (goto-char (car range))
16158 (while (re-search-forward
16159 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
16160 (cdr range) t)
16161 (setq key (org-match-string-no-properties 1)
16162 value (org-trim (or (org-match-string-no-properties 2) "")))
16163 (unless (member key excluded)
16164 (push (cons key (or value "")) props)))))
16165 (if clocksum
16166 (push (cons "CLOCKSUM"
16167 (org-column-number-to-string (/ (float clocksum) 60.)
16168 'add_times))
16169 props))
16170 (append sum-props (nreverse props)))))))
16172 (defun org-entry-get (pom property &optional inherit)
16173 "Get value of PROPERTY for entry at point-or-marker POM.
16174 If INHERIT is non-nil and the entry does not have the property,
16175 then also check higher levels of the hierarchy.
16176 If the property is present but empty, the return value is the empty string.
16177 If the property is not present at all, nil is returned."
16178 (org-with-point-at pom
16179 (if inherit
16180 (org-entry-get-with-inheritance property)
16181 (if (member property org-special-properties)
16182 ;; We need a special property. Use brute force, get all properties.
16183 (cdr (assoc property (org-entry-properties nil 'special)))
16184 (let ((range (org-get-property-block)))
16185 (if (and range
16186 (goto-char (car range))
16187 (re-search-forward
16188 (concat "^[ \t]*:" property ":[ \t]*\\(.*\\S-\\)?")
16189 (cdr range) t))
16190 ;; Found the property, return it.
16191 (if (match-end 1)
16192 (org-match-string-no-properties 1)
16193 "")))))))
16195 (defun org-entry-delete (pom property)
16196 "Delete the property PROPERTY from entry at point-or-marker POM."
16197 (org-with-point-at pom
16198 (if (member property org-special-properties)
16199 nil ; cannot delete these properties.
16200 (let ((range (org-get-property-block)))
16201 (if (and range
16202 (goto-char (car range))
16203 (re-search-forward
16204 (concat "^[ \t]*:" property ":[ \t]*\\(.*\\S-\\)")
16205 (cdr range) t))
16206 (progn
16207 (delete-region (match-beginning 0) (1+ (point-at-eol)))
16209 nil)))))
16211 ;; Multi-values properties are properties that contain multiple values
16212 ;; These values are assumed to be single words, separated by whitespace.
16213 (defun org-entry-add-to-multivalued-property (pom property value)
16214 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
16215 (let* ((old (org-entry-get pom property))
16216 (values (and old (org-split-string old "[ \t]"))))
16217 (unless (member value values)
16218 (setq values (cons value values))
16219 (org-entry-put pom property
16220 (mapconcat 'identity values " ")))))
16222 (defun org-entry-remove-from-multivalued-property (pom property value)
16223 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
16224 (let* ((old (org-entry-get pom property))
16225 (values (and old (org-split-string old "[ \t]"))))
16226 (when (member value values)
16227 (setq values (delete value values))
16228 (org-entry-put pom property
16229 (mapconcat 'identity values " ")))))
16231 (defun org-entry-member-in-multivalued-property (pom property value)
16232 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
16233 (let* ((old (org-entry-get pom property))
16234 (values (and old (org-split-string old "[ \t]"))))
16235 (member value values)))
16237 (defvar org-entry-property-inherited-from (make-marker))
16239 (defun org-entry-get-with-inheritance (property)
16240 "Get entry property, and search higher levels if not present."
16241 (let (tmp)
16242 (save-excursion
16243 (save-restriction
16244 (widen)
16245 (catch 'ex
16246 (while t
16247 (when (setq tmp (org-entry-get nil property))
16248 (org-back-to-heading t)
16249 (move-marker org-entry-property-inherited-from (point))
16250 (throw 'ex tmp))
16251 (or (org-up-heading-safe) (throw 'ex nil)))))
16252 (or tmp (cdr (assoc property org-local-properties))
16253 (cdr (assoc property org-global-properties))))))
16255 (defun org-entry-put (pom property value)
16256 "Set PROPERTY to VALUE for entry at point-or-marker POM."
16257 (org-with-point-at pom
16258 (org-back-to-heading t)
16259 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
16260 range)
16261 (cond
16262 ((equal property "TODO")
16263 (when (and (stringp value) (string-match "\\S-" value)
16264 (not (member value org-todo-keywords-1)))
16265 (error "\"%s\" is not a valid TODO state" value))
16266 (if (or (not value)
16267 (not (string-match "\\S-" value)))
16268 (setq value 'none))
16269 (org-todo value)
16270 (org-set-tags nil 'align))
16271 ((equal property "PRIORITY")
16272 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
16273 (string-to-char value) ?\ ))
16274 (org-set-tags nil 'align))
16275 ((equal property "SCHEDULED")
16276 (if (re-search-forward org-scheduled-time-regexp end t)
16277 (cond
16278 ((eq value 'earlier) (org-timestamp-change -1 'day))
16279 ((eq value 'later) (org-timestamp-change 1 'day))
16280 (t (call-interactively 'org-schedule)))
16281 (call-interactively 'org-schedule)))
16282 ((equal property "DEADLINE")
16283 (if (re-search-forward org-deadline-time-regexp end t)
16284 (cond
16285 ((eq value 'earlier) (org-timestamp-change -1 'day))
16286 ((eq value 'later) (org-timestamp-change 1 'day))
16287 (t (call-interactively 'org-deadline)))
16288 (call-interactively 'org-deadline)))
16289 ((member property org-special-properties)
16290 (error "The %s property can not yet be set with `org-entry-put'"
16291 property))
16292 (t ; a non-special property
16293 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
16294 (setq range (org-get-property-block beg end 'force))
16295 (goto-char (car range))
16296 (if (re-search-forward
16297 (concat "^[ \t]*:" property ":\\(.*\\)") (cdr range) t)
16298 (progn
16299 (delete-region (match-beginning 1) (match-end 1))
16300 (goto-char (match-beginning 1)))
16301 (goto-char (cdr range))
16302 (insert "\n")
16303 (backward-char 1)
16304 (org-indent-line-function)
16305 (insert ":" property ":"))
16306 (and value (insert " " value))
16307 (org-indent-line-function)))))))
16309 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
16310 "Get all property keys in the current buffer.
16311 With INCLUDE-SPECIALS, also list the special properties that relect things
16312 like tags and TODO state.
16313 With INCLUDE-DEFAULTS, also include properties that has special meaning
16314 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING.
16315 With INCLUDE-COLUMNS, also include property names given in COLUMN
16316 formats in the current buffer."
16317 (let (rtn range cfmt cols s p)
16318 (save-excursion
16319 (save-restriction
16320 (widen)
16321 (goto-char (point-min))
16322 (while (re-search-forward org-property-start-re nil t)
16323 (setq range (org-get-property-block))
16324 (goto-char (car range))
16325 (while (re-search-forward
16326 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
16327 (cdr range) t)
16328 (add-to-list 'rtn (org-match-string-no-properties 1)))
16329 (outline-next-heading))))
16331 (when include-specials
16332 (setq rtn (append org-special-properties rtn)))
16334 (when include-defaults
16335 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties))
16337 (when include-columns
16338 (save-excursion
16339 (save-restriction
16340 (widen)
16341 (goto-char (point-min))
16342 (while (re-search-forward
16343 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
16344 nil t)
16345 (setq cfmt (match-string 2) s 0)
16346 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
16347 cfmt s)
16348 (setq s (match-end 0)
16349 p (match-string 1 cfmt))
16350 (unless (or (equal p "ITEM")
16351 (member p org-special-properties))
16352 (add-to-list 'rtn (match-string 1 cfmt))))))))
16354 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
16356 (defun org-property-values (key)
16357 "Return a list of all values of property KEY."
16358 (save-excursion
16359 (save-restriction
16360 (widen)
16361 (goto-char (point-min))
16362 (let ((re (concat "^[ \t]*:" key ":[ \t]*\\(\\S-.*\\)"))
16363 values)
16364 (while (re-search-forward re nil t)
16365 (add-to-list 'values (org-trim (match-string 1))))
16366 (delete "" values)))))
16368 (defun org-insert-property-drawer ()
16369 "Insert a property drawer into the current entry."
16370 (interactive)
16371 (org-back-to-heading t)
16372 (looking-at outline-regexp)
16373 (let ((indent (- (match-end 0)(match-beginning 0)))
16374 (beg (point))
16375 (re (concat "^[ \t]*" org-keyword-time-regexp))
16376 end hiddenp)
16377 (outline-next-heading)
16378 (setq end (point))
16379 (goto-char beg)
16380 (while (re-search-forward re end t))
16381 (setq hiddenp (org-invisible-p))
16382 (end-of-line 1)
16383 (and (equal (char-after) ?\n) (forward-char 1))
16384 (org-skip-over-state-notes)
16385 (skip-chars-backward " \t\n\r")
16386 (if (eq (char-before) ?*) (forward-char 1))
16387 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
16388 (beginning-of-line 0)
16389 (indent-to-column indent)
16390 (beginning-of-line 2)
16391 (indent-to-column indent)
16392 (beginning-of-line 0)
16393 (if hiddenp
16394 (save-excursion
16395 (org-back-to-heading t)
16396 (hide-entry))
16397 (org-flag-drawer t))))
16399 (defun org-set-property (property value)
16400 "In the current entry, set PROPERTY to VALUE.
16401 When called interactively, this will prompt for a property name, offering
16402 completion on existing and default properties. And then it will prompt
16403 for a value, offering competion either on allowed values (via an inherited
16404 xxx_ALL property) or on existing values in other instances of this property
16405 in the current file."
16406 (interactive
16407 (let* ((prop (completing-read
16408 "Property: " (mapcar 'list (org-buffer-property-keys nil t t))))
16409 (cur (org-entry-get nil prop))
16410 (allowed (org-property-get-allowed-values nil prop 'table))
16411 (existing (mapcar 'list (org-property-values prop)))
16412 (val (if allowed
16413 (completing-read "Value: " allowed nil 'req-match)
16414 (completing-read
16415 (concat "Value" (if (and cur (string-match "\\S-" cur))
16416 (concat "[" cur "]") "")
16417 ": ")
16418 existing nil nil "" nil cur))))
16419 (list prop (if (equal val "") cur val))))
16420 (unless (equal (org-entry-get nil property) value)
16421 (org-entry-put nil property value)))
16423 (defun org-delete-property (property)
16424 "In the current entry, delete PROPERTY."
16425 (interactive
16426 (let* ((prop (completing-read
16427 "Property: " (org-entry-properties nil 'standard))))
16428 (list prop)))
16429 (message "Property %s %s" property
16430 (if (org-entry-delete nil property)
16431 "deleted"
16432 "was not present in the entry")))
16434 (defun org-delete-property-globally (property)
16435 "Remove PROPERTY globally, from all entries."
16436 (interactive
16437 (let* ((prop (completing-read
16438 "Globally remove property: "
16439 (mapcar 'list (org-buffer-property-keys)))))
16440 (list prop)))
16441 (save-excursion
16442 (save-restriction
16443 (widen)
16444 (goto-char (point-min))
16445 (let ((cnt 0))
16446 (while (re-search-forward
16447 (concat "^[ \t]*:" (regexp-quote property) ":.*\n?")
16448 nil t)
16449 (setq cnt (1+ cnt))
16450 (replace-match ""))
16451 (message "Property \"%s\" removed from %d entries" property cnt)))))
16453 (defvar org-columns-current-fmt-compiled) ; defined below
16455 (defun org-compute-property-at-point ()
16456 "Compute the property at point.
16457 This looks for an enclosing column format, extracts the operator and
16458 then applies it to the proerty in the column format's scope."
16459 (interactive)
16460 (unless (org-at-property-p)
16461 (error "Not at a property"))
16462 (let ((prop (org-match-string-no-properties 2)))
16463 (org-columns-get-format-and-top-level)
16464 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
16465 (error "No operator defined for property %s" prop))
16466 (org-columns-compute prop)))
16468 (defun org-property-get-allowed-values (pom property &optional table)
16469 "Get allowed values for the property PROPERTY.
16470 When TABLE is non-nil, return an alist that can directly be used for
16471 completion."
16472 (let (vals)
16473 (cond
16474 ((equal property "TODO")
16475 (setq vals (org-with-point-at pom
16476 (append org-todo-keywords-1 '("")))))
16477 ((equal property "PRIORITY")
16478 (let ((n org-lowest-priority))
16479 (while (>= n org-highest-priority)
16480 (push (char-to-string n) vals)
16481 (setq n (1- n)))))
16482 ((member property org-special-properties))
16484 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
16486 (when (and vals (string-match "\\S-" vals))
16487 (setq vals (car (read-from-string (concat "(" vals ")"))))
16488 (setq vals (mapcar (lambda (x)
16489 (cond ((stringp x) x)
16490 ((numberp x) (number-to-string x))
16491 ((symbolp x) (symbol-name x))
16492 (t "???")))
16493 vals)))))
16494 (if table (mapcar 'list vals) vals)))
16496 (defun org-property-previous-allowed-value (&optional previous)
16497 "Switch to the next allowed value for this property."
16498 (interactive)
16499 (org-property-next-allowed-value t))
16501 (defun org-property-next-allowed-value (&optional previous)
16502 "Switch to the next allowed value for this property."
16503 (interactive)
16504 (unless (org-at-property-p)
16505 (error "Not at a property"))
16506 (let* ((key (match-string 2))
16507 (value (match-string 3))
16508 (allowed (or (org-property-get-allowed-values (point) key)
16509 (and (member value '("[ ]" "[-]" "[X]"))
16510 '("[ ]" "[X]"))))
16511 nval)
16512 (unless allowed
16513 (error "Allowed values for this property have not been defined"))
16514 (if previous (setq allowed (reverse allowed)))
16515 (if (member value allowed)
16516 (setq nval (car (cdr (member value allowed)))))
16517 (setq nval (or nval (car allowed)))
16518 (if (equal nval value)
16519 (error "Only one allowed value for this property"))
16520 (org-at-property-p)
16521 (replace-match (concat " :" key ": " nval) t t)
16522 (org-indent-line-function)
16523 (beginning-of-line 1)
16524 (skip-chars-forward " \t")))
16526 (defun org-find-entry-with-id (ident)
16527 "Locate the entry that contains the ID property with exact value IDENT.
16528 IDENT can be a string, a symbol or a number, this function will search for
16529 the string representation of it.
16530 Return the position where this entry starts, or nil if there is no such entry."
16531 (let ((id (cond
16532 ((stringp ident) ident)
16533 ((symbol-name ident) (symbol-name ident))
16534 ((numberp ident) (number-to-string ident))
16535 (t (error "IDENT %s must be a string, symbol or number" ident))))
16536 (case-fold-search nil))
16537 (save-excursion
16538 (save-restriction
16539 (widen)
16540 (goto-char (point-min))
16541 (when (re-search-forward
16542 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
16543 nil t)
16544 (org-back-to-heading)
16545 (point))))))
16547 ;;; Column View
16549 (defvar org-columns-overlays nil
16550 "Holds the list of current column overlays.")
16552 (defvar org-columns-current-fmt nil
16553 "Local variable, holds the currently active column format.")
16554 (defvar org-columns-current-fmt-compiled nil
16555 "Local variable, holds the currently active column format.
16556 This is the compiled version of the format.")
16557 (defvar org-columns-current-widths nil
16558 "Loval variable, holds the currently widths of fields.")
16559 (defvar org-columns-current-maxwidths nil
16560 "Loval variable, holds the currently active maximum column widths.")
16561 (defvar org-columns-begin-marker (make-marker)
16562 "Points to the position where last a column creation command was called.")
16563 (defvar org-columns-top-level-marker (make-marker)
16564 "Points to the position where current columns region starts.")
16566 (defvar org-columns-map (make-sparse-keymap)
16567 "The keymap valid in column display.")
16569 (defun org-columns-content ()
16570 "Switch to contents view while in columns view."
16571 (interactive)
16572 (org-overview)
16573 (org-content))
16575 (org-defkey org-columns-map "c" 'org-columns-content)
16576 (org-defkey org-columns-map "o" 'org-overview)
16577 (org-defkey org-columns-map "e" 'org-columns-edit-value)
16578 (org-defkey org-columns-map "\C-c\C-t" 'org-columns-todo)
16579 (org-defkey org-columns-map "\C-c\C-c" 'org-columns-set-tags-or-toggle)
16580 (org-defkey org-columns-map "\C-c\C-o" 'org-columns-open-link)
16581 (org-defkey org-columns-map "v" 'org-columns-show-value)
16582 (org-defkey org-columns-map "q" 'org-columns-quit)
16583 (org-defkey org-columns-map "r" 'org-columns-redo)
16584 (org-defkey org-columns-map "g" 'org-columns-redo)
16585 (org-defkey org-columns-map [left] 'backward-char)
16586 (org-defkey org-columns-map "\M-b" 'backward-char)
16587 (org-defkey org-columns-map "a" 'org-columns-edit-allowed)
16588 (org-defkey org-columns-map "s" 'org-columns-edit-attributes)
16589 (org-defkey org-columns-map "\M-f" (lambda () (interactive) (goto-char (1+ (point)))))
16590 (org-defkey org-columns-map [right] (lambda () (interactive) (goto-char (1+ (point)))))
16591 (org-defkey org-columns-map [(shift right)] 'org-columns-next-allowed-value)
16592 (org-defkey org-columns-map "n" 'org-columns-next-allowed-value)
16593 (org-defkey org-columns-map [(shift left)] 'org-columns-previous-allowed-value)
16594 (org-defkey org-columns-map "p" 'org-columns-previous-allowed-value)
16595 (org-defkey org-columns-map "<" 'org-columns-narrow)
16596 (org-defkey org-columns-map ">" 'org-columns-widen)
16597 (org-defkey org-columns-map [(meta right)] 'org-columns-move-right)
16598 (org-defkey org-columns-map [(meta left)] 'org-columns-move-left)
16599 (org-defkey org-columns-map [(shift meta right)] 'org-columns-new)
16600 (org-defkey org-columns-map [(shift meta left)] 'org-columns-delete)
16602 (easy-menu-define org-columns-menu org-columns-map "Org Column Menu"
16603 '("Column"
16604 ["Edit property" org-columns-edit-value t]
16605 ["Next allowed value" org-columns-next-allowed-value t]
16606 ["Previous allowed value" org-columns-previous-allowed-value t]
16607 ["Show full value" org-columns-show-value t]
16608 ["Edit allowed values" org-columns-edit-allowed t]
16609 "--"
16610 ["Edit column attributes" org-columns-edit-attributes t]
16611 ["Increase column width" org-columns-widen t]
16612 ["Decrease column width" org-columns-narrow t]
16613 "--"
16614 ["Move column right" org-columns-move-right t]
16615 ["Move column left" org-columns-move-left t]
16616 ["Add column" org-columns-new t]
16617 ["Delete column" org-columns-delete t]
16618 "--"
16619 ["CONTENTS" org-columns-content t]
16620 ["OVERVIEW" org-overview t]
16621 ["Refresh columns display" org-columns-redo t]
16622 "--"
16623 ["Open link" org-columns-open-link t]
16624 "--"
16625 ["Quit" org-columns-quit t]))
16627 (defun org-columns-new-overlay (beg end &optional string face)
16628 "Create a new column overlay and add it to the list."
16629 (let ((ov (org-make-overlay beg end)))
16630 (org-overlay-put ov 'face (or face 'secondary-selection))
16631 (org-overlay-display ov string face)
16632 (push ov org-columns-overlays)
16633 ov))
16635 (defun org-columns-display-here (&optional props)
16636 "Overlay the current line with column display."
16637 (interactive)
16638 (let* ((fmt org-columns-current-fmt-compiled)
16639 (beg (point-at-bol))
16640 (level-face (save-excursion
16641 (beginning-of-line 1)
16642 (and (looking-at "\\(\\**\\)\\(\\* \\)")
16643 (org-get-level-face 2))))
16644 (color (list :foreground
16645 (face-attribute (or level-face 'default) :foreground)))
16646 props pom property ass width f string ov column val modval)
16647 ;; Check if the entry is in another buffer.
16648 (unless props
16649 (if (eq major-mode 'org-agenda-mode)
16650 (setq pom (or (get-text-property (point) 'org-hd-marker)
16651 (get-text-property (point) 'org-marker))
16652 props (if pom (org-entry-properties pom) nil))
16653 (setq props (org-entry-properties nil))))
16654 ;; Walk the format
16655 (while (setq column (pop fmt))
16656 (setq property (car column)
16657 ass (if (equal property "ITEM")
16658 (cons "ITEM"
16659 (save-match-data
16660 (org-no-properties
16661 (org-remove-tabs
16662 (buffer-substring-no-properties
16663 (point-at-bol) (point-at-eol))))))
16664 (assoc property props))
16665 width (or (cdr (assoc property org-columns-current-maxwidths))
16666 (nth 2 column)
16667 (length property))
16668 f (format "%%-%d.%ds | " width width)
16669 val (or (cdr ass) "")
16670 modval (if (equal property "ITEM")
16671 (org-columns-cleanup-item val org-columns-current-fmt-compiled))
16672 string (format f (or modval val)))
16673 ;; Create the overlay
16674 (org-unmodified
16675 (setq ov (org-columns-new-overlay
16676 beg (setq beg (1+ beg)) string
16677 (list color 'org-column)))
16678 ;;; (list (get-text-property (point-at-bol) 'face) 'org-column)))
16679 (org-overlay-put ov 'keymap org-columns-map)
16680 (org-overlay-put ov 'org-columns-key property)
16681 (org-overlay-put ov 'org-columns-value (cdr ass))
16682 (org-overlay-put ov 'org-columns-value-modified modval)
16683 (org-overlay-put ov 'org-columns-pom pom)
16684 (org-overlay-put ov 'org-columns-format f))
16685 (if (or (not (char-after beg))
16686 (equal (char-after beg) ?\n))
16687 (let ((inhibit-read-only t))
16688 (save-excursion
16689 (goto-char beg)
16690 (org-unmodified (insert " ")))))) ;; FIXME: add props and remove later?
16691 ;; Make the rest of the line disappear.
16692 (org-unmodified
16693 (setq ov (org-columns-new-overlay beg (point-at-eol)))
16694 (org-overlay-put ov 'invisible t)
16695 (org-overlay-put ov 'keymap org-columns-map)
16696 (org-overlay-put ov 'intangible t)
16697 (push ov org-columns-overlays)
16698 (setq ov (org-make-overlay (1- (point-at-eol)) (1+ (point-at-eol))))
16699 (org-overlay-put ov 'keymap org-columns-map)
16700 (push ov org-columns-overlays)
16701 (let ((inhibit-read-only t))
16702 (put-text-property (max (point-min) (1- (point-at-bol)))
16703 (min (point-max) (1+ (point-at-eol)))
16704 'read-only "Type `e' to edit property")))))
16706 (defvar org-previous-header-line-format nil
16707 "The header line format before column view was turned on.")
16708 (defvar org-columns-inhibit-recalculation nil
16709 "Inhibit recomputing of columns on column view startup.")
16712 (defvar header-line-format)
16713 (defun org-columns-display-here-title ()
16714 "Overlay the newline before the current line with the table title."
16715 (interactive)
16716 (let ((fmt org-columns-current-fmt-compiled)
16717 string (title "")
16718 property width f column str widths)
16719 (while (setq column (pop fmt))
16720 (setq property (car column)
16721 str (or (nth 1 column) property)
16722 width (or (cdr (assoc property org-columns-current-maxwidths))
16723 (nth 2 column)
16724 (length str))
16725 widths (push width widths)
16726 f (format "%%-%d.%ds | " width width)
16727 string (format f str)
16728 title (concat title string)))
16729 (setq title (concat
16730 (org-add-props " " nil 'display '(space :align-to 0))
16731 (org-add-props title nil 'face '(:weight bold :underline t))))
16732 (org-set-local 'org-previous-header-line-format header-line-format)
16733 (org-set-local 'org-columns-current-widths (nreverse widths))
16734 (setq header-line-format title)))
16736 (defun org-columns-remove-overlays ()
16737 "Remove all currently active column overlays."
16738 (interactive)
16739 (when (marker-buffer org-columns-begin-marker)
16740 (with-current-buffer (marker-buffer org-columns-begin-marker)
16741 (when (local-variable-p 'org-previous-header-line-format)
16742 (setq header-line-format org-previous-header-line-format)
16743 (kill-local-variable 'org-previous-header-line-format))
16744 (move-marker org-columns-begin-marker nil)
16745 (move-marker org-columns-top-level-marker nil)
16746 (org-unmodified
16747 (mapc 'org-delete-overlay org-columns-overlays)
16748 (setq org-columns-overlays nil)
16749 (let ((inhibit-read-only t))
16750 (remove-text-properties (point-min) (point-max) '(read-only t)))))))
16752 (defun org-columns-cleanup-item (item fmt)
16753 "Remove from ITEM what is a column in the format FMT."
16754 (if (not org-complex-heading-regexp)
16755 item
16756 (when (string-match org-complex-heading-regexp item)
16757 (concat
16758 (org-add-props (concat (match-string 1 item) " ") nil
16759 'org-whitespace (* 2 (1- (org-reduced-level (- (match-end 1) (match-beginning 1))))))
16760 (and (match-end 2) (not (assoc "TODO" fmt)) (concat " " (match-string 2 item)))
16761 (and (match-end 3) (not (assoc "PRIORITY" fmt)) (concat " " (match-string 3 item)))
16762 " " (match-string 4 item)
16763 (and (match-end 5) (not (assoc "TAGS" fmt)) (concat " " (match-string 5 item)))))))
16765 (defun org-columns-show-value ()
16766 "Show the full value of the property."
16767 (interactive)
16768 (let ((value (get-char-property (point) 'org-columns-value)))
16769 (message "Value is: %s" (or value ""))))
16771 (defun org-columns-quit ()
16772 "Remove the column overlays and in this way exit column editing."
16773 (interactive)
16774 (org-unmodified
16775 (org-columns-remove-overlays)
16776 (let ((inhibit-read-only t))
16777 (remove-text-properties (point-min) (point-max) '(read-only t))))
16778 (when (eq major-mode 'org-agenda-mode)
16779 (message
16780 "Modification not yet reflected in Agenda buffer, use `r' to refresh")))
16782 (defun org-columns-check-computed ()
16783 "Check if this column value is computed.
16784 If yes, throw an error indicating that changing it does not make sense."
16785 (let ((val (get-char-property (point) 'org-columns-value)))
16786 (when (and (stringp val)
16787 (get-char-property 0 'org-computed val))
16788 (error "This value is computed from the entry's children"))))
16790 (defun org-columns-todo (&optional arg)
16791 "Change the TODO state during column view."
16792 (interactive "P")
16793 (org-columns-edit-value "TODO"))
16795 (defun org-columns-set-tags-or-toggle (&optional arg)
16796 "Toggle checkbox at point, or set tags for current headline."
16797 (interactive "P")
16798 (if (string-match "\\`\\[[ xX-]\\]\\'"
16799 (get-char-property (point) 'org-columns-value))
16800 (org-columns-next-allowed-value)
16801 (org-columns-edit-value "TAGS")))
16803 (defun org-columns-edit-value (&optional key)
16804 "Edit the value of the property at point in column view.
16805 Where possible, use the standard interface for changing this line."
16806 (interactive)
16807 (org-columns-check-computed)
16808 (let* ((external-key key)
16809 (col (current-column))
16810 (key (or key (get-char-property (point) 'org-columns-key)))
16811 (value (get-char-property (point) 'org-columns-value))
16812 (bol (point-at-bol)) (eol (point-at-eol))
16813 (pom (or (get-text-property bol 'org-hd-marker)
16814 (point))) ; keep despite of compiler waring
16815 (line-overlays
16816 (delq nil (mapcar (lambda (x)
16817 (and (eq (overlay-buffer x) (current-buffer))
16818 (>= (overlay-start x) bol)
16819 (<= (overlay-start x) eol)
16821 org-columns-overlays)))
16822 nval eval allowed)
16823 (cond
16824 ((equal key "CLOCKSUM")
16825 (error "This special column cannot be edited"))
16826 ((equal key "ITEM")
16827 (setq eval '(org-with-point-at pom
16828 (org-edit-headline))))
16829 ((equal key "TODO")
16830 (setq eval '(org-with-point-at pom
16831 (let ((current-prefix-arg
16832 (if external-key current-prefix-arg '(4))))
16833 (call-interactively 'org-todo)))))
16834 ((equal key "PRIORITY")
16835 (setq eval '(org-with-point-at pom
16836 (call-interactively 'org-priority))))
16837 ((equal key "TAGS")
16838 (setq eval '(org-with-point-at pom
16839 (let ((org-fast-tag-selection-single-key
16840 (if (eq org-fast-tag-selection-single-key 'expert)
16841 t org-fast-tag-selection-single-key)))
16842 (call-interactively 'org-set-tags)))))
16843 ((equal key "DEADLINE")
16844 (setq eval '(org-with-point-at pom
16845 (call-interactively 'org-deadline))))
16846 ((equal key "SCHEDULED")
16847 (setq eval '(org-with-point-at pom
16848 (call-interactively 'org-schedule))))
16850 (setq allowed (org-property-get-allowed-values pom key 'table))
16851 (if allowed
16852 (setq nval (completing-read "Value: " allowed nil t))
16853 (setq nval (read-string "Edit: " value)))
16854 (setq nval (org-trim nval))
16855 (when (not (equal nval value))
16856 (setq eval '(org-entry-put pom key nval)))))
16857 (when eval
16858 (let ((inhibit-read-only t))
16859 (remove-text-properties (max (point-min) (1- bol)) eol '(read-only t))
16860 (unwind-protect
16861 (progn
16862 (setq org-columns-overlays
16863 (org-delete-all line-overlays org-columns-overlays))
16864 (mapc 'org-delete-overlay line-overlays)
16865 (org-columns-eval eval))
16866 (org-columns-display-here))))
16867 (move-to-column col)
16868 (if (and (org-mode-p)
16869 (nth 3 (assoc key org-columns-current-fmt-compiled)))
16870 (org-columns-update key))))
16872 (defun org-edit-headline () ; FIXME: this is not columns specific
16873 "Edit the current headline, the part without TODO keyword, TAGS."
16874 (org-back-to-heading)
16875 (when (looking-at org-todo-line-regexp)
16876 (let ((pre (buffer-substring (match-beginning 0) (match-beginning 3)))
16877 (txt (match-string 3))
16878 (post "")
16879 txt2)
16880 (if (string-match (org-re "[ \t]+:[[:alnum:]:_@]+:[ \t]*$") txt)
16881 (setq post (match-string 0 txt)
16882 txt (substring txt 0 (match-beginning 0))))
16883 (setq txt2 (read-string "Edit: " txt))
16884 (when (not (equal txt txt2))
16885 (beginning-of-line 1)
16886 (insert pre txt2 post)
16887 (delete-region (point) (point-at-eol))
16888 (org-set-tags nil t)))))
16890 (defun org-columns-edit-allowed ()
16891 "Edit the list of allowed values for the current property."
16892 (interactive)
16893 (let* ((key (get-char-property (point) 'org-columns-key))
16894 (key1 (concat key "_ALL"))
16895 (allowed (org-entry-get (point) key1 t))
16896 nval)
16897 ;; FIXME: Cover editing TODO, TAGS etc in-buffer settings.????
16898 (setq nval (read-string "Allowed: " allowed))
16899 (org-entry-put
16900 (cond ((marker-position org-entry-property-inherited-from)
16901 org-entry-property-inherited-from)
16902 ((marker-position org-columns-top-level-marker)
16903 org-columns-top-level-marker))
16904 key1 nval)))
16906 (defmacro org-no-warnings (&rest body)
16907 (cons (if (fboundp 'with-no-warnings) 'with-no-warnings 'progn) body))
16909 (defun org-columns-eval (form)
16910 (let (hidep)
16911 (save-excursion
16912 (beginning-of-line 1)
16913 ;; `next-line' is needed here, because it skips invisible line.
16914 (condition-case nil (org-no-warnings (next-line 1)) (error nil))
16915 (setq hidep (org-on-heading-p 1)))
16916 (eval form)
16917 (and hidep (hide-entry))))
16919 (defun org-columns-previous-allowed-value ()
16920 "Switch to the previous allowed value for this column."
16921 (interactive)
16922 (org-columns-next-allowed-value t))
16924 (defun org-columns-next-allowed-value (&optional previous)
16925 "Switch to the next allowed value for this column."
16926 (interactive)
16927 (org-columns-check-computed)
16928 (let* ((col (current-column))
16929 (key (get-char-property (point) 'org-columns-key))
16930 (value (get-char-property (point) 'org-columns-value))
16931 (bol (point-at-bol)) (eol (point-at-eol))
16932 (pom (or (get-text-property bol 'org-hd-marker)
16933 (point))) ; keep despite of compiler waring
16934 (line-overlays
16935 (delq nil (mapcar (lambda (x)
16936 (and (eq (overlay-buffer x) (current-buffer))
16937 (>= (overlay-start x) bol)
16938 (<= (overlay-start x) eol)
16940 org-columns-overlays)))
16941 (allowed (or (org-property-get-allowed-values pom key)
16942 (and (memq
16943 (nth 4 (assoc key org-columns-current-fmt-compiled))
16944 '(checkbox checkbox-n-of-m checkbox-percent))
16945 '("[ ]" "[X]"))))
16946 nval)
16947 (when (equal key "ITEM")
16948 (error "Cannot edit item headline from here"))
16949 (unless (or allowed (member key '("SCHEDULED" "DEADLINE")))
16950 (error "Allowed values for this property have not been defined"))
16951 (if (member key '("SCHEDULED" "DEADLINE"))
16952 (setq nval (if previous 'earlier 'later))
16953 (if previous (setq allowed (reverse allowed)))
16954 (if (member value allowed)
16955 (setq nval (car (cdr (member value allowed)))))
16956 (setq nval (or nval (car allowed)))
16957 (if (equal nval value)
16958 (error "Only one allowed value for this property")))
16959 (let ((inhibit-read-only t))
16960 (remove-text-properties (1- bol) eol '(read-only t))
16961 (unwind-protect
16962 (progn
16963 (setq org-columns-overlays
16964 (org-delete-all line-overlays org-columns-overlays))
16965 (mapc 'org-delete-overlay line-overlays)
16966 (org-columns-eval '(org-entry-put pom key nval)))
16967 (org-columns-display-here)))
16968 (move-to-column col)
16969 (if (and (org-mode-p)
16970 (nth 3 (assoc key org-columns-current-fmt-compiled)))
16971 (org-columns-update key))))
16973 (defun org-verify-version (task)
16974 (cond
16975 ((eq task 'columns)
16976 (if (or (featurep 'xemacs)
16977 (< emacs-major-version 22))
16978 (error "Emacs 22 is required for the columns feature")))))
16980 (defun org-columns-open-link (&optional arg)
16981 (interactive "P")
16982 (let ((value (get-char-property (point) 'org-columns-value)))
16983 (org-open-link-from-string value arg)))
16985 (defun org-open-link-from-string (s &optional arg)
16986 "Open a link in the string S, as if it was in Org-mode."
16987 (interactive)
16988 (with-temp-buffer
16989 (let ((org-inhibit-startup t))
16990 (org-mode)
16991 (insert s)
16992 (goto-char (point-min))
16993 (org-open-at-point arg))))
16995 (defun org-columns-get-format-and-top-level ()
16996 (let (fmt)
16997 (when (condition-case nil (org-back-to-heading) (error nil))
16998 (move-marker org-entry-property-inherited-from nil)
16999 (setq fmt (org-entry-get nil "COLUMNS" t)))
17000 (setq fmt (or fmt org-columns-default-format))
17001 (org-set-local 'org-columns-current-fmt fmt)
17002 (org-columns-compile-format fmt)
17003 (if (marker-position org-entry-property-inherited-from)
17004 (move-marker org-columns-top-level-marker
17005 org-entry-property-inherited-from)
17006 (move-marker org-columns-top-level-marker (point)))
17007 fmt))
17009 (defun org-columns ()
17010 "Turn on column view on an org-mode file."
17011 (interactive)
17012 (org-verify-version 'columns)
17013 (org-columns-remove-overlays)
17014 (move-marker org-columns-begin-marker (point))
17015 (let (beg end fmt cache maxwidths)
17016 (setq fmt (org-columns-get-format-and-top-level))
17017 (save-excursion
17018 (goto-char org-columns-top-level-marker)
17019 (setq beg (point))
17020 (unless org-columns-inhibit-recalculation
17021 (org-columns-compute-all))
17022 (setq end (or (condition-case nil (org-end-of-subtree t t) (error nil))
17023 (point-max)))
17024 ;; Get and cache the properties
17025 (goto-char beg)
17026 (when (assoc "CLOCKSUM" org-columns-current-fmt-compiled)
17027 (save-excursion
17028 (save-restriction
17029 (narrow-to-region beg end)
17030 (org-clock-sum))))
17031 (while (re-search-forward (concat "^" outline-regexp) end t)
17032 (push (cons (org-current-line) (org-entry-properties)) cache))
17033 (when cache
17034 (setq maxwidths (org-columns-get-autowidth-alist fmt cache))
17035 (org-set-local 'org-columns-current-maxwidths maxwidths)
17036 (org-columns-display-here-title)
17037 (mapc (lambda (x)
17038 (goto-line (car x))
17039 (org-columns-display-here (cdr x)))
17040 cache)))))
17042 (defun org-columns-new (&optional prop title width op fmt &rest rest)
17043 "Insert a new column, to the leeft o the current column."
17044 (interactive)
17045 (let ((editp (and prop (assoc prop org-columns-current-fmt-compiled)))
17046 cell)
17047 (setq prop (completing-read
17048 "Property: " (mapcar 'list (org-buffer-property-keys t nil t))
17049 nil nil prop))
17050 (setq title (read-string (concat "Column title [" prop "]: ") (or title prop)))
17051 (setq width (read-string "Column width: " (if width (number-to-string width))))
17052 (if (string-match "\\S-" width)
17053 (setq width (string-to-number width))
17054 (setq width nil))
17055 (setq fmt (completing-read "Summary [none]: "
17056 '(("none") ("add_numbers") ("currency") ("add_times") ("checkbox") ("checkbox-n-of-m") ("checkbox-percent"))
17057 nil t))
17058 (if (string-match "\\S-" fmt)
17059 (setq fmt (intern fmt))
17060 (setq fmt nil))
17061 (if (eq fmt 'none) (setq fmt nil))
17062 (if editp
17063 (progn
17064 (setcar editp prop)
17065 (setcdr editp (list title width nil fmt)))
17066 (setq cell (nthcdr (1- (current-column))
17067 org-columns-current-fmt-compiled))
17068 (setcdr cell (cons (list prop title width nil fmt)
17069 (cdr cell))))
17070 (org-columns-store-format)
17071 (org-columns-redo)))
17073 (defun org-columns-delete ()
17074 "Delete the column at point from columns view."
17075 (interactive)
17076 (let* ((n (current-column))
17077 (title (nth 1 (nth n org-columns-current-fmt-compiled))))
17078 (when (y-or-n-p
17079 (format "Are you sure you want to remove column \"%s\"? " title))
17080 (setq org-columns-current-fmt-compiled
17081 (delq (nth n org-columns-current-fmt-compiled)
17082 org-columns-current-fmt-compiled))
17083 (org-columns-store-format)
17084 (org-columns-redo)
17085 (if (>= (current-column) (length org-columns-current-fmt-compiled))
17086 (backward-char 1)))))
17088 (defun org-columns-edit-attributes ()
17089 "Edit the attributes of the current column."
17090 (interactive)
17091 (let* ((n (current-column))
17092 (info (nth n org-columns-current-fmt-compiled)))
17093 (apply 'org-columns-new info)))
17095 (defun org-columns-widen (arg)
17096 "Make the column wider by ARG characters."
17097 (interactive "p")
17098 (let* ((n (current-column))
17099 (entry (nth n org-columns-current-fmt-compiled))
17100 (width (or (nth 2 entry)
17101 (cdr (assoc (car entry) org-columns-current-maxwidths)))))
17102 (setq width (max 1 (+ width arg)))
17103 (setcar (nthcdr 2 entry) width)
17104 (org-columns-store-format)
17105 (org-columns-redo)))
17107 (defun org-columns-narrow (arg)
17108 "Make the column nrrower by ARG characters."
17109 (interactive "p")
17110 (org-columns-widen (- arg)))
17112 (defun org-columns-move-right ()
17113 "Swap this column with the one to the right."
17114 (interactive)
17115 (let* ((n (current-column))
17116 (cell (nthcdr n org-columns-current-fmt-compiled))
17118 (when (>= n (1- (length org-columns-current-fmt-compiled)))
17119 (error "Cannot shift this column further to the right"))
17120 (setq e (car cell))
17121 (setcar cell (car (cdr cell)))
17122 (setcdr cell (cons e (cdr (cdr cell))))
17123 (org-columns-store-format)
17124 (org-columns-redo)
17125 (forward-char 1)))
17127 (defun org-columns-move-left ()
17128 "Swap this column with the one to the left."
17129 (interactive)
17130 (let* ((n (current-column)))
17131 (when (= n 0)
17132 (error "Cannot shift this column further to the left"))
17133 (backward-char 1)
17134 (org-columns-move-right)
17135 (backward-char 1)))
17137 (defun org-columns-store-format ()
17138 "Store the text version of the current columns format in appropriate place.
17139 This is either in the COLUMNS property of the node starting the current column
17140 display, or in the #+COLUMNS line of the current buffer."
17141 (let (fmt (cnt 0))
17142 (setq fmt (org-columns-uncompile-format org-columns-current-fmt-compiled))
17143 (org-set-local 'org-columns-current-fmt fmt)
17144 (if (marker-position org-columns-top-level-marker)
17145 (save-excursion
17146 (goto-char org-columns-top-level-marker)
17147 (if (and (org-at-heading-p)
17148 (org-entry-get nil "COLUMNS"))
17149 (org-entry-put nil "COLUMNS" fmt)
17150 (goto-char (point-min))
17151 ;; Overwrite all #+COLUMNS lines....
17152 (while (re-search-forward "^#\\+COLUMNS:.*" nil t)
17153 (setq cnt (1+ cnt))
17154 (replace-match (concat "#+COLUMNS: " fmt) t t))
17155 (unless (> cnt 0)
17156 (goto-char (point-min))
17157 (or (org-on-heading-p t) (outline-next-heading))
17158 (let ((inhibit-read-only t))
17159 (insert-before-markers "#+COLUMNS: " fmt "\n")))
17160 (org-set-local 'org-columns-default-format fmt))))))
17162 (defvar org-overriding-columns-format nil
17163 "When set, overrides any other definition.")
17164 (defvar org-agenda-view-columns-initially nil
17165 "When set, switch to columns view immediately after creating the agenda.")
17167 (defun org-agenda-columns ()
17168 "Turn on column view in the agenda."
17169 (interactive)
17170 (org-verify-version 'columns)
17171 (org-columns-remove-overlays)
17172 (move-marker org-columns-begin-marker (point))
17173 (let (fmt cache maxwidths m)
17174 (cond
17175 ((and (local-variable-p 'org-overriding-columns-format)
17176 org-overriding-columns-format)
17177 (setq fmt org-overriding-columns-format))
17178 ((setq m (get-text-property (point-at-bol) 'org-hd-marker))
17179 (setq fmt (org-entry-get m "COLUMNS" t)))
17180 ((and (boundp 'org-columns-current-fmt)
17181 (local-variable-p 'org-columns-current-fmt)
17182 org-columns-current-fmt)
17183 (setq fmt org-columns-current-fmt))
17184 ((setq m (next-single-property-change (point-min) 'org-hd-marker))
17185 (setq m (get-text-property m 'org-hd-marker))
17186 (setq fmt (org-entry-get m "COLUMNS" t))))
17187 (setq fmt (or fmt org-columns-default-format))
17188 (org-set-local 'org-columns-current-fmt fmt)
17189 (org-columns-compile-format fmt)
17190 (save-excursion
17191 ;; Get and cache the properties
17192 (goto-char (point-min))
17193 (while (not (eobp))
17194 (when (setq m (or (get-text-property (point) 'org-hd-marker)
17195 (get-text-property (point) 'org-marker)))
17196 (push (cons (org-current-line) (org-entry-properties m)) cache))
17197 (beginning-of-line 2))
17198 (when cache
17199 (setq maxwidths (org-columns-get-autowidth-alist fmt cache))
17200 (org-set-local 'org-columns-current-maxwidths maxwidths)
17201 (org-columns-display-here-title)
17202 (mapc (lambda (x)
17203 (goto-line (car x))
17204 (org-columns-display-here (cdr x)))
17205 cache)))))
17207 (defun org-columns-get-autowidth-alist (s cache)
17208 "Derive the maximum column widths from the format and the cache."
17209 (let ((start 0) rtn)
17210 (while (string-match (org-re "%\\([[:alpha:]][[:alnum:]_-]*\\)") s start)
17211 (push (cons (match-string 1 s) 1) rtn)
17212 (setq start (match-end 0)))
17213 (mapc (lambda (x)
17214 (setcdr x (apply 'max
17215 (mapcar
17216 (lambda (y)
17217 (length (or (cdr (assoc (car x) (cdr y))) " ")))
17218 cache))))
17219 rtn)
17220 rtn))
17222 (defun org-columns-compute-all ()
17223 "Compute all columns that have operators defined."
17224 (org-unmodified
17225 (remove-text-properties (point-min) (point-max) '(org-summaries t)))
17226 (let ((columns org-columns-current-fmt-compiled) col)
17227 (while (setq col (pop columns))
17228 (when (nth 3 col)
17229 (save-excursion
17230 (org-columns-compute (car col)))))))
17232 (defun org-columns-update (property)
17233 "Recompute PROPERTY, and update the columns display for it."
17234 (org-columns-compute property)
17235 (let (fmt val pos)
17236 (save-excursion
17237 (mapc (lambda (ov)
17238 (when (equal (org-overlay-get ov 'org-columns-key) property)
17239 (setq pos (org-overlay-start ov))
17240 (goto-char pos)
17241 (when (setq val (cdr (assoc property
17242 (get-text-property
17243 (point-at-bol) 'org-summaries))))
17244 (setq fmt (org-overlay-get ov 'org-columns-format))
17245 (org-overlay-put ov 'org-columns-value val)
17246 (org-overlay-put ov 'display (format fmt val)))))
17247 org-columns-overlays))))
17249 (defun org-columns-compute (property)
17250 "Sum the values of property PROPERTY hierarchically, for the entire buffer."
17251 (interactive)
17252 (let* ((re (concat "^" outline-regexp))
17253 (lmax 30) ; Does anyone use deeper levels???
17254 (lsum (make-vector lmax 0))
17255 (lflag (make-vector lmax nil))
17256 (level 0)
17257 (ass (assoc property org-columns-current-fmt-compiled))
17258 (format (nth 4 ass))
17259 (printf (nth 5 ass))
17260 (beg org-columns-top-level-marker)
17261 last-level val valflag flag end sumpos sum-alist sum str str1 useval)
17262 (save-excursion
17263 ;; Find the region to compute
17264 (goto-char beg)
17265 (setq end (condition-case nil (org-end-of-subtree t) (error (point-max))))
17266 (goto-char end)
17267 ;; Walk the tree from the back and do the computations
17268 (while (re-search-backward re beg t)
17269 (setq sumpos (match-beginning 0)
17270 last-level level
17271 level (org-outline-level)
17272 val (org-entry-get nil property)
17273 valflag (and val (string-match "\\S-" val)))
17274 (cond
17275 ((< level last-level)
17276 ;; put the sum of lower levels here as a property
17277 (setq sum (aref lsum last-level) ; current sum
17278 flag (aref lflag last-level) ; any valid entries from children?
17279 str (org-column-number-to-string sum format printf)
17280 str1 (org-add-props (copy-sequence str) nil 'org-computed t 'face 'bold)
17281 useval (if flag str1 (if valflag val ""))
17282 sum-alist (get-text-property sumpos 'org-summaries))
17283 (if (assoc property sum-alist)
17284 (setcdr (assoc property sum-alist) useval)
17285 (push (cons property useval) sum-alist)
17286 (org-unmodified
17287 (add-text-properties sumpos (1+ sumpos)
17288 (list 'org-summaries sum-alist))))
17289 (when val
17290 (org-entry-put nil property (if flag str val)))
17291 ;; add current to current level accumulator
17292 (when (or flag valflag)
17293 (aset lsum level (+ (aref lsum level)
17294 (if flag sum (org-column-string-to-number
17295 (if flag str val) format))))
17296 (aset lflag level t))
17297 ;; clear accumulators for deeper levels
17298 (loop for l from (1+ level) to (1- lmax) do
17299 (aset lsum l 0)
17300 (aset lflag l nil)))
17301 ((>= level last-level)
17302 ;; add what we have here to the accumulator for this level
17303 (aset lsum level (+ (aref lsum level)
17304 (org-column-string-to-number (or val "0") format)))
17305 (and valflag (aset lflag level t)))
17306 (t (error "This should not happen")))))))
17308 (defun org-columns-redo ()
17309 "Construct the column display again."
17310 (interactive)
17311 (message "Recomputing columns...")
17312 (save-excursion
17313 (if (marker-position org-columns-begin-marker)
17314 (goto-char org-columns-begin-marker))
17315 (org-columns-remove-overlays)
17316 (if (org-mode-p)
17317 (call-interactively 'org-columns)
17318 (call-interactively 'org-agenda-columns)))
17319 (message "Recomputing columns...done"))
17321 (defun org-columns-not-in-agenda ()
17322 (if (eq major-mode 'org-agenda-mode)
17323 (error "This command is only allowed in Org-mode buffers")))
17326 (defun org-string-to-number (s)
17327 "Convert string to number, and interpret hh:mm:ss."
17328 (if (not (string-match ":" s))
17329 (string-to-number s)
17330 (let ((l (nreverse (org-split-string s ":"))) (sum 0.0))
17331 (while l
17332 (setq sum (+ (string-to-number (pop l)) (/ sum 60))))
17333 sum)))
17335 (defun org-column-number-to-string (n fmt &optional printf)
17336 "Convert a computed column number to a string value, according to FMT."
17337 (cond
17338 ((eq fmt 'add_times)
17339 (let* ((h (floor n)) (m (floor (+ 0.5 (* 60 (- n h))))))
17340 (format "%d:%02d" h m)))
17341 ((eq fmt 'checkbox)
17342 (cond ((= n (floor n)) "[X]")
17343 ((> n 1.) "[-]")
17344 (t "[ ]")))
17345 ((memq fmt '(checkbox-n-of-m checkbox-percent))
17346 (let* ((n1 (floor n)) (n2 (floor (+ .5 (* 1000000 (- n n1))))))
17347 (org-nofm-to-completion n1 (+ n2 n1) (eq fmt 'checkbox-percent))))
17348 (printf (format printf n))
17349 ((eq fmt 'currency)
17350 (format "%.2f" n))
17351 (t (number-to-string n))))
17353 (defun org-nofm-to-completion (n m &optional percent)
17354 (if (not percent)
17355 (format "[%d/%d]" n m)
17356 (format "[%d%%]"(floor (+ 0.5 (* 100. (/ (* 1.0 n) m)))))))
17358 (defun org-column-string-to-number (s fmt)
17359 "Convert a column value to a number that can be used for column computing."
17360 (cond
17361 ((string-match ":" s)
17362 (let ((l (nreverse (org-split-string s ":"))) (sum 0.0))
17363 (while l
17364 (setq sum (+ (string-to-number (pop l)) (/ sum 60))))
17365 sum))
17366 ((memq fmt '(checkbox checkbox-n-of-m checkbox-percent))
17367 (if (equal s "[X]") 1. 0.000001))
17368 (t (string-to-number s))))
17370 (defun org-columns-uncompile-format (cfmt)
17371 "Turn the compiled columns format back into a string representation."
17372 (let ((rtn "") e s prop title op width fmt printf)
17373 (while (setq e (pop cfmt))
17374 (setq prop (car e)
17375 title (nth 1 e)
17376 width (nth 2 e)
17377 op (nth 3 e)
17378 fmt (nth 4 e)
17379 printf (nth 5 e))
17380 (cond
17381 ((eq fmt 'add_times) (setq op ":"))
17382 ((eq fmt 'checkbox) (setq op "X"))
17383 ((eq fmt 'checkbox-n-of-m) (setq op "X/"))
17384 ((eq fmt 'checkbox-percent) (setq op "X%"))
17385 ((eq fmt 'add_numbers) (setq op "+"))
17386 ((eq fmt 'currency) (setq op "$")))
17387 (if (and op printf) (setq op (concat op ";" printf)))
17388 (if (equal title prop) (setq title nil))
17389 (setq s (concat "%" (if width (number-to-string width))
17390 prop
17391 (if title (concat "(" title ")"))
17392 (if op (concat "{" op "}"))))
17393 (setq rtn (concat rtn " " s)))
17394 (org-trim rtn)))
17396 (defun org-columns-compile-format (fmt)
17397 "Turn a column format string into an alist of specifications.
17398 The alist has one entry for each column in the format. The elements of
17399 that list are:
17400 property the property
17401 title the title field for the columns
17402 width the column width in characters, can be nil for automatic
17403 operator the operator if any
17404 format the output format for computed results, derived from operator
17405 printf a printf format for computed values"
17406 (let ((start 0) width prop title op f printf)
17407 (setq org-columns-current-fmt-compiled nil)
17408 (while (string-match
17409 (org-re "%\\([0-9]+\\)?\\([[:alnum:]_-]+\\)\\(?:(\\([^)]+\\))\\)?\\(?:{\\([^}]+\\)}\\)?\\s-*")
17410 fmt start)
17411 (setq start (match-end 0)
17412 width (match-string 1 fmt)
17413 prop (match-string 2 fmt)
17414 title (or (match-string 3 fmt) prop)
17415 op (match-string 4 fmt)
17416 f nil
17417 printf nil)
17418 (if width (setq width (string-to-number width)))
17419 (when (and op (string-match ";" op))
17420 (setq printf (substring op (match-end 0))
17421 op (substring op 0 (match-beginning 0))))
17422 (cond
17423 ((equal op "+") (setq f 'add_numbers))
17424 ((equal op "$") (setq f 'currency))
17425 ((equal op ":") (setq f 'add_times))
17426 ((equal op "X") (setq f 'checkbox))
17427 ((equal op "X/") (setq f 'checkbox-n-of-m))
17428 ((equal op "X%") (setq f 'checkbox-percent))
17430 (push (list prop title width op f printf) org-columns-current-fmt-compiled))
17431 (setq org-columns-current-fmt-compiled
17432 (nreverse org-columns-current-fmt-compiled))))
17435 ;;; Dynamic block for Column view
17437 (defun org-columns-capture-view ()
17438 "Get the column view of the current buffer and return it as a list.
17439 The list will contains the title row and all other rows. Each row is
17440 a list of fields."
17441 (save-excursion
17442 (let* ((title (mapcar 'cadr org-columns-current-fmt-compiled))
17443 (n (length title)) row tbl)
17444 (goto-char (point-min))
17445 (while (re-search-forward "^\\*+ " nil t)
17446 (when (get-char-property (match-beginning 0) 'org-columns-key)
17447 (setq row nil)
17448 (loop for i from 0 to (1- n) do
17449 (push (or (get-char-property (+ (match-beginning 0) i) 'org-columns-value-modified)
17450 (get-char-property (+ (match-beginning 0) i) 'org-columns-value)
17452 row))
17453 (setq row (nreverse row))
17454 (push row tbl)))
17455 (append (list title 'hline) (nreverse tbl)))))
17457 (defun org-dblock-write:columnview (params)
17458 "Write the column view table.
17459 PARAMS is a property list of parameters:
17461 :width enforce same column widths with <N> specifiers.
17462 :id the :ID: property of the entry where the columns view
17463 should be built, as a string. When `local', call locally.
17464 When `global' call column view with the cursor at the beginning
17465 of the buffer (usually this means that the whole buffer switches
17466 to column view).
17467 :hlines When t, insert a hline before each item. When a number, insert
17468 a hline before each level <= that number.
17469 :vlines When t, make each column a colgroup to enforce vertical lines."
17470 (let ((pos (move-marker (make-marker) (point)))
17471 (hlines (plist-get params :hlines))
17472 (vlines (plist-get params :vlines))
17473 tbl id idpos nfields tmp)
17474 (save-excursion
17475 (save-restriction
17476 (when (setq id (plist-get params :id))
17477 (cond ((not id) nil)
17478 ((eq id 'global) (goto-char (point-min)))
17479 ((eq id 'local) nil)
17480 ((setq idpos (org-find-entry-with-id id))
17481 (goto-char idpos))
17482 (t (error "Cannot find entry with :ID: %s" id))))
17483 (org-columns)
17484 (setq tbl (org-columns-capture-view))
17485 (setq nfields (length (car tbl)))
17486 (org-columns-quit)))
17487 (goto-char pos)
17488 (move-marker pos nil)
17489 (when tbl
17490 (when (plist-get params :hlines)
17491 (setq tmp nil)
17492 (while tbl
17493 (if (eq (car tbl) 'hline)
17494 (push (pop tbl) tmp)
17495 (if (string-match "\\` *\\(\\*+\\)" (caar tbl))
17496 (if (and (not (eq (car tmp) 'hline))
17497 (or (eq hlines t)
17498 (and (numberp hlines) (<= (- (match-end 1) (match-beginning 1)) hlines))))
17499 (push 'hline tmp)))
17500 (push (pop tbl) tmp)))
17501 (setq tbl (nreverse tmp)))
17502 (when vlines
17503 (setq tbl (mapcar (lambda (x)
17504 (if (eq 'hline x) x (cons "" x)))
17505 tbl))
17506 (setq tbl (append tbl (list (cons "/" (make-list nfields "<>"))))))
17507 (setq pos (point))
17508 (insert (org-listtable-to-string tbl))
17509 (when (plist-get params :width)
17510 (insert "\n|" (mapconcat (lambda (x) (format "<%d>" (max 3 x)))
17511 org-columns-current-widths "|")))
17512 (goto-char pos)
17513 (org-table-align))))
17515 (defun org-listtable-to-string (tbl)
17516 "Convert a listtable TBL to a string that contains the Org-mode table.
17517 The table still need to be alligned. The resulting string has no leading
17518 and tailing newline characters."
17519 (mapconcat
17520 (lambda (x)
17521 (cond
17522 ((listp x)
17523 (concat "|" (mapconcat 'identity x "|") "|"))
17524 ((eq x 'hline) "|-|")
17525 (t (error "Garbage in listtable: %s" x))))
17526 tbl "\n"))
17528 (defun org-insert-columns-dblock ()
17529 "Create a dynamic block capturing a column view table."
17530 (interactive)
17531 (let ((defaults '(:name "columnview" :hlines 1))
17532 (id (completing-read
17533 "Capture columns (local, global, entry with :ID: property) [local]: "
17534 (append '(("global") ("local"))
17535 (mapcar 'list (org-property-values "ID"))))))
17536 (if (equal id "") (setq id 'local))
17537 (if (equal id "global") (setq id 'global))
17538 (setq defaults (append defaults (list :id id)))
17539 (org-create-dblock defaults)
17540 (org-update-dblock)))
17542 ;;;; Timestamps
17544 (defvar org-last-changed-timestamp nil)
17545 (defvar org-time-was-given) ; dynamically scoped parameter
17546 (defvar org-end-time-was-given) ; dynamically scoped parameter
17547 (defvar org-ts-what) ; dynamically scoped parameter
17549 (defun org-time-stamp (arg)
17550 "Prompt for a date/time and insert a time stamp.
17551 If the user specifies a time like HH:MM, or if this command is called
17552 with a prefix argument, the time stamp will contain date and time.
17553 Otherwise, only the date will be included. All parts of a date not
17554 specified by the user will be filled in from the current date/time.
17555 So if you press just return without typing anything, the time stamp
17556 will represent the current date/time. If there is already a timestamp
17557 at the cursor, it will be modified."
17558 (interactive "P")
17559 (let* ((ts nil)
17560 (default-time
17561 ;; Default time is either today, or, when entering a range,
17562 ;; the range start.
17563 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
17564 (save-excursion
17565 (re-search-backward
17566 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
17567 (- (point) 20) t)))
17568 (apply 'encode-time (org-parse-time-string (match-string 1)))
17569 (current-time)))
17570 (default-input (and ts (org-get-compact-tod ts)))
17571 org-time-was-given org-end-time-was-given time)
17572 (cond
17573 ((and (org-at-timestamp-p)
17574 (eq last-command 'org-time-stamp)
17575 (eq this-command 'org-time-stamp))
17576 (insert "--")
17577 (setq time (let ((this-command this-command))
17578 (org-read-date arg 'totime nil nil default-time default-input)))
17579 (org-insert-time-stamp time (or org-time-was-given arg)))
17580 ((org-at-timestamp-p)
17581 (setq time (let ((this-command this-command))
17582 (org-read-date arg 'totime nil nil default-time default-input)))
17583 (when (org-at-timestamp-p) ; just to get the match data
17584 (replace-match "")
17585 (setq org-last-changed-timestamp
17586 (org-insert-time-stamp
17587 time (or org-time-was-given arg)
17588 nil nil nil (list org-end-time-was-given))))
17589 (message "Timestamp updated"))
17591 (setq time (let ((this-command this-command))
17592 (org-read-date arg 'totime nil nil default-time default-input)))
17593 (org-insert-time-stamp time (or org-time-was-given arg)
17594 nil nil nil (list org-end-time-was-given))))))
17596 ;; FIXME: can we use this for something else????
17597 ;; like computing time differences?????
17598 (defun org-get-compact-tod (s)
17599 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
17600 (let* ((t1 (match-string 1 s))
17601 (h1 (string-to-number (match-string 2 s)))
17602 (m1 (string-to-number (match-string 3 s)))
17603 (t2 (and (match-end 4) (match-string 5 s)))
17604 (h2 (and t2 (string-to-number (match-string 6 s))))
17605 (m2 (and t2 (string-to-number (match-string 7 s))))
17606 dh dm)
17607 (if (not t2)
17609 (setq dh (- h2 h1) dm (- m2 m1))
17610 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
17611 (concat t1 "+" (number-to-string dh)
17612 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
17614 (defun org-time-stamp-inactive (&optional arg)
17615 "Insert an inactive time stamp.
17616 An inactive time stamp is enclosed in square brackets instead of angle
17617 brackets. It is inactive in the sense that it does not trigger agenda entries,
17618 does not link to the calendar and cannot be changed with the S-cursor keys.
17619 So these are more for recording a certain time/date."
17620 (interactive "P")
17621 (let (org-time-was-given org-end-time-was-given time)
17622 (setq time (org-read-date arg 'totime))
17623 (org-insert-time-stamp time (or org-time-was-given arg) 'inactive
17624 nil nil (list org-end-time-was-given))))
17626 (defvar org-date-ovl (org-make-overlay 1 1))
17627 (org-overlay-put org-date-ovl 'face 'org-warning)
17628 (org-detach-overlay org-date-ovl)
17630 (defvar org-ans1) ; dynamically scoped parameter
17631 (defvar org-ans2) ; dynamically scoped parameter
17633 (defvar org-plain-time-of-day-regexp) ; defined below
17635 (defvar org-read-date-overlay nil)
17636 (defvar org-dcst nil) ; dynamically scoped
17638 (defun org-read-date (&optional with-time to-time from-string prompt
17639 default-time default-input)
17640 "Read a date, possibly a time, and make things smooth for the user.
17641 The prompt will suggest to enter an ISO date, but you can also enter anything
17642 which will at least partially be understood by `parse-time-string'.
17643 Unrecognized parts of the date will default to the current day, month, year,
17644 hour and minute. If this command is called to replace a timestamp at point,
17645 of to enter the second timestamp of a range, the default time is taken from the
17646 existing stamp. For example,
17647 3-2-5 --> 2003-02-05
17648 feb 15 --> currentyear-02-15
17649 sep 12 9 --> 2009-09-12
17650 12:45 --> today 12:45
17651 22 sept 0:34 --> currentyear-09-22 0:34
17652 12 --> currentyear-currentmonth-12
17653 Fri --> nearest Friday (today or later)
17654 etc.
17656 Furthermore you can specify a relative date by giving, as the *first* thing
17657 in the input: a plus/minus sign, a number and a letter [dwmy] to indicate
17658 change in days weeks, months, years.
17659 With a single plus or minus, the date is relative to today. With a double
17660 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
17661 +4d --> four days from today
17662 +4 --> same as above
17663 +2w --> two weeks from today
17664 ++5 --> five days from default date
17666 The function understands only English month and weekday abbreviations,
17667 but this can be configured with the variables `parse-time-months' and
17668 `parse-time-weekdays'.
17670 While prompting, a calendar is popped up - you can also select the
17671 date with the mouse (button 1). The calendar shows a period of three
17672 months. To scroll it to other months, use the keys `>' and `<'.
17673 If you don't like the calendar, turn it off with
17674 \(setq org-read-date-popup-calendar nil)
17676 With optional argument TO-TIME, the date will immediately be converted
17677 to an internal time.
17678 With an optional argument WITH-TIME, the prompt will suggest to also
17679 insert a time. Note that when WITH-TIME is not set, you can still
17680 enter a time, and this function will inform the calling routine about
17681 this change. The calling routine may then choose to change the format
17682 used to insert the time stamp into the buffer to include the time.
17683 With optional argument FROM-STRING, read from this string instead from
17684 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
17685 the time/date that is used for everything that is not specified by the
17686 user."
17687 (require 'parse-time)
17688 (let* ((org-time-stamp-rounding-minutes
17689 (if (equal with-time '(16)) 0 org-time-stamp-rounding-minutes))
17690 (org-dcst org-display-custom-times)
17691 (ct (org-current-time))
17692 (def (or default-time ct))
17693 (defdecode (decode-time def))
17694 (dummy (progn
17695 (when (< (nth 2 defdecode) org-extend-today-until)
17696 (setcar (nthcdr 2 defdecode) -1)
17697 (setcar (nthcdr 1 defdecode) 59)
17698 (setq def (apply 'encode-time defdecode)
17699 defdecode (decode-time def)))))
17700 (calendar-move-hook nil)
17701 (view-diary-entries-initially nil)
17702 (view-calendar-holidays-initially nil)
17703 (timestr (format-time-string
17704 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") def))
17705 (prompt (concat (if prompt (concat prompt " ") "")
17706 (format "Date+time [%s]: " timestr)))
17707 ans (org-ans0 "") org-ans1 org-ans2 final)
17709 (cond
17710 (from-string (setq ans from-string))
17711 (org-read-date-popup-calendar
17712 (save-excursion
17713 (save-window-excursion
17714 (calendar)
17715 (calendar-forward-day (- (time-to-days def)
17716 (calendar-absolute-from-gregorian
17717 (calendar-current-date))))
17718 (org-eval-in-calendar nil t)
17719 (let* ((old-map (current-local-map))
17720 (map (copy-keymap calendar-mode-map))
17721 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
17722 (org-defkey map (kbd "RET") 'org-calendar-select)
17723 (org-defkey map (if (featurep 'xemacs) [button1] [mouse-1])
17724 'org-calendar-select-mouse)
17725 (org-defkey map (if (featurep 'xemacs) [button2] [mouse-2])
17726 'org-calendar-select-mouse)
17727 (org-defkey minibuffer-local-map [(meta shift left)]
17728 (lambda () (interactive)
17729 (org-eval-in-calendar '(calendar-backward-month 1))))
17730 (org-defkey minibuffer-local-map [(meta shift right)]
17731 (lambda () (interactive)
17732 (org-eval-in-calendar '(calendar-forward-month 1))))
17733 (org-defkey minibuffer-local-map [(meta shift up)]
17734 (lambda () (interactive)
17735 (org-eval-in-calendar '(calendar-backward-year 1))))
17736 (org-defkey minibuffer-local-map [(meta shift down)]
17737 (lambda () (interactive)
17738 (org-eval-in-calendar '(calendar-forward-year 1))))
17739 (org-defkey minibuffer-local-map [(shift up)]
17740 (lambda () (interactive)
17741 (org-eval-in-calendar '(calendar-backward-week 1))))
17742 (org-defkey minibuffer-local-map [(shift down)]
17743 (lambda () (interactive)
17744 (org-eval-in-calendar '(calendar-forward-week 1))))
17745 (org-defkey minibuffer-local-map [(shift left)]
17746 (lambda () (interactive)
17747 (org-eval-in-calendar '(calendar-backward-day 1))))
17748 (org-defkey minibuffer-local-map [(shift right)]
17749 (lambda () (interactive)
17750 (org-eval-in-calendar '(calendar-forward-day 1))))
17751 (org-defkey minibuffer-local-map ">"
17752 (lambda () (interactive)
17753 (org-eval-in-calendar '(scroll-calendar-left 1))))
17754 (org-defkey minibuffer-local-map "<"
17755 (lambda () (interactive)
17756 (org-eval-in-calendar '(scroll-calendar-right 1))))
17757 (unwind-protect
17758 (progn
17759 (use-local-map map)
17760 (add-hook 'post-command-hook 'org-read-date-display)
17761 (setq org-ans0 (read-string prompt default-input nil nil))
17762 ;; org-ans0: from prompt
17763 ;; org-ans1: from mouse click
17764 ;; org-ans2: from calendar motion
17765 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
17766 (remove-hook 'post-command-hook 'org-read-date-display)
17767 (use-local-map old-map)
17768 (when org-read-date-overlay
17769 (org-delete-overlay org-read-date-overlay)
17770 (setq org-read-date-overlay nil)))))))
17772 (t ; Naked prompt only
17773 (unwind-protect
17774 (setq ans (read-string prompt default-input nil timestr))
17775 (when org-read-date-overlay
17776 (org-delete-overlay org-read-date-overlay)
17777 (setq org-read-date-overlay nil)))))
17779 (setq final (org-read-date-analyze ans def defdecode))
17781 (if to-time
17782 (apply 'encode-time final)
17783 (if (and (boundp 'org-time-was-given) org-time-was-given)
17784 (format "%04d-%02d-%02d %02d:%02d"
17785 (nth 5 final) (nth 4 final) (nth 3 final)
17786 (nth 2 final) (nth 1 final))
17787 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
17788 (defvar def)
17789 (defvar defdecode)
17790 (defvar with-time)
17791 (defun org-read-date-display ()
17792 "Display the currrent date prompt interpretation in the minibuffer."
17793 (when org-read-date-display-live
17794 (when org-read-date-overlay
17795 (org-delete-overlay org-read-date-overlay))
17796 (let ((p (point)))
17797 (end-of-line 1)
17798 (while (not (equal (buffer-substring
17799 (max (point-min) (- (point) 4)) (point))
17800 " "))
17801 (insert " "))
17802 (goto-char p))
17803 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
17804 " " (or org-ans1 org-ans2)))
17805 (org-end-time-was-given nil)
17806 (f (org-read-date-analyze ans def defdecode))
17807 (fmts (if org-dcst
17808 org-time-stamp-custom-formats
17809 org-time-stamp-formats))
17810 (fmt (if (or with-time
17811 (and (boundp 'org-time-was-given) org-time-was-given))
17812 (cdr fmts)
17813 (car fmts)))
17814 (txt (concat "=> " (format-time-string fmt (apply 'encode-time f)))))
17815 (when (and org-end-time-was-given
17816 (string-match org-plain-time-of-day-regexp txt))
17817 (setq txt (concat (substring txt 0 (match-end 0)) "-"
17818 org-end-time-was-given
17819 (substring txt (match-end 0)))))
17820 (setq org-read-date-overlay
17821 (make-overlay (1- (point-at-eol)) (point-at-eol)))
17822 (org-overlay-display org-read-date-overlay txt 'secondary-selection))))
17824 (defun org-read-date-analyze (ans def defdecode)
17825 "Analyze the combined answer of the date prompt."
17826 ;; FIXME: cleanup and comment
17827 (let (delta deltan deltaw deltadef year month day
17828 hour minute second wday pm h2 m2 tl wday1)
17830 (when (setq delta (org-read-date-get-relative ans (current-time) def))
17831 (setq ans (replace-match "" t t ans)
17832 deltan (car delta)
17833 deltaw (nth 1 delta)
17834 deltadef (nth 2 delta)))
17836 ;; Help matching ISO dates with single digit month ot day, like 2006-8-11.
17837 (when (string-match
17838 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
17839 (setq year (if (match-end 2)
17840 (string-to-number (match-string 2 ans))
17841 (string-to-number (format-time-string "%Y")))
17842 month (string-to-number (match-string 3 ans))
17843 day (string-to-number (match-string 4 ans)))
17844 (if (< year 100) (setq year (+ 2000 year)))
17845 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
17846 t nil ans)))
17847 ;; Help matching am/pm times, because `parse-time-string' does not do that.
17848 ;; If there is a time with am/pm, and *no* time without it, we convert
17849 ;; so that matching will be successful.
17850 (loop for i from 1 to 2 do ; twice, for end time as well
17851 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
17852 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
17853 (setq hour (string-to-number (match-string 1 ans))
17854 minute (if (match-end 3)
17855 (string-to-number (match-string 3 ans))
17857 pm (equal ?p
17858 (string-to-char (downcase (match-string 4 ans)))))
17859 (if (and (= hour 12) (not pm))
17860 (setq hour 0)
17861 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
17862 (setq ans (replace-match (format "%02d:%02d" hour minute)
17863 t t ans))))
17865 ;; Check if a time range is given as a duration
17866 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
17867 (setq hour (string-to-number (match-string 1 ans))
17868 h2 (+ hour (string-to-number (match-string 3 ans)))
17869 minute (string-to-number (match-string 2 ans))
17870 m2 (+ minute (if (match-end 5) (string-to-number (match-string 5 ans))0)))
17871 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
17872 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2) t t ans)))
17874 ;; Check if there is a time range
17875 (when (boundp 'org-end-time-was-given)
17876 (setq org-time-was-given nil)
17877 (when (and (string-match org-plain-time-of-day-regexp ans)
17878 (match-end 8))
17879 (setq org-end-time-was-given (match-string 8 ans))
17880 (setq ans (concat (substring ans 0 (match-beginning 7))
17881 (substring ans (match-end 7))))))
17883 (setq tl (parse-time-string ans)
17884 day (or (nth 3 tl) (nth 3 defdecode))
17885 month (or (nth 4 tl)
17886 (if (and org-read-date-prefer-future
17887 (nth 3 tl) (< (nth 3 tl) (nth 3 defdecode)))
17888 (1+ (nth 4 defdecode))
17889 (nth 4 defdecode)))
17890 year (or (nth 5 tl)
17891 (if (and org-read-date-prefer-future
17892 (nth 4 tl) (< (nth 4 tl) (nth 4 defdecode)))
17893 (1+ (nth 5 defdecode))
17894 (nth 5 defdecode)))
17895 hour (or (nth 2 tl) (nth 2 defdecode))
17896 minute (or (nth 1 tl) (nth 1 defdecode))
17897 second (or (nth 0 tl) 0)
17898 wday (nth 6 tl))
17899 (when deltan
17900 (unless deltadef
17901 (let ((now (decode-time (current-time))))
17902 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
17903 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
17904 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
17905 ((equal deltaw "m") (setq month (+ month deltan)))
17906 ((equal deltaw "y") (setq year (+ year deltan)))))
17907 (when (and wday (not (nth 3 tl)))
17908 ;; Weekday was given, but no day, so pick that day in the week
17909 ;; on or after the derived date.
17910 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
17911 (unless (equal wday wday1)
17912 (setq day (+ day (% (- wday wday1 -7) 7)))))
17913 (if (and (boundp 'org-time-was-given)
17914 (nth 2 tl))
17915 (setq org-time-was-given t))
17916 (if (< year 100) (setq year (+ 2000 year)))
17917 (if (< year 1970) (setq year (nth 5 defdecode))) ; not representable
17918 (list second minute hour day month year)))
17920 (defvar parse-time-weekdays)
17922 (defun org-read-date-get-relative (s today default)
17923 "Check string S for special relative date string.
17924 TODAY and DEFAULT are internal times, for today and for a default.
17925 Return shift list (N what def-flag)
17926 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
17927 N is the number of WHATs to shift.
17928 DEF-FLAG is t when a double ++ or -- indicates shift relative to
17929 the DEFAULT date rather than TODAY."
17930 (when (string-match
17931 (concat
17932 "\\`[ \t]*\\([-+]\\{1,2\\}\\)"
17933 "\\([0-9]+\\)?"
17934 "\\([dwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
17935 "\\([ \t]\\|$\\)") s)
17936 (let* ((dir (if (match-end 1)
17937 (string-to-char (substring (match-string 1 s) -1))
17938 ?+))
17939 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
17940 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
17941 (what (if (match-end 3) (match-string 3 s) "d"))
17942 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
17943 (date (if rel default today))
17944 (wday (nth 6 (decode-time date)))
17945 delta)
17946 (if wday1
17947 (progn
17948 (setq delta (mod (+ 7 (- wday1 wday)) 7))
17949 (if (= dir ?-) (setq delta (- delta 7)))
17950 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
17951 (list delta "d" rel))
17952 (list (* n (if (= dir ?-) -1 1)) what rel)))))
17954 (defun org-eval-in-calendar (form &optional keepdate)
17955 "Eval FORM in the calendar window and return to current window.
17956 Also, store the cursor date in variable org-ans2."
17957 (let ((sw (selected-window)))
17958 (select-window (get-buffer-window "*Calendar*"))
17959 (eval form)
17960 (when (and (not keepdate) (calendar-cursor-to-date))
17961 (let* ((date (calendar-cursor-to-date))
17962 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17963 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
17964 (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
17965 (select-window sw)))
17967 ; ;; Update the prompt to show new default date
17968 ; (save-excursion
17969 ; (goto-char (point-min))
17970 ; (when (and org-ans2
17971 ; (re-search-forward "\\[[-0-9]+\\]" nil t)
17972 ; (get-text-property (match-end 0) 'field))
17973 ; (let ((inhibit-read-only t))
17974 ; (replace-match (concat "[" org-ans2 "]") t t)
17975 ; (add-text-properties (point-min) (1+ (match-end 0))
17976 ; (text-properties-at (1+ (point-min)))))))))
17978 (defun org-calendar-select ()
17979 "Return to `org-read-date' with the date currently selected.
17980 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
17981 (interactive)
17982 (when (calendar-cursor-to-date)
17983 (let* ((date (calendar-cursor-to-date))
17984 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17985 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
17986 (if (active-minibuffer-window) (exit-minibuffer))))
17988 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
17989 "Insert a date stamp for the date given by the internal TIME.
17990 WITH-HM means, use the stamp format that includes the time of the day.
17991 INACTIVE means use square brackets instead of angular ones, so that the
17992 stamp will not contribute to the agenda.
17993 PRE and POST are optional strings to be inserted before and after the
17994 stamp.
17995 The command returns the inserted time stamp."
17996 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
17997 stamp)
17998 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
17999 (insert-before-markers (or pre ""))
18000 (insert-before-markers (setq stamp (format-time-string fmt time)))
18001 (when (listp extra)
18002 (setq extra (car extra))
18003 (if (and (stringp extra)
18004 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
18005 (setq extra (format "-%02d:%02d"
18006 (string-to-number (match-string 1 extra))
18007 (string-to-number (match-string 2 extra))))
18008 (setq extra nil)))
18009 (when extra
18010 (backward-char 1)
18011 (insert-before-markers extra)
18012 (forward-char 1))
18013 (insert-before-markers (or post ""))
18014 stamp))
18016 (defun org-toggle-time-stamp-overlays ()
18017 "Toggle the use of custom time stamp formats."
18018 (interactive)
18019 (setq org-display-custom-times (not org-display-custom-times))
18020 (unless org-display-custom-times
18021 (let ((p (point-min)) (bmp (buffer-modified-p)))
18022 (while (setq p (next-single-property-change p 'display))
18023 (if (and (get-text-property p 'display)
18024 (eq (get-text-property p 'face) 'org-date))
18025 (remove-text-properties
18026 p (setq p (next-single-property-change p 'display))
18027 '(display t))))
18028 (set-buffer-modified-p bmp)))
18029 (if (featurep 'xemacs)
18030 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
18031 (org-restart-font-lock)
18032 (setq org-table-may-need-update t)
18033 (if org-display-custom-times
18034 (message "Time stamps are overlayed with custom format")
18035 (message "Time stamp overlays removed")))
18037 (defun org-display-custom-time (beg end)
18038 "Overlay modified time stamp format over timestamp between BED and END."
18039 (let* ((ts (buffer-substring beg end))
18040 t1 w1 with-hm tf time str w2 (off 0))
18041 (save-match-data
18042 (setq t1 (org-parse-time-string ts t))
18043 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( \\+[0-9]+[dwmy]\\)?\\'" ts)
18044 (setq off (- (match-end 0) (match-beginning 0)))))
18045 (setq end (- end off))
18046 (setq w1 (- end beg)
18047 with-hm (and (nth 1 t1) (nth 2 t1))
18048 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
18049 time (org-fix-decoded-time t1)
18050 str (org-add-props
18051 (format-time-string
18052 (substring tf 1 -1) (apply 'encode-time time))
18053 nil 'mouse-face 'highlight)
18054 w2 (length str))
18055 (if (not (= w2 w1))
18056 (add-text-properties (1+ beg) (+ 2 beg)
18057 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
18058 (if (featurep 'xemacs)
18059 (progn
18060 (put-text-property beg end 'invisible t)
18061 (put-text-property beg end 'end-glyph (make-glyph str)))
18062 (put-text-property beg end 'display str))))
18064 (defun org-translate-time (string)
18065 "Translate all timestamps in STRING to custom format.
18066 But do this only if the variable `org-display-custom-times' is set."
18067 (when org-display-custom-times
18068 (save-match-data
18069 (let* ((start 0)
18070 (re org-ts-regexp-both)
18071 t1 with-hm inactive tf time str beg end)
18072 (while (setq start (string-match re string start))
18073 (setq beg (match-beginning 0)
18074 end (match-end 0)
18075 t1 (save-match-data
18076 (org-parse-time-string (substring string beg end) t))
18077 with-hm (and (nth 1 t1) (nth 2 t1))
18078 inactive (equal (substring string beg (1+ beg)) "[")
18079 tf (funcall (if with-hm 'cdr 'car)
18080 org-time-stamp-custom-formats)
18081 time (org-fix-decoded-time t1)
18082 str (format-time-string
18083 (concat
18084 (if inactive "[" "<") (substring tf 1 -1)
18085 (if inactive "]" ">"))
18086 (apply 'encode-time time))
18087 string (replace-match str t t string)
18088 start (+ start (length str)))))))
18089 string)
18091 (defun org-fix-decoded-time (time)
18092 "Set 0 instead of nil for the first 6 elements of time.
18093 Don't touch the rest."
18094 (let ((n 0))
18095 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
18097 (defun org-days-to-time (timestamp-string)
18098 "Difference between TIMESTAMP-STRING and now in days."
18099 (- (time-to-days (org-time-string-to-time timestamp-string))
18100 (time-to-days (current-time))))
18102 (defun org-deadline-close (timestamp-string &optional ndays)
18103 "Is the time in TIMESTAMP-STRING close to the current date?"
18104 (setq ndays (or ndays (org-get-wdays timestamp-string)))
18105 (and (< (org-days-to-time timestamp-string) ndays)
18106 (not (org-entry-is-done-p))))
18108 (defun org-get-wdays (ts)
18109 "Get the deadline lead time appropriate for timestring TS."
18110 (cond
18111 ((<= org-deadline-warning-days 0)
18112 ;; 0 or negative, enforce this value no matter what
18113 (- org-deadline-warning-days))
18114 ((string-match "-\\([0-9]+\\)\\([dwmy]\\)\\(\\'\\|>\\)" ts)
18115 ;; lead time is specified.
18116 (floor (* (string-to-number (match-string 1 ts))
18117 (cdr (assoc (match-string 2 ts)
18118 '(("d" . 1) ("w" . 7)
18119 ("m" . 30.4) ("y" . 365.25)))))))
18120 ;; go for the default.
18121 (t org-deadline-warning-days)))
18123 (defun org-calendar-select-mouse (ev)
18124 "Return to `org-read-date' with the date currently selected.
18125 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
18126 (interactive "e")
18127 (mouse-set-point ev)
18128 (when (calendar-cursor-to-date)
18129 (let* ((date (calendar-cursor-to-date))
18130 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
18131 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
18132 (if (active-minibuffer-window) (exit-minibuffer))))
18134 (defun org-check-deadlines (ndays)
18135 "Check if there are any deadlines due or past due.
18136 A deadline is considered due if it happens within `org-deadline-warning-days'
18137 days from today's date. If the deadline appears in an entry marked DONE,
18138 it is not shown. The prefix arg NDAYS can be used to test that many
18139 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
18140 (interactive "P")
18141 (let* ((org-warn-days
18142 (cond
18143 ((equal ndays '(4)) 100000)
18144 (ndays (prefix-numeric-value ndays))
18145 (t (abs org-deadline-warning-days))))
18146 (case-fold-search nil)
18147 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
18148 (callback
18149 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
18151 (message "%d deadlines past-due or due within %d days"
18152 (org-occur regexp nil callback)
18153 org-warn-days)))
18155 (defun org-check-before-date (date)
18156 "Check if there are deadlines or scheduled entries before DATE."
18157 (interactive (list (org-read-date)))
18158 (let ((case-fold-search nil)
18159 (regexp (concat "\\<\\(" org-deadline-string
18160 "\\|" org-scheduled-string
18161 "\\) *<\\([^>]+\\)>"))
18162 (callback
18163 (lambda () (time-less-p
18164 (org-time-string-to-time (match-string 2))
18165 (org-time-string-to-time date)))))
18166 (message "%d entries before %s"
18167 (org-occur regexp nil callback) date)))
18169 (defun org-evaluate-time-range (&optional to-buffer)
18170 "Evaluate a time range by computing the difference between start and end.
18171 Normally the result is just printed in the echo area, but with prefix arg
18172 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
18173 If the time range is actually in a table, the result is inserted into the
18174 next column.
18175 For time difference computation, a year is assumed to be exactly 365
18176 days in order to avoid rounding problems."
18177 (interactive "P")
18179 (org-clock-update-time-maybe)
18180 (save-excursion
18181 (unless (org-at-date-range-p t)
18182 (goto-char (point-at-bol))
18183 (re-search-forward org-tr-regexp-both (point-at-eol) t))
18184 (if (not (org-at-date-range-p t))
18185 (error "Not at a time-stamp range, and none found in current line")))
18186 (let* ((ts1 (match-string 1))
18187 (ts2 (match-string 2))
18188 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
18189 (match-end (match-end 0))
18190 (time1 (org-time-string-to-time ts1))
18191 (time2 (org-time-string-to-time ts2))
18192 (t1 (time-to-seconds time1))
18193 (t2 (time-to-seconds time2))
18194 (diff (abs (- t2 t1)))
18195 (negative (< (- t2 t1) 0))
18196 ;; (ys (floor (* 365 24 60 60)))
18197 (ds (* 24 60 60))
18198 (hs (* 60 60))
18199 (fy "%dy %dd %02d:%02d")
18200 (fy1 "%dy %dd")
18201 (fd "%dd %02d:%02d")
18202 (fd1 "%dd")
18203 (fh "%02d:%02d")
18204 y d h m align)
18205 (if havetime
18206 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
18208 d (floor (/ diff ds)) diff (mod diff ds)
18209 h (floor (/ diff hs)) diff (mod diff hs)
18210 m (floor (/ diff 60)))
18211 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
18213 d (floor (+ (/ diff ds) 0.5))
18214 h 0 m 0))
18215 (if (not to-buffer)
18216 (message "%s" (org-make-tdiff-string y d h m))
18217 (if (org-at-table-p)
18218 (progn
18219 (goto-char match-end)
18220 (setq align t)
18221 (and (looking-at " *|") (goto-char (match-end 0))))
18222 (goto-char match-end))
18223 (if (looking-at
18224 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
18225 (replace-match ""))
18226 (if negative (insert " -"))
18227 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
18228 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
18229 (insert " " (format fh h m))))
18230 (if align (org-table-align))
18231 (message "Time difference inserted")))))
18233 (defun org-make-tdiff-string (y d h m)
18234 (let ((fmt "")
18235 (l nil))
18236 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
18237 l (push y l)))
18238 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
18239 l (push d l)))
18240 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
18241 l (push h l)))
18242 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
18243 l (push m l)))
18244 (apply 'format fmt (nreverse l))))
18246 (defun org-time-string-to-time (s)
18247 (apply 'encode-time (org-parse-time-string s)))
18249 (defun org-time-string-to-absolute (s &optional daynr prefer)
18250 "Convert a time stamp to an absolute day number.
18251 If there is a specifyer for a cyclic time stamp, get the closest date to
18252 DAYNR."
18253 (cond
18254 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
18255 (if (org-diary-sexp-entry (match-string 1 s) "" date)
18256 daynr
18257 (+ daynr 1000)))
18258 ((and daynr (string-match "\\+[0-9]+[dwmy]" s))
18259 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
18260 (time-to-days (current-time))) (match-string 0 s)
18261 prefer))
18262 (t (time-to-days (apply 'encode-time (org-parse-time-string s))))))
18264 (defun org-time-from-absolute (d)
18265 "Return the time corresponding to date D.
18266 D may be an absolute day number, or a calendar-type list (month day year)."
18267 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
18268 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
18270 (defun org-calendar-holiday ()
18271 "List of holidays, for Diary display in Org-mode."
18272 (require 'holidays)
18273 (let ((hl (funcall
18274 (if (fboundp 'calendar-check-holidays)
18275 'calendar-check-holidays 'check-calendar-holidays) date)))
18276 (if hl (mapconcat 'identity hl "; "))))
18278 (defun org-diary-sexp-entry (sexp entry date)
18279 "Process a SEXP diary ENTRY for DATE."
18280 (require 'diary-lib)
18281 (let ((result (if calendar-debug-sexp
18282 (let ((stack-trace-on-error t))
18283 (eval (car (read-from-string sexp))))
18284 (condition-case nil
18285 (eval (car (read-from-string sexp)))
18286 (error
18287 (beep)
18288 (message "Bad sexp at line %d in %s: %s"
18289 (org-current-line)
18290 (buffer-file-name) sexp)
18291 (sleep-for 2))))))
18292 (cond ((stringp result) result)
18293 ((and (consp result)
18294 (stringp (cdr result))) (cdr result))
18295 (result entry)
18296 (t nil))))
18298 (defun org-diary-to-ical-string (frombuf)
18299 "Get iCalendar entries from diary entries in buffer FROMBUF.
18300 This uses the icalendar.el library."
18301 (let* ((tmpdir (if (featurep 'xemacs)
18302 (temp-directory)
18303 temporary-file-directory))
18304 (tmpfile (make-temp-name
18305 (expand-file-name "orgics" tmpdir)))
18306 buf rtn b e)
18307 (save-excursion
18308 (set-buffer frombuf)
18309 (icalendar-export-region (point-min) (point-max) tmpfile)
18310 (setq buf (find-buffer-visiting tmpfile))
18311 (set-buffer buf)
18312 (goto-char (point-min))
18313 (if (re-search-forward "^BEGIN:VEVENT" nil t)
18314 (setq b (match-beginning 0)))
18315 (goto-char (point-max))
18316 (if (re-search-backward "^END:VEVENT" nil t)
18317 (setq e (match-end 0)))
18318 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
18319 (kill-buffer buf)
18320 (kill-buffer frombuf)
18321 (delete-file tmpfile)
18322 rtn))
18324 (defun org-closest-date (start current change prefer)
18325 "Find the date closest to CURRENT that is consistent with START and CHANGE.
18326 When PREFER is `past' return a date that is either CURRENT or past.
18327 When PREFER is `future', return a date that is either CURRENT or future."
18328 ;; Make the proper lists from the dates
18329 (catch 'exit
18330 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
18331 dn dw sday cday n1 n2
18332 d m y y1 y2 date1 date2 nmonths nm ny m2)
18334 (setq start (org-date-to-gregorian start)
18335 current (org-date-to-gregorian
18336 (if org-agenda-repeating-timestamp-show-all
18337 current
18338 (time-to-days (current-time))))
18339 sday (calendar-absolute-from-gregorian start)
18340 cday (calendar-absolute-from-gregorian current))
18342 (if (<= cday sday) (throw 'exit sday))
18344 (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
18345 (setq dn (string-to-number (match-string 1 change))
18346 dw (cdr (assoc (match-string 2 change) a1)))
18347 (error "Invalid change specifyer: %s" change))
18348 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
18349 (cond
18350 ((eq dw 'day)
18351 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
18352 n2 (+ n1 dn)))
18353 ((eq dw 'year)
18354 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
18355 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
18356 (setq date1 (list m d y1)
18357 n1 (calendar-absolute-from-gregorian date1)
18358 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
18359 n2 (calendar-absolute-from-gregorian date2)))
18360 ((eq dw 'month)
18361 ;; approx number of month between the tow dates
18362 (setq nmonths (floor (/ (- cday sday) 30.436875)))
18363 ;; How often does dn fit in there?
18364 (setq d (nth 1 start) m (car start) y (nth 2 start)
18365 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
18366 m (+ m nm)
18367 ny (floor (/ m 12))
18368 y (+ y ny)
18369 m (- m (* ny 12)))
18370 (while (> m 12) (setq m (- m 12) y (1+ y)))
18371 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
18372 (setq m2 (+ m dn) y2 y)
18373 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
18374 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
18375 (while (< n2 cday)
18376 (setq n1 n2 m m2 y y2)
18377 (setq m2 (+ m dn) y2 y)
18378 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
18379 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
18381 (if org-agenda-repeating-timestamp-show-all
18382 (cond
18383 ((eq prefer 'past) n1)
18384 ((eq prefer 'future) (if (= cday n1) n1 n2))
18385 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
18386 (cond
18387 ((eq prefer 'past) n1)
18388 ((eq prefer 'future) (if (= cday n1) n1 n2))
18389 (t (if (= cday n1) n1 n2)))))))
18391 (defun org-date-to-gregorian (date)
18392 "Turn any specification of DATE into a gregorian date for the calendar."
18393 (cond ((integerp date) (calendar-gregorian-from-absolute date))
18394 ((and (listp date) (= (length date) 3)) date)
18395 ((stringp date)
18396 (setq date (org-parse-time-string date))
18397 (list (nth 4 date) (nth 3 date) (nth 5 date)))
18398 ((listp date)
18399 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
18401 (defun org-parse-time-string (s &optional nodefault)
18402 "Parse the standard Org-mode time string.
18403 This should be a lot faster than the normal `parse-time-string'.
18404 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
18405 hour and minute fields will be nil if not given."
18406 (if (string-match org-ts-regexp0 s)
18407 (list 0
18408 (if (or (match-beginning 8) (not nodefault))
18409 (string-to-number (or (match-string 8 s) "0")))
18410 (if (or (match-beginning 7) (not nodefault))
18411 (string-to-number (or (match-string 7 s) "0")))
18412 (string-to-number (match-string 4 s))
18413 (string-to-number (match-string 3 s))
18414 (string-to-number (match-string 2 s))
18415 nil nil nil)
18416 (make-list 9 0)))
18418 (defun org-timestamp-up (&optional arg)
18419 "Increase the date item at the cursor by one.
18420 If the cursor is on the year, change the year. If it is on the month or
18421 the day, change that.
18422 With prefix ARG, change by that many units."
18423 (interactive "p")
18424 (org-timestamp-change (prefix-numeric-value arg)))
18426 (defun org-timestamp-down (&optional arg)
18427 "Decrease the date item at the cursor by one.
18428 If the cursor is on the year, change the year. If it is on the month or
18429 the day, change that.
18430 With prefix ARG, change by that many units."
18431 (interactive "p")
18432 (org-timestamp-change (- (prefix-numeric-value arg))))
18434 (defun org-timestamp-up-day (&optional arg)
18435 "Increase the date in the time stamp by one day.
18436 With prefix ARG, change that many days."
18437 (interactive "p")
18438 (if (and (not (org-at-timestamp-p t))
18439 (org-on-heading-p))
18440 (org-todo 'up)
18441 (org-timestamp-change (prefix-numeric-value arg) 'day)))
18443 (defun org-timestamp-down-day (&optional arg)
18444 "Decrease the date in the time stamp by one day.
18445 With prefix ARG, change that many days."
18446 (interactive "p")
18447 (if (and (not (org-at-timestamp-p t))
18448 (org-on-heading-p))
18449 (org-todo 'down)
18450 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
18452 (defsubst org-pos-in-match-range (pos n)
18453 (and (match-beginning n)
18454 (<= (match-beginning n) pos)
18455 (>= (match-end n) pos)))
18457 (defun org-at-timestamp-p (&optional inactive-ok)
18458 "Determine if the cursor is in or at a timestamp."
18459 (interactive)
18460 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
18461 (pos (point))
18462 (ans (or (looking-at tsr)
18463 (save-excursion
18464 (skip-chars-backward "^[<\n\r\t")
18465 (if (> (point) (point-min)) (backward-char 1))
18466 (and (looking-at tsr)
18467 (> (- (match-end 0) pos) -1))))))
18468 (and ans
18469 (boundp 'org-ts-what)
18470 (setq org-ts-what
18471 (cond
18472 ((= pos (match-beginning 0)) 'bracket)
18473 ((= pos (1- (match-end 0))) 'bracket)
18474 ((org-pos-in-match-range pos 2) 'year)
18475 ((org-pos-in-match-range pos 3) 'month)
18476 ((org-pos-in-match-range pos 7) 'hour)
18477 ((org-pos-in-match-range pos 8) 'minute)
18478 ((or (org-pos-in-match-range pos 4)
18479 (org-pos-in-match-range pos 5)) 'day)
18480 ((and (> pos (or (match-end 8) (match-end 5)))
18481 (< pos (match-end 0)))
18482 (- pos (or (match-end 8) (match-end 5))))
18483 (t 'day))))
18484 ans))
18486 (defun org-toggle-timestamp-type ()
18488 (interactive)
18489 (when (org-at-timestamp-p t)
18490 (save-excursion
18491 (goto-char (match-beginning 0))
18492 (insert (if (equal (char-after) ?<) "[" "<")) (delete-char 1)
18493 (goto-char (1- (match-end 0)))
18494 (insert (if (equal (char-after) ?>) "]" ">")) (delete-char 1))
18495 (message "Timestamp is now %sactive"
18496 (if (equal (char-before) ?>) "in" ""))))
18498 (defun org-timestamp-change (n &optional what)
18499 "Change the date in the time stamp at point.
18500 The date will be changed by N times WHAT. WHAT can be `day', `month',
18501 `year', `minute', `second'. If WHAT is not given, the cursor position
18502 in the timestamp determines what will be changed."
18503 (let ((pos (point))
18504 with-hm inactive
18505 org-ts-what
18506 extra
18507 ts time time0)
18508 (if (not (org-at-timestamp-p t))
18509 (error "Not at a timestamp"))
18510 (if (and (not what) (eq org-ts-what 'bracket))
18511 (org-toggle-timestamp-type)
18512 (if (and (not what) (not (eq org-ts-what 'day))
18513 org-display-custom-times
18514 (get-text-property (point) 'display)
18515 (not (get-text-property (1- (point)) 'display)))
18516 (setq org-ts-what 'day))
18517 (setq org-ts-what (or what org-ts-what)
18518 inactive (= (char-after (match-beginning 0)) ?\[)
18519 ts (match-string 0))
18520 (replace-match "")
18521 (if (string-match
18522 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( [-+][0-9]+[dwmy]\\)*\\)[]>]"
18524 (setq extra (match-string 1 ts)))
18525 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
18526 (setq with-hm t))
18527 (setq time0 (org-parse-time-string ts))
18528 (setq time
18529 (encode-time (or (car time0) 0)
18530 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
18531 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
18532 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
18533 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
18534 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
18535 (nthcdr 6 time0)))
18536 (when (integerp org-ts-what)
18537 (setq extra (org-modify-ts-extra extra org-ts-what n)))
18538 (if (eq what 'calendar)
18539 (let ((cal-date (org-get-date-from-calendar)))
18540 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
18541 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
18542 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
18543 (setcar time0 (or (car time0) 0))
18544 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
18545 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
18546 (setq time (apply 'encode-time time0))))
18547 (setq org-last-changed-timestamp
18548 (org-insert-time-stamp time with-hm inactive nil nil extra))
18549 (org-clock-update-time-maybe)
18550 (goto-char pos)
18551 ;; Try to recenter the calendar window, if any
18552 (if (and org-calendar-follow-timestamp-change
18553 (get-buffer-window "*Calendar*" t)
18554 (memq org-ts-what '(day month year)))
18555 (org-recenter-calendar (time-to-days time))))))
18557 ;; FIXME: does not yet work for lead times
18558 (defun org-modify-ts-extra (s pos n)
18559 "Change the different parts of the lead-time and repeat fields in timestamp."
18560 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
18561 ng h m new)
18562 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( \\+\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
18563 (cond
18564 ((or (org-pos-in-match-range pos 2)
18565 (org-pos-in-match-range pos 3))
18566 (setq m (string-to-number (match-string 3 s))
18567 h (string-to-number (match-string 2 s)))
18568 (if (org-pos-in-match-range pos 2)
18569 (setq h (+ h n))
18570 (setq m (+ m n)))
18571 (if (< m 0) (setq m (+ m 60) h (1- h)))
18572 (if (> m 59) (setq m (- m 60) h (1+ h)))
18573 (setq h (min 24 (max 0 h)))
18574 (setq ng 1 new (format "-%02d:%02d" h m)))
18575 ((org-pos-in-match-range pos 6)
18576 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
18577 ((org-pos-in-match-range pos 5)
18578 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s))))))))
18580 (when ng
18581 (setq s (concat
18582 (substring s 0 (match-beginning ng))
18584 (substring s (match-end ng))))))
18587 (defun org-recenter-calendar (date)
18588 "If the calendar is visible, recenter it to DATE."
18589 (let* ((win (selected-window))
18590 (cwin (get-buffer-window "*Calendar*" t))
18591 (calendar-move-hook nil))
18592 (when cwin
18593 (select-window cwin)
18594 (calendar-goto-date (if (listp date) date
18595 (calendar-gregorian-from-absolute date)))
18596 (select-window win))))
18598 (defun org-goto-calendar (&optional arg)
18599 "Go to the Emacs calendar at the current date.
18600 If there is a time stamp in the current line, go to that date.
18601 A prefix ARG can be used to force the current date."
18602 (interactive "P")
18603 (let ((tsr org-ts-regexp) diff
18604 (calendar-move-hook nil)
18605 (view-calendar-holidays-initially nil)
18606 (view-diary-entries-initially nil))
18607 (if (or (org-at-timestamp-p)
18608 (save-excursion
18609 (beginning-of-line 1)
18610 (looking-at (concat ".*" tsr))))
18611 (let ((d1 (time-to-days (current-time)))
18612 (d2 (time-to-days
18613 (org-time-string-to-time (match-string 1)))))
18614 (setq diff (- d2 d1))))
18615 (calendar)
18616 (calendar-goto-today)
18617 (if (and diff (not arg)) (calendar-forward-day diff))))
18619 (defun org-get-date-from-calendar ()
18620 "Return a list (month day year) of date at point in calendar."
18621 (with-current-buffer "*Calendar*"
18622 (save-match-data
18623 (calendar-cursor-to-date))))
18625 (defun org-date-from-calendar ()
18626 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
18627 If there is already a time stamp at the cursor position, update it."
18628 (interactive)
18629 (if (org-at-timestamp-p t)
18630 (org-timestamp-change 0 'calendar)
18631 (let ((cal-date (org-get-date-from-calendar)))
18632 (org-insert-time-stamp
18633 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
18635 (defvar appt-time-msg-list)
18637 ;;;###autoload
18638 (defun org-agenda-to-appt (&optional refresh filter)
18639 "Activate appointments found in `org-agenda-files'.
18640 With a \\[universal-argument] prefix, refresh the list of
18641 appointements.
18643 If FILTER is t, interactively prompt the user for a regular
18644 expression, and filter out entries that don't match it.
18646 If FILTER is a string, use this string as a regular expression
18647 for filtering entries out.
18649 FILTER can also be an alist with the car of each cell being
18650 either 'headline or 'category. For example:
18652 '((headline \"IMPORTANT\")
18653 (category \"Work\"))
18655 will only add headlines containing IMPORTANT or headlines
18656 belonging to the \"Work\" category."
18657 (interactive "P")
18658 (require 'calendar)
18659 (if refresh (setq appt-time-msg-list nil))
18660 (if (eq filter t)
18661 (setq filter (read-from-minibuffer "Regexp filter: ")))
18662 (let* ((cnt 0) ; count added events
18663 (org-agenda-new-buffers nil)
18664 (org-deadline-warning-days 0)
18665 (today (org-date-to-gregorian
18666 (time-to-days (current-time))))
18667 (files (org-agenda-files)) entries file)
18668 ;; Get all entries which may contain an appt
18669 (while (setq file (pop files))
18670 (setq entries
18671 (append entries
18672 (org-agenda-get-day-entries
18673 file today :timestamp :scheduled :deadline))))
18674 (setq entries (delq nil entries))
18675 ;; Map thru entries and find if we should filter them out
18676 (mapc
18677 (lambda(x)
18678 (let* ((evt (org-trim (get-text-property 1 'txt x)))
18679 (cat (get-text-property 1 'org-category x))
18680 (tod (get-text-property 1 'time-of-day x))
18681 (ok (or (null filter)
18682 (and (stringp filter) (string-match filter evt))
18683 (and (listp filter)
18684 (or (string-match
18685 (cadr (assoc 'category filter)) cat)
18686 (string-match
18687 (cadr (assoc 'headline filter)) evt))))))
18688 ;; FIXME: Shall we remove text-properties for the appt text?
18689 ;; (setq evt (set-text-properties 0 (length evt) nil evt))
18690 (when (and ok tod)
18691 (setq tod (number-to-string tod)
18692 tod (when (string-match
18693 "\\([0-9]\\{1,2\\}\\)\\([0-9]\\{2\\}\\)" tod)
18694 (concat (match-string 1 tod) ":"
18695 (match-string 2 tod))))
18696 (appt-add tod evt)
18697 (setq cnt (1+ cnt))))) entries)
18698 (org-release-buffers org-agenda-new-buffers)
18699 (if (eq cnt 0)
18700 (message "No event to add")
18701 (message "Added %d event%s for today" cnt (if (> cnt 1) "s" "")))))
18703 ;;; The clock for measuring work time.
18705 (defvar org-mode-line-string "")
18706 (put 'org-mode-line-string 'risky-local-variable t)
18708 (defvar org-mode-line-timer nil)
18709 (defvar org-clock-heading "")
18710 (defvar org-clock-start-time "")
18712 (defun org-update-mode-line ()
18713 (let* ((delta (- (time-to-seconds (current-time))
18714 (time-to-seconds org-clock-start-time)))
18715 (h (floor delta 3600))
18716 (m (floor (- delta (* 3600 h)) 60)))
18717 (setq org-mode-line-string
18718 (propertize (format "-[%d:%02d (%s)]" h m org-clock-heading)
18719 'help-echo "Org-mode clock is running"))
18720 (force-mode-line-update)))
18722 (defvar org-clock-marker (make-marker)
18723 "Marker recording the last clock-in.")
18724 (defvar org-clock-mode-line-entry nil
18725 "Information for the modeline about the running clock.")
18727 (defun org-clock-in ()
18728 "Start the clock on the current item.
18729 If necessary, clock-out of the currently active clock."
18730 (interactive)
18731 (org-clock-out t)
18732 (let (ts)
18733 (save-excursion
18734 (org-back-to-heading t)
18735 (when (and org-clock-in-switch-to-state
18736 (not (looking-at (concat outline-regexp "[ \t]*"
18737 org-clock-in-switch-to-state
18738 "\\>"))))
18739 (org-todo org-clock-in-switch-to-state))
18740 (if (and org-clock-heading-function
18741 (functionp org-clock-heading-function))
18742 (setq org-clock-heading (funcall org-clock-heading-function))
18743 (if (looking-at org-complex-heading-regexp)
18744 (setq org-clock-heading (match-string 4))
18745 (setq org-clock-heading "???")))
18746 (setq org-clock-heading (propertize org-clock-heading 'face nil))
18747 (org-clock-find-position)
18749 (insert "\n") (backward-char 1)
18750 (indent-relative)
18751 (insert org-clock-string " ")
18752 (setq org-clock-start-time (current-time))
18753 (setq ts (org-insert-time-stamp (current-time) 'with-hm 'inactive))
18754 (move-marker org-clock-marker (point) (buffer-base-buffer))
18755 (or global-mode-string (setq global-mode-string '("")))
18756 (or (memq 'org-mode-line-string global-mode-string)
18757 (setq global-mode-string
18758 (append global-mode-string '(org-mode-line-string))))
18759 (org-update-mode-line)
18760 (setq org-mode-line-timer (run-with-timer 60 60 'org-update-mode-line))
18761 (message "Clock started at %s" ts))))
18763 (defun org-clock-find-position ()
18764 "Find the location where the next clock line should be inserted."
18765 (org-back-to-heading t)
18766 (catch 'exit
18767 (let ((beg (point-at-bol 2)) (end (progn (outline-next-heading) (point)))
18768 (re (concat "^[ \t]*" org-clock-string))
18769 (cnt 0)
18770 first last)
18771 (goto-char beg)
18772 (when (eobp) (newline) (setq end (max (point) end)))
18773 (when (re-search-forward "^[ \t]*:CLOCK:" end t)
18774 ;; we seem to have a CLOCK drawer, so go there.
18775 (beginning-of-line 2)
18776 (throw 'exit t))
18777 ;; Lets count the CLOCK lines
18778 (goto-char beg)
18779 (while (re-search-forward re end t)
18780 (setq first (or first (match-beginning 0))
18781 last (match-beginning 0)
18782 cnt (1+ cnt)))
18783 (when (and (integerp org-clock-into-drawer)
18784 (>= (1+ cnt) org-clock-into-drawer))
18785 ;; Wrap current entries into a new drawer
18786 (goto-char last)
18787 (beginning-of-line 2)
18788 (if (org-at-item-p) (org-end-of-item))
18789 (insert ":END:\n")
18790 (beginning-of-line 0)
18791 (org-indent-line-function)
18792 (goto-char first)
18793 (insert ":CLOCK:\n")
18794 (beginning-of-line 0)
18795 (org-indent-line-function)
18796 (org-flag-drawer t)
18797 (beginning-of-line 2)
18798 (throw 'exit nil))
18800 (goto-char beg)
18801 (while (and (looking-at (concat "[ \t]*" org-keyword-time-regexp))
18802 (not (equal (match-string 1) org-clock-string)))
18803 ;; Planning info, skip to after it
18804 (beginning-of-line 2)
18805 (or (bolp) (newline)))
18806 (when (eq t org-clock-into-drawer)
18807 (insert ":CLOCK:\n:END:\n")
18808 (beginning-of-line -1)
18809 (org-indent-line-function)
18810 (org-flag-drawer t)
18811 (beginning-of-line 2)
18812 (org-indent-line-function)))))
18814 (defun org-clock-out (&optional fail-quietly)
18815 "Stop the currently running clock.
18816 If there is no running clock, throw an error, unless FAIL-QUIETLY is set."
18817 (interactive)
18818 (catch 'exit
18819 (if (not (marker-buffer org-clock-marker))
18820 (if fail-quietly (throw 'exit t) (error "No active clock")))
18821 (let (ts te s h m)
18822 (save-excursion
18823 (set-buffer (marker-buffer org-clock-marker))
18824 (goto-char org-clock-marker)
18825 (beginning-of-line 1)
18826 (if (and (looking-at (concat "[ \t]*" org-keyword-time-regexp))
18827 (equal (match-string 1) org-clock-string))
18828 (setq ts (match-string 2))
18829 (if fail-quietly (throw 'exit nil) (error "Clock start time is gone")))
18830 (goto-char (match-end 0))
18831 (delete-region (point) (point-at-eol))
18832 (insert "--")
18833 (setq te (org-insert-time-stamp (current-time) 'with-hm 'inactive))
18834 (setq s (- (time-to-seconds (apply 'encode-time (org-parse-time-string te)))
18835 (time-to-seconds (apply 'encode-time (org-parse-time-string ts))))
18836 h (floor (/ s 3600))
18837 s (- s (* 3600 h))
18838 m (floor (/ s 60))
18839 s (- s (* 60 s)))
18840 (insert " => " (format "%2d:%02d" h m))
18841 (move-marker org-clock-marker nil)
18842 (when org-log-note-clock-out
18843 (org-add-log-maybe 'clock-out))
18844 (when org-mode-line-timer
18845 (cancel-timer org-mode-line-timer)
18846 (setq org-mode-line-timer nil))
18847 (setq global-mode-string
18848 (delq 'org-mode-line-string global-mode-string))
18849 (force-mode-line-update)
18850 (message "Clock stopped at %s after HH:MM = %d:%02d" te h m)))))
18852 (defun org-clock-cancel ()
18853 "Cancel the running clock be removing the start timestamp."
18854 (interactive)
18855 (if (not (marker-buffer org-clock-marker))
18856 (error "No active clock"))
18857 (save-excursion
18858 (set-buffer (marker-buffer org-clock-marker))
18859 (goto-char org-clock-marker)
18860 (delete-region (1- (point-at-bol)) (point-at-eol)))
18861 (setq global-mode-string
18862 (delq 'org-mode-line-string global-mode-string))
18863 (force-mode-line-update)
18864 (message "Clock canceled"))
18866 (defun org-clock-goto (&optional delete-windows)
18867 "Go to the currently clocked-in entry."
18868 (interactive "P")
18869 (if (not (marker-buffer org-clock-marker))
18870 (error "No active clock"))
18871 (switch-to-buffer-other-window
18872 (marker-buffer org-clock-marker))
18873 (if delete-windows (delete-other-windows))
18874 (goto-char org-clock-marker)
18875 (org-show-entry)
18876 (org-back-to-heading)
18877 (recenter))
18879 (defvar org-clock-file-total-minutes nil
18880 "Holds the file total time in minutes, after a call to `org-clock-sum'.")
18881 (make-variable-buffer-local 'org-clock-file-total-minutes)
18883 (defun org-clock-sum (&optional tstart tend)
18884 "Sum the times for each subtree.
18885 Puts the resulting times in minutes as a text property on each headline."
18886 (interactive)
18887 (let* ((bmp (buffer-modified-p))
18888 (re (concat "^\\(\\*+\\)[ \t]\\|^[ \t]*"
18889 org-clock-string
18890 "[ \t]*\\(?:\\(\\[.*?\\]\\)-+\\(\\[.*?\\]\\)\\|=>[ \t]+\\([0-9]+\\):\\([0-9]+\\)\\)"))
18891 (lmax 30)
18892 (ltimes (make-vector lmax 0))
18893 (t1 0)
18894 (level 0)
18895 ts te dt
18896 time)
18897 (remove-text-properties (point-min) (point-max) '(:org-clock-minutes t))
18898 (save-excursion
18899 (goto-char (point-max))
18900 (while (re-search-backward re nil t)
18901 (cond
18902 ((match-end 2)
18903 ;; Two time stamps
18904 (setq ts (match-string 2)
18905 te (match-string 3)
18906 ts (time-to-seconds
18907 (apply 'encode-time (org-parse-time-string ts)))
18908 te (time-to-seconds
18909 (apply 'encode-time (org-parse-time-string te)))
18910 ts (if tstart (max ts tstart) ts)
18911 te (if tend (min te tend) te)
18912 dt (- te ts)
18913 t1 (if (> dt 0) (+ t1 (floor (/ dt 60))) t1)))
18914 ((match-end 4)
18915 ;; A naket time
18916 (setq t1 (+ t1 (string-to-number (match-string 5))
18917 (* 60 (string-to-number (match-string 4))))))
18918 (t ;; A headline
18919 (setq level (- (match-end 1) (match-beginning 1)))
18920 (when (or (> t1 0) (> (aref ltimes level) 0))
18921 (loop for l from 0 to level do
18922 (aset ltimes l (+ (aref ltimes l) t1)))
18923 (setq t1 0 time (aref ltimes level))
18924 (loop for l from level to (1- lmax) do
18925 (aset ltimes l 0))
18926 (goto-char (match-beginning 0))
18927 (put-text-property (point) (point-at-eol) :org-clock-minutes time)))))
18928 (setq org-clock-file-total-minutes (aref ltimes 0)))
18929 (set-buffer-modified-p bmp)))
18931 (defun org-clock-display (&optional total-only)
18932 "Show subtree times in the entire buffer.
18933 If TOTAL-ONLY is non-nil, only show the total time for the entire file
18934 in the echo area."
18935 (interactive)
18936 (org-remove-clock-overlays)
18937 (let (time h m p)
18938 (org-clock-sum)
18939 (unless total-only
18940 (save-excursion
18941 (goto-char (point-min))
18942 (while (or (and (equal (setq p (point)) (point-min))
18943 (get-text-property p :org-clock-minutes))
18944 (setq p (next-single-property-change
18945 (point) :org-clock-minutes)))
18946 (goto-char p)
18947 (when (setq time (get-text-property p :org-clock-minutes))
18948 (org-put-clock-overlay time (funcall outline-level))))
18949 (setq h (/ org-clock-file-total-minutes 60)
18950 m (- org-clock-file-total-minutes (* 60 h)))
18951 ;; Arrange to remove the overlays upon next change.
18952 (when org-remove-highlights-with-change
18953 (org-add-hook 'before-change-functions 'org-remove-clock-overlays
18954 nil 'local))))
18955 (message "Total file time: %d:%02d (%d hours and %d minutes)" h m h m)))
18957 (defvar org-clock-overlays nil)
18958 (make-variable-buffer-local 'org-clock-overlays)
18960 (defun org-put-clock-overlay (time &optional level)
18961 "Put an overlays on the current line, displaying TIME.
18962 If LEVEL is given, prefix time with a corresponding number of stars.
18963 This creates a new overlay and stores it in `org-clock-overlays', so that it
18964 will be easy to remove."
18965 (let* ((c 60) (h (floor (/ time 60))) (m (- time (* 60 h)))
18966 (l (if level (org-get-legal-level level 0) 0))
18967 (off 0)
18968 ov tx)
18969 (move-to-column c)
18970 (unless (eolp) (skip-chars-backward "^ \t"))
18971 (skip-chars-backward " \t")
18972 (setq ov (org-make-overlay (1- (point)) (point-at-eol))
18973 tx (concat (buffer-substring (1- (point)) (point))
18974 (make-string (+ off (max 0 (- c (current-column)))) ?.)
18975 (org-add-props (format "%s %2d:%02d%s"
18976 (make-string l ?*) h m
18977 (make-string (- 16 l) ?\ ))
18978 '(face secondary-selection))
18979 ""))
18980 (if (not (featurep 'xemacs))
18981 (org-overlay-put ov 'display tx)
18982 (org-overlay-put ov 'invisible t)
18983 (org-overlay-put ov 'end-glyph (make-glyph tx)))
18984 (push ov org-clock-overlays)))
18986 (defun org-remove-clock-overlays (&optional beg end noremove)
18987 "Remove the occur highlights from the buffer.
18988 BEG and END are ignored. If NOREMOVE is nil, remove this function
18989 from the `before-change-functions' in the current buffer."
18990 (interactive)
18991 (unless org-inhibit-highlight-removal
18992 (mapc 'org-delete-overlay org-clock-overlays)
18993 (setq org-clock-overlays nil)
18994 (unless noremove
18995 (remove-hook 'before-change-functions
18996 'org-remove-clock-overlays 'local))))
18998 (defun org-clock-out-if-current ()
18999 "Clock out if the current entry contains the running clock.
19000 This is used to stop the clock after a TODO entry is marked DONE,
19001 and is only done if the variable `org-clock-out-when-done' is not nil."
19002 (when (and org-clock-out-when-done
19003 (member state org-done-keywords)
19004 (equal (marker-buffer org-clock-marker) (current-buffer))
19005 (< (point) org-clock-marker)
19006 (> (save-excursion (outline-next-heading) (point))
19007 org-clock-marker))
19008 ;; Clock out, but don't accept a logging message for this.
19009 (let ((org-log-note-clock-out nil))
19010 (org-clock-out))))
19012 (add-hook 'org-after-todo-state-change-hook
19013 'org-clock-out-if-current)
19015 (defun org-check-running-clock ()
19016 "Check if the current buffer contains the running clock.
19017 If yes, offer to stop it and to save the buffer with the changes."
19018 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
19019 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
19020 (buffer-name))))
19021 (org-clock-out)
19022 (when (y-or-n-p "Save changed buffer?")
19023 (save-buffer))))
19025 (defun org-clock-report (&optional arg)
19026 "Create a table containing a report about clocked time.
19027 If the cursor is inside an existing clocktable block, then the table
19028 will be updated. If not, a new clocktable will be inserted.
19029 When called with a prefix argument, move to the first clock table in the
19030 buffer and update it."
19031 (interactive "P")
19032 (org-remove-clock-overlays)
19033 (when arg
19034 (org-find-dblock "clocktable")
19035 (org-show-entry))
19036 (if (org-in-clocktable-p)
19037 (goto-char (org-in-clocktable-p))
19038 (org-create-dblock (list :name "clocktable"
19039 :maxlevel 2 :scope 'file)))
19040 (org-update-dblock))
19042 (defun org-in-clocktable-p ()
19043 "Check if the cursor is in a clocktable."
19044 (let ((pos (point)) start)
19045 (save-excursion
19046 (end-of-line 1)
19047 (and (re-search-backward "^#\\+BEGIN:[ \t]+clocktable" nil t)
19048 (setq start (match-beginning 0))
19049 (re-search-forward "^#\\+END:.*" nil t)
19050 (>= (match-end 0) pos)
19051 start))))
19053 (defun org-clock-update-time-maybe ()
19054 "If this is a CLOCK line, update it and return t.
19055 Otherwise, return nil."
19056 (interactive)
19057 (save-excursion
19058 (beginning-of-line 1)
19059 (skip-chars-forward " \t")
19060 (when (looking-at org-clock-string)
19061 (let ((re (concat "[ \t]*" org-clock-string
19062 " *[[<]\\([^]>]+\\)[]>]-+[[<]\\([^]>]+\\)[]>]"
19063 "\\([ \t]*=>.*\\)?"))
19064 ts te h m s)
19065 (if (not (looking-at re))
19067 (and (match-end 3) (delete-region (match-beginning 3) (match-end 3)))
19068 (end-of-line 1)
19069 (setq ts (match-string 1)
19070 te (match-string 2))
19071 (setq s (- (time-to-seconds
19072 (apply 'encode-time (org-parse-time-string te)))
19073 (time-to-seconds
19074 (apply 'encode-time (org-parse-time-string ts))))
19075 h (floor (/ s 3600))
19076 s (- s (* 3600 h))
19077 m (floor (/ s 60))
19078 s (- s (* 60 s)))
19079 (insert " => " (format "%2d:%02d" h m))
19080 t)))))
19082 (defun org-clock-special-range (key &optional time as-strings)
19083 "Return two times bordering a special time range.
19084 Key is a symbol specifying the range and can be one of `today', `yesterday',
19085 `thisweek', `lastweek', `thismonth', `lastmonth', `thisyear', `lastyear'.
19086 A week starts Monday 0:00 and ends Sunday 24:00.
19087 The range is determined relative to TIME. TIME defaults to the current time.
19088 The return value is a cons cell with two internal times like the ones
19089 returned by `current time' or `encode-time'. if AS-STRINGS is non-nil,
19090 the returned times will be formatted strings."
19091 (let* ((tm (decode-time (or time (current-time))))
19092 (s 0) (m (nth 1 tm)) (h (nth 2 tm))
19093 (d (nth 3 tm)) (month (nth 4 tm)) (y (nth 5 tm))
19094 (dow (nth 6 tm))
19095 s1 m1 h1 d1 month1 y1 diff ts te fm)
19096 (cond
19097 ((eq key 'today)
19098 (setq h 0 m 0 h1 24 m1 0))
19099 ((eq key 'yesterday)
19100 (setq d (1- d) h 0 m 0 h1 24 m1 0))
19101 ((eq key 'thisweek)
19102 (setq diff (if (= dow 0) 6 (1- dow))
19103 m 0 h 0 d (- d diff) d1 (+ 7 d)))
19104 ((eq key 'lastweek)
19105 (setq diff (+ 7 (if (= dow 0) 6 (1- dow)))
19106 m 0 h 0 d (- d diff) d1 (+ 7 d)))
19107 ((eq key 'thismonth)
19108 (setq d 1 h 0 m 0 d1 1 month1 (1+ month) h1 0 m1 0))
19109 ((eq key 'lastmonth)
19110 (setq d 1 h 0 m 0 d1 1 month (1- month) month1 (1+ month) h1 0 m1 0))
19111 ((eq key 'thisyear)
19112 (setq m 0 h 0 d 1 month 1 y1 (1+ y)))
19113 ((eq key 'lastyear)
19114 (setq m 0 h 0 d 1 month 1 y (1- y) y1 (1+ y)))
19115 (t (error "No such time block %s" key)))
19116 (setq ts (encode-time s m h d month y)
19117 te (encode-time (or s1 s) (or m1 m) (or h1 h)
19118 (or d1 d) (or month1 month) (or y1 y)))
19119 (setq fm (cdr org-time-stamp-formats))
19120 (if as-strings
19121 (cons (format-time-string fm ts) (format-time-string fm te))
19122 (cons ts te))))
19124 (defun org-dblock-write:clocktable (params)
19125 "Write the standard clocktable."
19126 (catch 'exit
19127 (let* ((hlchars '((1 . "*") (2 . "/")))
19128 (ins (make-marker))
19129 (total-time nil)
19130 (scope (plist-get params :scope))
19131 (tostring (plist-get params :tostring))
19132 (multifile (plist-get params :multifile))
19133 (header (plist-get params :header))
19134 (maxlevel (or (plist-get params :maxlevel) 3))
19135 (step (plist-get params :step))
19136 (emph (plist-get params :emphasize))
19137 (ts (plist-get params :tstart))
19138 (te (plist-get params :tend))
19139 (block (plist-get params :block))
19140 ipos time h m p level hlc hdl
19141 cc beg end pos tbl)
19142 (when step
19143 (org-clocktable-steps params)
19144 (throw 'exit nil))
19145 (when block
19146 (setq cc (org-clock-special-range block nil t)
19147 ts (car cc) te (cdr cc)))
19148 (if ts (setq ts (time-to-seconds
19149 (apply 'encode-time (org-parse-time-string ts)))))
19150 (if te (setq te (time-to-seconds
19151 (apply 'encode-time (org-parse-time-string te)))))
19152 (move-marker ins (point))
19153 (setq ipos (point))
19155 ;; Get the right scope
19156 (setq pos (point))
19157 (save-restriction
19158 (cond
19159 ((not scope))
19160 ((eq scope 'file) (widen))
19161 ((eq scope 'subtree) (org-narrow-to-subtree))
19162 ((eq scope 'tree)
19163 (while (org-up-heading-safe))
19164 (org-narrow-to-subtree))
19165 ((and (symbolp scope) (string-match "^tree\\([0-9]+\\)$"
19166 (symbol-name scope)))
19167 (setq level (string-to-number (match-string 1 (symbol-name scope))))
19168 (catch 'exit
19169 (while (org-up-heading-safe)
19170 (looking-at outline-regexp)
19171 (if (<= (org-reduced-level (funcall outline-level)) level)
19172 (throw 'exit nil))))
19173 (org-narrow-to-subtree))
19174 ((or (listp scope) (eq scope 'agenda))
19175 (let* ((files (if (listp scope) scope (org-agenda-files)))
19176 (scope 'agenda)
19177 (p1 (copy-sequence params))
19178 file)
19179 (plist-put p1 :tostring t)
19180 (plist-put p1 :multifile t)
19181 (plist-put p1 :scope 'file)
19182 (org-prepare-agenda-buffers files)
19183 (while (setq file (pop files))
19184 (with-current-buffer (find-buffer-visiting file)
19185 (push (org-clocktable-add-file
19186 file (org-dblock-write:clocktable p1)) tbl)
19187 (setq total-time (+ (or total-time 0)
19188 org-clock-file-total-minutes)))))))
19189 (goto-char pos)
19191 (unless (eq scope 'agenda)
19192 (org-clock-sum ts te)
19193 (goto-char (point-min))
19194 (while (setq p (next-single-property-change (point) :org-clock-minutes))
19195 (goto-char p)
19196 (when (setq time (get-text-property p :org-clock-minutes))
19197 (save-excursion
19198 (beginning-of-line 1)
19199 (when (and (looking-at (org-re "\\(\\*+\\)[ \t]+\\(.*?\\)\\([ \t]+:[[:alnum:]_@:]+:\\)?[ \t]*$"))
19200 (setq level (org-reduced-level
19201 (- (match-end 1) (match-beginning 1))))
19202 (<= level maxlevel))
19203 (setq hlc (if emph (or (cdr (assoc level hlchars)) "") "")
19204 hdl (match-string 2)
19205 h (/ time 60)
19206 m (- time (* 60 h)))
19207 (if (and (not multifile) (= level 1)) (push "|-" tbl))
19208 (push (concat
19209 "| " (int-to-string level) "|" hlc hdl hlc " |"
19210 (make-string (1- level) ?|)
19211 hlc (format "%d:%02d" h m) hlc
19212 " |") tbl))))))
19213 (setq tbl (nreverse tbl))
19214 (if tostring
19215 (if tbl (mapconcat 'identity tbl "\n") nil)
19216 (goto-char ins)
19217 (insert-before-markers
19218 (or header
19219 (concat
19220 "Clock summary at ["
19221 (substring
19222 (format-time-string (cdr org-time-stamp-formats))
19223 1 -1)
19224 "]."
19225 (if block
19226 (format " Considered range is /%s/." block)
19228 "\n\n"))
19229 (if (eq scope 'agenda) "|File" "")
19230 "|L|Headline|Time|\n")
19231 (setq total-time (or total-time org-clock-file-total-minutes)
19232 h (/ total-time 60)
19233 m (- total-time (* 60 h)))
19234 (insert-before-markers
19235 "|-\n|"
19236 (if (eq scope 'agenda) "|" "")
19238 "*Total time*| "
19239 (format "*%d:%02d*" h m)
19240 "|\n|-\n")
19241 (setq tbl (delq nil tbl))
19242 (if (and (stringp (car tbl)) (> (length (car tbl)) 1)
19243 (equal (substring (car tbl) 0 2) "|-"))
19244 (pop tbl))
19245 (insert-before-markers (mapconcat
19246 'identity (delq nil tbl)
19247 (if (eq scope 'agenda) "\n|-\n" "\n")))
19248 (backward-delete-char 1)
19249 (goto-char ipos)
19250 (skip-chars-forward "^|")
19251 (org-table-align))))))
19253 (defun org-clocktable-steps (params)
19254 (let* ((p1 (copy-sequence params))
19255 (ts (plist-get p1 :tstart))
19256 (te (plist-get p1 :tend))
19257 (step0 (plist-get p1 :step))
19258 (step (cdr (assoc step0 '((day . 86400) (week . 604800)))))
19259 (block (plist-get p1 :block))
19261 (when block
19262 (setq cc (org-clock-special-range block nil t)
19263 ts (car cc) te (cdr cc)))
19264 (if ts (setq ts (time-to-seconds
19265 (apply 'encode-time (org-parse-time-string ts)))))
19266 (if te (setq te (time-to-seconds
19267 (apply 'encode-time (org-parse-time-string te)))))
19268 (plist-put p1 :header "")
19269 (plist-put p1 :step nil)
19270 (plist-put p1 :block nil)
19271 (while (< ts te)
19272 (or (bolp) (insert "\n"))
19273 (plist-put p1 :tstart (format-time-string
19274 (car org-time-stamp-formats)
19275 (seconds-to-time ts)))
19276 (plist-put p1 :tend (format-time-string
19277 (car org-time-stamp-formats)
19278 (seconds-to-time (setq ts (+ ts step)))))
19279 (insert "\n" (if (eq step0 'day) "Daily report: " "Weekly report starting on: ")
19280 (plist-get p1 :tstart) "\n")
19281 (org-dblock-write:clocktable p1)
19282 (re-search-forward "#\\+END:")
19283 (end-of-line 0))))
19286 (defun org-clocktable-add-file (file table)
19287 (if table
19288 (let ((lines (org-split-string table "\n"))
19289 (ff (file-name-nondirectory file)))
19290 (mapconcat 'identity
19291 (mapcar (lambda (x)
19292 (if (string-match org-table-dataline-regexp x)
19293 (concat "|" ff x)
19295 lines)
19296 "\n"))))
19298 ;; FIXME: I don't think anybody uses this, ask David
19299 (defun org-collect-clock-time-entries ()
19300 "Return an internal list with clocking information.
19301 This list has one entry for each CLOCK interval.
19302 FIXME: describe the elements."
19303 (interactive)
19304 (let ((re (concat "^[ \t]*" org-clock-string
19305 " *\\[\\(.*?\\)\\]--\\[\\(.*?\\)\\]"))
19306 rtn beg end next cont level title total closedp leafp
19307 clockpos titlepos h m donep)
19308 (save-excursion
19309 (org-clock-sum)
19310 (goto-char (point-min))
19311 (while (re-search-forward re nil t)
19312 (setq clockpos (match-beginning 0)
19313 beg (match-string 1) end (match-string 2)
19314 cont (match-end 0))
19315 (setq beg (apply 'encode-time (org-parse-time-string beg))
19316 end (apply 'encode-time (org-parse-time-string end)))
19317 (org-back-to-heading t)
19318 (setq donep (org-entry-is-done-p))
19319 (setq titlepos (point)
19320 total (or (get-text-property (1+ (point)) :org-clock-minutes) 0)
19321 h (/ total 60) m (- total (* 60 h))
19322 total (cons h m))
19323 (looking-at "\\(\\*+\\) +\\(.*\\)")
19324 (setq level (- (match-end 1) (match-beginning 1))
19325 title (org-match-string-no-properties 2))
19326 (save-excursion (outline-next-heading) (setq next (point)))
19327 (setq closedp (re-search-forward org-closed-time-regexp next t))
19328 (goto-char next)
19329 (setq leafp (and (looking-at "^\\*+ ")
19330 (<= (- (match-end 0) (point)) level)))
19331 (push (list beg end clockpos closedp donep
19332 total title titlepos level leafp)
19333 rtn)
19334 (goto-char cont)))
19335 (nreverse rtn)))
19337 ;;;; Agenda, and Diary Integration
19339 ;;; Define the Org-agenda-mode
19341 (defvar org-agenda-mode-map (make-sparse-keymap)
19342 "Keymap for `org-agenda-mode'.")
19344 (defvar org-agenda-menu) ; defined later in this file.
19345 (defvar org-agenda-follow-mode nil)
19346 (defvar org-agenda-show-log nil)
19347 (defvar org-agenda-redo-command nil)
19348 (defvar org-agenda-query-string nil)
19349 (defvar org-agenda-mode-hook nil)
19350 (defvar org-agenda-type nil)
19351 (defvar org-agenda-force-single-file nil)
19353 (defun org-agenda-mode ()
19354 "Mode for time-sorted view on action items in Org-mode files.
19356 The following commands are available:
19358 \\{org-agenda-mode-map}"
19359 (interactive)
19360 (kill-all-local-variables)
19361 (setq org-agenda-undo-list nil
19362 org-agenda-pending-undo-list nil)
19363 (setq major-mode 'org-agenda-mode)
19364 ;; Keep global-font-lock-mode from turning on font-lock-mode
19365 (org-set-local 'font-lock-global-modes (list 'not major-mode))
19366 (setq mode-name "Org-Agenda")
19367 (use-local-map org-agenda-mode-map)
19368 (easy-menu-add org-agenda-menu)
19369 (if org-startup-truncated (setq truncate-lines t))
19370 (org-add-hook 'post-command-hook 'org-agenda-post-command-hook nil 'local)
19371 (org-add-hook 'pre-command-hook 'org-unhighlight nil 'local)
19372 ;; Make sure properties are removed when copying text
19373 (when (boundp 'buffer-substring-filters)
19374 (org-set-local 'buffer-substring-filters
19375 (cons (lambda (x)
19376 (set-text-properties 0 (length x) nil x) x)
19377 buffer-substring-filters)))
19378 (unless org-agenda-keep-modes
19379 (setq org-agenda-follow-mode org-agenda-start-with-follow-mode
19380 org-agenda-show-log nil))
19381 (easy-menu-change
19382 '("Agenda") "Agenda Files"
19383 (append
19384 (list
19385 (vector
19386 (if (get 'org-agenda-files 'org-restrict)
19387 "Restricted to single file"
19388 "Edit File List")
19389 '(org-edit-agenda-file-list)
19390 (not (get 'org-agenda-files 'org-restrict)))
19391 "--")
19392 (mapcar 'org-file-menu-entry (org-agenda-files))))
19393 (org-agenda-set-mode-name)
19394 (apply
19395 (if (fboundp 'run-mode-hooks) 'run-mode-hooks 'run-hooks)
19396 (list 'org-agenda-mode-hook)))
19398 (substitute-key-definition 'undo 'org-agenda-undo
19399 org-agenda-mode-map global-map)
19400 (org-defkey org-agenda-mode-map "\C-i" 'org-agenda-goto)
19401 (org-defkey org-agenda-mode-map [(tab)] 'org-agenda-goto)
19402 (org-defkey org-agenda-mode-map "\C-m" 'org-agenda-switch-to)
19403 (org-defkey org-agenda-mode-map "\C-k" 'org-agenda-kill)
19404 (org-defkey org-agenda-mode-map "\C-c$" 'org-agenda-archive)
19405 (org-defkey org-agenda-mode-map "\C-c\C-x\C-s" 'org-agenda-archive)
19406 (org-defkey org-agenda-mode-map "$" 'org-agenda-archive)
19407 (org-defkey org-agenda-mode-map "\C-c\C-o" 'org-agenda-open-link)
19408 (org-defkey org-agenda-mode-map " " 'org-agenda-show)
19409 (org-defkey org-agenda-mode-map "\C-c\C-t" 'org-agenda-todo)
19410 (org-defkey org-agenda-mode-map [(control shift right)] 'org-agenda-todo-nextset)
19411 (org-defkey org-agenda-mode-map [(control shift left)] 'org-agenda-todo-previousset)
19412 (org-defkey org-agenda-mode-map "\C-c\C-xb" 'org-agenda-tree-to-indirect-buffer)
19413 (org-defkey org-agenda-mode-map "b" 'org-agenda-tree-to-indirect-buffer)
19414 (org-defkey org-agenda-mode-map "o" 'delete-other-windows)
19415 (org-defkey org-agenda-mode-map "L" 'org-agenda-recenter)
19416 (org-defkey org-agenda-mode-map "t" 'org-agenda-todo)
19417 (org-defkey org-agenda-mode-map "a" 'org-agenda-toggle-archive-tag)
19418 (org-defkey org-agenda-mode-map ":" 'org-agenda-set-tags)
19419 (org-defkey org-agenda-mode-map "." 'org-agenda-goto-today)
19420 (org-defkey org-agenda-mode-map "j" 'org-agenda-goto-date)
19421 (org-defkey org-agenda-mode-map "d" 'org-agenda-day-view)
19422 (org-defkey org-agenda-mode-map "w" 'org-agenda-week-view)
19423 (org-defkey org-agenda-mode-map "m" 'org-agenda-month-view)
19424 (org-defkey org-agenda-mode-map "y" 'org-agenda-year-view)
19425 (org-defkey org-agenda-mode-map [(shift right)] 'org-agenda-date-later)
19426 (org-defkey org-agenda-mode-map [(shift left)] 'org-agenda-date-earlier)
19427 (org-defkey org-agenda-mode-map [?\C-c ?\C-x (right)] 'org-agenda-date-later)
19428 (org-defkey org-agenda-mode-map [?\C-c ?\C-x (left)] 'org-agenda-date-earlier)
19430 (org-defkey org-agenda-mode-map ">" 'org-agenda-date-prompt)
19431 (org-defkey org-agenda-mode-map "\C-c\C-s" 'org-agenda-schedule)
19432 (org-defkey org-agenda-mode-map "\C-c\C-d" 'org-agenda-deadline)
19433 (let ((l '(1 2 3 4 5 6 7 8 9 0)))
19434 (while l (org-defkey org-agenda-mode-map
19435 (int-to-string (pop l)) 'digit-argument)))
19437 (org-defkey org-agenda-mode-map "f" 'org-agenda-follow-mode)
19438 (org-defkey org-agenda-mode-map "l" 'org-agenda-log-mode)
19439 (org-defkey org-agenda-mode-map "D" 'org-agenda-toggle-diary)
19440 (org-defkey org-agenda-mode-map "G" 'org-agenda-toggle-time-grid)
19441 (org-defkey org-agenda-mode-map "r" 'org-agenda-redo)
19442 (org-defkey org-agenda-mode-map "g" 'org-agenda-redo)
19443 (org-defkey org-agenda-mode-map "e" 'org-agenda-execute)
19444 (org-defkey org-agenda-mode-map "q" 'org-agenda-quit)
19445 (org-defkey org-agenda-mode-map "x" 'org-agenda-exit)
19446 (org-defkey org-agenda-mode-map "\C-x\C-w" 'org-write-agenda)
19447 (org-defkey org-agenda-mode-map "s" 'org-save-all-org-buffers)
19448 (org-defkey org-agenda-mode-map "\C-x\C-s" 'org-save-all-org-buffers)
19449 (org-defkey org-agenda-mode-map "P" 'org-agenda-show-priority)
19450 (org-defkey org-agenda-mode-map "T" 'org-agenda-show-tags)
19451 (org-defkey org-agenda-mode-map "n" 'next-line)
19452 (org-defkey org-agenda-mode-map "p" 'previous-line)
19453 (org-defkey org-agenda-mode-map "\C-c\C-n" 'org-agenda-next-date-line)
19454 (org-defkey org-agenda-mode-map "\C-c\C-p" 'org-agenda-previous-date-line)
19455 (org-defkey org-agenda-mode-map "," 'org-agenda-priority)
19456 (org-defkey org-agenda-mode-map "\C-c," 'org-agenda-priority)
19457 (org-defkey org-agenda-mode-map "i" 'org-agenda-diary-entry)
19458 (org-defkey org-agenda-mode-map "c" 'org-agenda-goto-calendar)
19459 (eval-after-load "calendar"
19460 '(org-defkey calendar-mode-map org-calendar-to-agenda-key
19461 'org-calendar-goto-agenda))
19462 (org-defkey org-agenda-mode-map "C" 'org-agenda-convert-date)
19463 (org-defkey org-agenda-mode-map "M" 'org-agenda-phases-of-moon)
19464 (org-defkey org-agenda-mode-map "S" 'org-agenda-sunrise-sunset)
19465 (org-defkey org-agenda-mode-map "h" 'org-agenda-holidays)
19466 (org-defkey org-agenda-mode-map "H" 'org-agenda-holidays)
19467 (org-defkey org-agenda-mode-map "\C-c\C-x\C-i" 'org-agenda-clock-in)
19468 (org-defkey org-agenda-mode-map "I" 'org-agenda-clock-in)
19469 (org-defkey org-agenda-mode-map "\C-c\C-x\C-o" 'org-agenda-clock-out)
19470 (org-defkey org-agenda-mode-map "O" 'org-agenda-clock-out)
19471 (org-defkey org-agenda-mode-map "\C-c\C-x\C-x" 'org-agenda-clock-cancel)
19472 (org-defkey org-agenda-mode-map "X" 'org-agenda-clock-cancel)
19473 (org-defkey org-agenda-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
19474 (org-defkey org-agenda-mode-map "J" 'org-clock-goto)
19475 (org-defkey org-agenda-mode-map "+" 'org-agenda-priority-up)
19476 (org-defkey org-agenda-mode-map "-" 'org-agenda-priority-down)
19477 (org-defkey org-agenda-mode-map [(shift up)] 'org-agenda-priority-up)
19478 (org-defkey org-agenda-mode-map [(shift down)] 'org-agenda-priority-down)
19479 (org-defkey org-agenda-mode-map [?\C-c ?\C-x (up)] 'org-agenda-priority-up)
19480 (org-defkey org-agenda-mode-map [?\C-c ?\C-x (down)] 'org-agenda-priority-down)
19481 (org-defkey org-agenda-mode-map [(right)] 'org-agenda-later)
19482 (org-defkey org-agenda-mode-map [(left)] 'org-agenda-earlier)
19483 (org-defkey org-agenda-mode-map "\C-c\C-x\C-c" 'org-agenda-columns)
19485 (org-defkey org-agenda-mode-map "[" 'org-agenda-manipulate-query-add)
19486 (org-defkey org-agenda-mode-map "]" 'org-agenda-manipulate-query-subtract)
19487 (org-defkey org-agenda-mode-map "{" 'org-agenda-manipulate-query-add-re)
19488 (org-defkey org-agenda-mode-map "}" 'org-agenda-manipulate-query-subtract-re)
19490 (defvar org-agenda-keymap (copy-keymap org-agenda-mode-map)
19491 "Local keymap for agenda entries from Org-mode.")
19493 (org-defkey org-agenda-keymap
19494 (if (featurep 'xemacs) [(button2)] [(mouse-2)]) 'org-agenda-goto-mouse)
19495 (org-defkey org-agenda-keymap
19496 (if (featurep 'xemacs) [(button3)] [(mouse-3)]) 'org-agenda-show-mouse)
19497 (when org-agenda-mouse-1-follows-link
19498 (org-defkey org-agenda-keymap [follow-link] 'mouse-face))
19499 (easy-menu-define org-agenda-menu org-agenda-mode-map "Agenda menu"
19500 '("Agenda"
19501 ("Agenda Files")
19502 "--"
19503 ["Show" org-agenda-show t]
19504 ["Go To (other window)" org-agenda-goto t]
19505 ["Go To (this window)" org-agenda-switch-to t]
19506 ["Follow Mode" org-agenda-follow-mode
19507 :style toggle :selected org-agenda-follow-mode :active t]
19508 ["Tree to indirect frame" org-agenda-tree-to-indirect-buffer t]
19509 "--"
19510 ["Cycle TODO" org-agenda-todo t]
19511 ["Archive subtree" org-agenda-archive t]
19512 ["Delete subtree" org-agenda-kill t]
19513 "--"
19514 ["Goto Today" org-agenda-goto-today (org-agenda-check-type nil 'agenda 'timeline)]
19515 ["Next Dates" org-agenda-later (org-agenda-check-type nil 'agenda)]
19516 ["Previous Dates" org-agenda-earlier (org-agenda-check-type nil 'agenda)]
19517 ["Jump to date" org-agenda-goto-date (org-agenda-check-type nil 'agenda)]
19518 "--"
19519 ("Tags and Properties"
19520 ["Show all Tags" org-agenda-show-tags t]
19521 ["Set Tags current line" org-agenda-set-tags (not (org-region-active-p))]
19522 ["Change tag in region" org-agenda-set-tags (org-region-active-p)]
19523 "--"
19524 ["Column View" org-columns t])
19525 ("Date/Schedule"
19526 ["Schedule" org-agenda-schedule t]
19527 ["Set Deadline" org-agenda-deadline t]
19528 "--"
19529 ["Change Date +1 day" org-agenda-date-later (org-agenda-check-type nil 'agenda 'timeline)]
19530 ["Change Date -1 day" org-agenda-date-earlier (org-agenda-check-type nil 'agenda 'timeline)]
19531 ["Change Date to ..." org-agenda-date-prompt (org-agenda-check-type nil 'agenda 'timeline)])
19532 ("Clock"
19533 ["Clock in" org-agenda-clock-in t]
19534 ["Clock out" org-agenda-clock-out t]
19535 ["Clock cancel" org-agenda-clock-cancel t]
19536 ["Goto running clock" org-clock-goto t])
19537 ("Priority"
19538 ["Set Priority" org-agenda-priority t]
19539 ["Increase Priority" org-agenda-priority-up t]
19540 ["Decrease Priority" org-agenda-priority-down t]
19541 ["Show Priority" org-agenda-show-priority t])
19542 ("Calendar/Diary"
19543 ["New Diary Entry" org-agenda-diary-entry (org-agenda-check-type nil 'agenda 'timeline)]
19544 ["Goto Calendar" org-agenda-goto-calendar (org-agenda-check-type nil 'agenda 'timeline)]
19545 ["Phases of the Moon" org-agenda-phases-of-moon (org-agenda-check-type nil 'agenda 'timeline)]
19546 ["Sunrise/Sunset" org-agenda-sunrise-sunset (org-agenda-check-type nil 'agenda 'timeline)]
19547 ["Holidays" org-agenda-holidays (org-agenda-check-type nil 'agenda 'timeline)]
19548 ["Convert" org-agenda-convert-date (org-agenda-check-type nil 'agenda 'timeline)]
19549 "--"
19550 ["Create iCalendar file" org-export-icalendar-combine-agenda-files t])
19551 "--"
19552 ("View"
19553 ["Day View" org-agenda-day-view :active (org-agenda-check-type nil 'agenda)
19554 :style radio :selected (equal org-agenda-ndays 1)]
19555 ["Week View" org-agenda-week-view :active (org-agenda-check-type nil 'agenda)
19556 :style radio :selected (equal org-agenda-ndays 7)]
19557 ["Month View" org-agenda-month-view :active (org-agenda-check-type nil 'agenda)
19558 :style radio :selected (member org-agenda-ndays '(28 29 30 31))]
19559 ["Year View" org-agenda-year-view :active (org-agenda-check-type nil 'agenda)
19560 :style radio :selected (member org-agenda-ndays '(365 366))]
19561 "--"
19562 ["Show Logbook entries" org-agenda-log-mode
19563 :style toggle :selected org-agenda-show-log :active (org-agenda-check-type nil 'agenda 'timeline)]
19564 ["Include Diary" org-agenda-toggle-diary
19565 :style toggle :selected org-agenda-include-diary :active (org-agenda-check-type nil 'agenda)]
19566 ["Use Time Grid" org-agenda-toggle-time-grid
19567 :style toggle :selected org-agenda-use-time-grid :active (org-agenda-check-type nil 'agenda)])
19568 ["Write view to file" org-write-agenda t]
19569 ["Rebuild buffer" org-agenda-redo t]
19570 ["Save all Org-mode Buffers" org-save-all-org-buffers t]
19571 "--"
19572 ["Undo Remote Editing" org-agenda-undo org-agenda-undo-list]
19573 "--"
19574 ["Quit" org-agenda-quit t]
19575 ["Exit and Release Buffers" org-agenda-exit t]
19578 ;;; Agenda undo
19580 (defvar org-agenda-allow-remote-undo t
19581 "Non-nil means, allow remote undo from the agenda buffer.")
19582 (defvar org-agenda-undo-list nil
19583 "List of undoable operations in the agenda since last refresh.")
19584 (defvar org-agenda-undo-has-started-in nil
19585 "Buffers that have already seen `undo-start' in the current undo sequence.")
19586 (defvar org-agenda-pending-undo-list nil
19587 "In a series of undo commands, this is the list of remaning undo items.")
19589 (defmacro org-if-unprotected (&rest body)
19590 "Execute BODY if there is no `org-protected' text property at point."
19591 (declare (debug t))
19592 `(unless (get-text-property (point) 'org-protected)
19593 ,@body))
19595 (defmacro org-with-remote-undo (_buffer &rest _body)
19596 "Execute BODY while recording undo information in two buffers."
19597 (declare (indent 1) (debug t))
19598 `(let ((_cline (org-current-line))
19599 (_cmd this-command)
19600 (_buf1 (current-buffer))
19601 (_buf2 ,_buffer)
19602 (_undo1 buffer-undo-list)
19603 (_undo2 (with-current-buffer ,_buffer buffer-undo-list))
19604 _c1 _c2)
19605 ,@_body
19606 (when org-agenda-allow-remote-undo
19607 (setq _c1 (org-verify-change-for-undo
19608 _undo1 (with-current-buffer _buf1 buffer-undo-list))
19609 _c2 (org-verify-change-for-undo
19610 _undo2 (with-current-buffer _buf2 buffer-undo-list)))
19611 (when (or _c1 _c2)
19612 ;; make sure there are undo boundaries
19613 (and _c1 (with-current-buffer _buf1 (undo-boundary)))
19614 (and _c2 (with-current-buffer _buf2 (undo-boundary)))
19615 ;; remember which buffer to undo
19616 (push (list _cmd _cline _buf1 _c1 _buf2 _c2)
19617 org-agenda-undo-list)))))
19619 (defun org-agenda-undo ()
19620 "Undo a remote editing step in the agenda.
19621 This undoes changes both in the agenda buffer and in the remote buffer
19622 that have been changed along."
19623 (interactive)
19624 (or org-agenda-allow-remote-undo
19625 (error "Check the variable `org-agenda-allow-remote-undo' to activate remote undo."))
19626 (if (not (eq this-command last-command))
19627 (setq org-agenda-undo-has-started-in nil
19628 org-agenda-pending-undo-list org-agenda-undo-list))
19629 (if (not org-agenda-pending-undo-list)
19630 (error "No further undo information"))
19631 (let* ((entry (pop org-agenda-pending-undo-list))
19632 buf line cmd rembuf)
19633 (setq cmd (pop entry) line (pop entry))
19634 (setq rembuf (nth 2 entry))
19635 (org-with-remote-undo rembuf
19636 (while (bufferp (setq buf (pop entry)))
19637 (if (pop entry)
19638 (with-current-buffer buf
19639 (let ((last-undo-buffer buf)
19640 (inhibit-read-only t))
19641 (unless (memq buf org-agenda-undo-has-started-in)
19642 (push buf org-agenda-undo-has-started-in)
19643 (make-local-variable 'pending-undo-list)
19644 (undo-start))
19645 (while (and pending-undo-list
19646 (listp pending-undo-list)
19647 (not (car pending-undo-list)))
19648 (pop pending-undo-list))
19649 (undo-more 1))))))
19650 (goto-line line)
19651 (message "`%s' undone (buffer %s)" cmd (buffer-name rembuf))))
19653 (defun org-verify-change-for-undo (l1 l2)
19654 "Verify that a real change occurred between the undo lists L1 and L2."
19655 (while (and l1 (listp l1) (null (car l1))) (pop l1))
19656 (while (and l2 (listp l2) (null (car l2))) (pop l2))
19657 (not (eq l1 l2)))
19659 ;;; Agenda dispatch
19661 (defvar org-agenda-restrict nil)
19662 (defvar org-agenda-restrict-begin (make-marker))
19663 (defvar org-agenda-restrict-end (make-marker))
19664 (defvar org-agenda-last-dispatch-buffer nil)
19665 (defvar org-agenda-overriding-restriction nil)
19667 ;;;###autoload
19668 (defun org-agenda (arg &optional keys restriction)
19669 "Dispatch agenda commands to collect entries to the agenda buffer.
19670 Prompts for a command to execute. Any prefix arg will be passed
19671 on to the selected command. The default selections are:
19673 a Call `org-agenda-list' to display the agenda for current day or week.
19674 t Call `org-todo-list' to display the global todo list.
19675 T Call `org-todo-list' to display the global todo list, select only
19676 entries with a specific TODO keyword (the user gets a prompt).
19677 m Call `org-tags-view' to display headlines with tags matching
19678 a condition (the user is prompted for the condition).
19679 M Like `m', but select only TODO entries, no ordinary headlines.
19680 L Create a timeline for the current buffer.
19681 e Export views to associated files.
19683 More commands can be added by configuring the variable
19684 `org-agenda-custom-commands'. In particular, specific tags and TODO keyword
19685 searches can be pre-defined in this way.
19687 If the current buffer is in Org-mode and visiting a file, you can also
19688 first press `<' once to indicate that the agenda should be temporarily
19689 \(until the next use of \\[org-agenda]) restricted to the current file.
19690 Pressing `<' twice means to restrict to the current subtree or region
19691 \(if active)."
19692 (interactive "P")
19693 (catch 'exit
19694 (let* ((prefix-descriptions nil)
19695 (org-agenda-custom-commands-orig org-agenda-custom-commands)
19696 (org-agenda-custom-commands
19697 ;; normalize different versions
19698 (delq nil
19699 (mapcar
19700 (lambda (x)
19701 (cond ((stringp (cdr x))
19702 (push x prefix-descriptions)
19703 nil)
19704 ((stringp (nth 1 x)) x)
19705 ((not (nth 1 x)) (cons (car x) (cons "" (cddr x))))
19706 (t (cons (car x) (cons "" (cdr x))))))
19707 org-agenda-custom-commands)))
19708 (buf (current-buffer))
19709 (bfn (buffer-file-name (buffer-base-buffer)))
19710 entry key type match lprops ans)
19711 ;; Turn off restriction unless there is an overriding one
19712 (unless org-agenda-overriding-restriction
19713 (put 'org-agenda-files 'org-restrict nil)
19714 (setq org-agenda-restrict nil)
19715 (move-marker org-agenda-restrict-begin nil)
19716 (move-marker org-agenda-restrict-end nil))
19717 ;; Delete old local properties
19718 (put 'org-agenda-redo-command 'org-lprops nil)
19719 ;; Remember where this call originated
19720 (setq org-agenda-last-dispatch-buffer (current-buffer))
19721 (unless keys
19722 (setq ans (org-agenda-get-restriction-and-command prefix-descriptions)
19723 keys (car ans)
19724 restriction (cdr ans)))
19725 ;; Estabish the restriction, if any
19726 (when (and (not org-agenda-overriding-restriction) restriction)
19727 (put 'org-agenda-files 'org-restrict (list bfn))
19728 (cond
19729 ((eq restriction 'region)
19730 (setq org-agenda-restrict t)
19731 (move-marker org-agenda-restrict-begin (region-beginning))
19732 (move-marker org-agenda-restrict-end (region-end)))
19733 ((eq restriction 'subtree)
19734 (save-excursion
19735 (setq org-agenda-restrict t)
19736 (org-back-to-heading t)
19737 (move-marker org-agenda-restrict-begin (point))
19738 (move-marker org-agenda-restrict-end
19739 (progn (org-end-of-subtree t)))))))
19741 (require 'calendar) ; FIXME: can we avoid this for some commands?
19742 ;; For example the todo list should not need it (but does...)
19743 (cond
19744 ((setq entry (assoc keys org-agenda-custom-commands))
19745 (if (or (symbolp (nth 2 entry)) (functionp (nth 2 entry)))
19746 (progn
19747 (setq type (nth 2 entry) match (nth 3 entry) lprops (nth 4 entry))
19748 (put 'org-agenda-redo-command 'org-lprops lprops)
19749 (cond
19750 ((eq type 'agenda)
19751 (org-let lprops '(org-agenda-list current-prefix-arg)))
19752 ((eq type 'alltodo)
19753 (org-let lprops '(org-todo-list current-prefix-arg)))
19754 ((eq type 'search)
19755 (org-let lprops '(org-search-view current-prefix-arg match)))
19756 ((eq type 'stuck)
19757 (org-let lprops '(org-agenda-list-stuck-projects
19758 current-prefix-arg)))
19759 ((eq type 'tags)
19760 (org-let lprops '(org-tags-view current-prefix-arg match)))
19761 ((eq type 'tags-todo)
19762 (org-let lprops '(org-tags-view '(4) match)))
19763 ((eq type 'todo)
19764 (org-let lprops '(org-todo-list match)))
19765 ((eq type 'tags-tree)
19766 (org-check-for-org-mode)
19767 (org-let lprops '(org-tags-sparse-tree current-prefix-arg match)))
19768 ((eq type 'todo-tree)
19769 (org-check-for-org-mode)
19770 (org-let lprops
19771 '(org-occur (concat "^" outline-regexp "[ \t]*"
19772 (regexp-quote match) "\\>"))))
19773 ((eq type 'occur-tree)
19774 (org-check-for-org-mode)
19775 (org-let lprops '(org-occur match)))
19776 ((functionp type)
19777 (org-let lprops '(funcall type match)))
19778 ((fboundp type)
19779 (org-let lprops '(funcall type match)))
19780 (t (error "Invalid custom agenda command type %s" type))))
19781 (org-run-agenda-series (nth 1 entry) (cddr entry))))
19782 ((equal keys "C")
19783 (setq org-agenda-custom-commands org-agenda-custom-commands-orig)
19784 (customize-variable 'org-agenda-custom-commands))
19785 ((equal keys "a") (call-interactively 'org-agenda-list))
19786 ((equal keys "s") (call-interactively 'org-search-view))
19787 ((equal keys "t") (call-interactively 'org-todo-list))
19788 ((equal keys "T") (org-call-with-arg 'org-todo-list (or arg '(4))))
19789 ((equal keys "m") (call-interactively 'org-tags-view))
19790 ((equal keys "M") (org-call-with-arg 'org-tags-view (or arg '(4))))
19791 ((equal keys "e") (call-interactively 'org-store-agenda-views))
19792 ((equal keys "L")
19793 (unless (org-mode-p)
19794 (error "This is not an Org-mode file"))
19795 (unless restriction
19796 (put 'org-agenda-files 'org-restrict (list bfn))
19797 (org-call-with-arg 'org-timeline arg)))
19798 ((equal keys "#") (call-interactively 'org-agenda-list-stuck-projects))
19799 ((equal keys "/") (call-interactively 'org-occur-in-agenda-files))
19800 ((equal keys "!") (customize-variable 'org-stuck-projects))
19801 (t (error "Invalid agenda key"))))))
19803 (defun org-agenda-normalize-custom-commands (cmds)
19804 (delq nil
19805 (mapcar
19806 (lambda (x)
19807 (cond ((stringp (cdr x)) nil)
19808 ((stringp (nth 1 x)) x)
19809 ((not (nth 1 x)) (cons (car x) (cons "" (cddr x))))
19810 (t (cons (car x) (cons "" (cdr x))))))
19811 cmds)))
19813 (defun org-agenda-get-restriction-and-command (prefix-descriptions)
19814 "The user interface for selecting an agenda command."
19815 (catch 'exit
19816 (let* ((bfn (buffer-file-name (buffer-base-buffer)))
19817 (restrict-ok (and bfn (org-mode-p)))
19818 (region-p (org-region-active-p))
19819 (custom org-agenda-custom-commands)
19820 (selstring "")
19821 restriction second-time
19822 c entry key type match prefixes rmheader header-end custom1 desc)
19823 (save-window-excursion
19824 (delete-other-windows)
19825 (org-switch-to-buffer-other-window " *Agenda Commands*")
19826 (erase-buffer)
19827 (insert (eval-when-compile
19828 (let ((header
19830 Press key for an agenda command: < Buffer,subtree/region restriction
19831 -------------------------------- > Remove restriction
19832 a Agenda for current week or day e Export agenda views
19833 t List of all TODO entries T Entries with special TODO kwd
19834 m Match a TAGS query M Like m, but only TODO entries
19835 L Timeline for current buffer # List stuck projects (!=configure)
19836 s Search for keywords C Configure custom agenda commands
19837 / Multi-occur
19839 (start 0))
19840 (while (string-match
19841 "\\(^\\| \\|(\\)\\(\\S-\\)\\( \\|=\\)"
19842 header start)
19843 (setq start (match-end 0))
19844 (add-text-properties (match-beginning 2) (match-end 2)
19845 '(face bold) header))
19846 header)))
19847 (setq header-end (move-marker (make-marker) (point)))
19848 (while t
19849 (setq custom1 custom)
19850 (when (eq rmheader t)
19851 (goto-line 1)
19852 (re-search-forward ":" nil t)
19853 (delete-region (match-end 0) (point-at-eol))
19854 (forward-char 1)
19855 (looking-at "-+")
19856 (delete-region (match-end 0) (point-at-eol))
19857 (move-marker header-end (match-end 0)))
19858 (goto-char header-end)
19859 (delete-region (point) (point-max))
19860 (while (setq entry (pop custom1))
19861 (setq key (car entry) desc (nth 1 entry)
19862 type (nth 2 entry) match (nth 3 entry))
19863 (if (> (length key) 1)
19864 (add-to-list 'prefixes (string-to-char key))
19865 (insert
19866 (format
19867 "\n%-4s%-14s: %s"
19868 (org-add-props (copy-sequence key)
19869 '(face bold))
19870 (cond
19871 ((string-match "\\S-" desc) desc)
19872 ((eq type 'agenda) "Agenda for current week or day")
19873 ((eq type 'alltodo) "List of all TODO entries")
19874 ((eq type 'search) "Word search")
19875 ((eq type 'stuck) "List of stuck projects")
19876 ((eq type 'todo) "TODO keyword")
19877 ((eq type 'tags) "Tags query")
19878 ((eq type 'tags-todo) "Tags (TODO)")
19879 ((eq type 'tags-tree) "Tags tree")
19880 ((eq type 'todo-tree) "TODO kwd tree")
19881 ((eq type 'occur-tree) "Occur tree")
19882 ((functionp type) (if (symbolp type)
19883 (symbol-name type)
19884 "Lambda expression"))
19885 (t "???"))
19886 (cond
19887 ((stringp match)
19888 (org-add-props match nil 'face 'org-warning))
19889 (match
19890 (format "set of %d commands" (length match)))
19891 (t ""))))))
19892 (when prefixes
19893 (mapc (lambda (x)
19894 (insert
19895 (format "\n%s %s"
19896 (org-add-props (char-to-string x)
19897 nil 'face 'bold)
19898 (or (cdr (assoc (concat selstring (char-to-string x))
19899 prefix-descriptions))
19900 "Prefix key"))))
19901 prefixes))
19902 (goto-char (point-min))
19903 (when (fboundp 'fit-window-to-buffer)
19904 (if second-time
19905 (if (not (pos-visible-in-window-p (point-max)))
19906 (fit-window-to-buffer))
19907 (setq second-time t)
19908 (fit-window-to-buffer)))
19909 (message "Press key for agenda command%s:"
19910 (if (or restrict-ok org-agenda-overriding-restriction)
19911 (if org-agenda-overriding-restriction
19912 " (restriction lock active)"
19913 (if restriction
19914 (format " (restricted to %s)" restriction)
19915 " (unrestricted)"))
19916 ""))
19917 (setq c (read-char-exclusive))
19918 (message "")
19919 (cond
19920 ((assoc (char-to-string c) custom)
19921 (setq selstring (concat selstring (char-to-string c)))
19922 (throw 'exit (cons selstring restriction)))
19923 ((memq c prefixes)
19924 (setq selstring (concat selstring (char-to-string c))
19925 prefixes nil
19926 rmheader (or rmheader t)
19927 custom (delq nil (mapcar
19928 (lambda (x)
19929 (if (or (= (length (car x)) 1)
19930 (/= (string-to-char (car x)) c))
19932 (cons (substring (car x) 1) (cdr x))))
19933 custom))))
19934 ((and (not restrict-ok) (memq c '(?1 ?0 ?<)))
19935 (message "Restriction is only possible in Org-mode buffers")
19936 (ding) (sit-for 1))
19937 ((eq c ?1)
19938 (org-agenda-remove-restriction-lock 'noupdate)
19939 (setq restriction 'buffer))
19940 ((eq c ?0)
19941 (org-agenda-remove-restriction-lock 'noupdate)
19942 (setq restriction (if region-p 'region 'subtree)))
19943 ((eq c ?<)
19944 (org-agenda-remove-restriction-lock 'noupdate)
19945 (setq restriction
19946 (cond
19947 ((eq restriction 'buffer)
19948 (if region-p 'region 'subtree))
19949 ((memq restriction '(subtree region))
19950 nil)
19951 (t 'buffer))))
19952 ((eq c ?>)
19953 (org-agenda-remove-restriction-lock 'noupdate)
19954 (setq restriction nil))
19955 ((and (equal selstring "") (memq c '(?s ?a ?t ?m ?L ?C ?e ?T ?M ?# ?! ?/)))
19956 (throw 'exit (cons (setq selstring (char-to-string c)) restriction)))
19957 ((and (> (length selstring) 0) (eq c ?\d))
19958 (delete-window)
19959 (org-agenda-get-restriction-and-command prefix-descriptions))
19961 ((equal c ?q) (error "Abort"))
19962 (t (error "Invalid key %c" c))))))))
19964 (defun org-run-agenda-series (name series)
19965 (org-prepare-agenda name)
19966 (let* ((org-agenda-multi t)
19967 (redo (list 'org-run-agenda-series name (list 'quote series)))
19968 (cmds (car series))
19969 (gprops (nth 1 series))
19970 match ;; The byte compiler incorrectly complains about this. Keep it!
19971 cmd type lprops)
19972 (while (setq cmd (pop cmds))
19973 (setq type (car cmd) match (nth 1 cmd) lprops (nth 2 cmd))
19974 (cond
19975 ((eq type 'agenda)
19976 (org-let2 gprops lprops
19977 '(call-interactively 'org-agenda-list)))
19978 ((eq type 'alltodo)
19979 (org-let2 gprops lprops
19980 '(call-interactively 'org-todo-list)))
19981 ((eq type 'search)
19982 (org-let2 gprops lprops
19983 '(org-search-view current-prefix-arg match)))
19984 ((eq type 'stuck)
19985 (org-let2 gprops lprops
19986 '(call-interactively 'org-agenda-list-stuck-projects)))
19987 ((eq type 'tags)
19988 (org-let2 gprops lprops
19989 '(org-tags-view current-prefix-arg match)))
19990 ((eq type 'tags-todo)
19991 (org-let2 gprops lprops
19992 '(org-tags-view '(4) match)))
19993 ((eq type 'todo)
19994 (org-let2 gprops lprops
19995 '(org-todo-list match)))
19996 ((fboundp type)
19997 (org-let2 gprops lprops
19998 '(funcall type match)))
19999 (t (error "Invalid type in command series"))))
20000 (widen)
20001 (setq org-agenda-redo-command redo)
20002 (goto-char (point-min)))
20003 (org-finalize-agenda))
20005 ;;;###autoload
20006 (defmacro org-batch-agenda (cmd-key &rest parameters)
20007 "Run an agenda command in batch mode and send the result to STDOUT.
20008 If CMD-KEY is a string of length 1, it is used as a key in
20009 `org-agenda-custom-commands' and triggers this command. If it is a
20010 longer string it is used as a tags/todo match string.
20011 Paramters are alternating variable names and values that will be bound
20012 before running the agenda command."
20013 (let (pars)
20014 (while parameters
20015 (push (list (pop parameters) (if parameters (pop parameters))) pars))
20016 (if (> (length cmd-key) 2)
20017 (eval (list 'let (nreverse pars)
20018 (list 'org-tags-view nil cmd-key)))
20019 (eval (list 'let (nreverse pars) (list 'org-agenda nil cmd-key))))
20020 (set-buffer org-agenda-buffer-name)
20021 (princ (org-encode-for-stdout (buffer-string)))))
20023 (defun org-encode-for-stdout (string)
20024 (if (fboundp 'encode-coding-string)
20025 (encode-coding-string string buffer-file-coding-system)
20026 string))
20028 (defvar org-agenda-info nil)
20030 ;;;###autoload
20031 (defmacro org-batch-agenda-csv (cmd-key &rest parameters)
20032 "Run an agenda command in batch mode and send the result to STDOUT.
20033 If CMD-KEY is a string of length 1, it is used as a key in
20034 `org-agenda-custom-commands' and triggers this command. If it is a
20035 longer string it is used as a tags/todo match string.
20036 Paramters are alternating variable names and values that will be bound
20037 before running the agenda command.
20039 The output gives a line for each selected agenda item. Each
20040 item is a list of comma-separated values, like this:
20042 category,head,type,todo,tags,date,time,extra,priority-l,priority-n
20044 category The category of the item
20045 head The headline, without TODO kwd, TAGS and PRIORITY
20046 type The type of the agenda entry, can be
20047 todo selected in TODO match
20048 tagsmatch selected in tags match
20049 diary imported from diary
20050 deadline a deadline on given date
20051 scheduled scheduled on given date
20052 timestamp entry has timestamp on given date
20053 closed entry was closed on given date
20054 upcoming-deadline warning about deadline
20055 past-scheduled forwarded scheduled item
20056 block entry has date block including g. date
20057 todo The todo keyword, if any
20058 tags All tags including inherited ones, separated by colons
20059 date The relevant date, like 2007-2-14
20060 time The time, like 15:00-16:50
20061 extra Sting with extra planning info
20062 priority-l The priority letter if any was given
20063 priority-n The computed numerical priority
20064 agenda-day The day in the agenda where this is listed"
20066 (let (pars)
20067 (while parameters
20068 (push (list (pop parameters) (if parameters (pop parameters))) pars))
20069 (push (list 'org-agenda-remove-tags t) pars)
20070 (if (> (length cmd-key) 2)
20071 (eval (list 'let (nreverse pars)
20072 (list 'org-tags-view nil cmd-key)))
20073 (eval (list 'let (nreverse pars) (list 'org-agenda nil cmd-key))))
20074 (set-buffer org-agenda-buffer-name)
20075 (let* ((lines (org-split-string (buffer-string) "\n"))
20076 line)
20077 (while (setq line (pop lines))
20078 (catch 'next
20079 (if (not (get-text-property 0 'org-category line)) (throw 'next nil))
20080 (setq org-agenda-info
20081 (org-fix-agenda-info (text-properties-at 0 line)))
20082 (princ
20083 (org-encode-for-stdout
20084 (mapconcat 'org-agenda-export-csv-mapper
20085 '(org-category txt type todo tags date time-of-day extra
20086 priority-letter priority agenda-day)
20087 ",")))
20088 (princ "\n"))))))
20090 (defun org-fix-agenda-info (props)
20091 "Make sure all properties on an agenda item have a canonical form,
20092 so the export commands can easily use it."
20093 (let (tmp re)
20094 (when (setq tmp (plist-get props 'tags))
20095 (setq props (plist-put props 'tags (mapconcat 'identity tmp ":"))))
20096 (when (setq tmp (plist-get props 'date))
20097 (if (integerp tmp) (setq tmp (calendar-gregorian-from-absolute tmp)))
20098 (let ((calendar-date-display-form '(year "-" month "-" day)))
20099 '((format "%4d, %9s %2s, %4s" dayname monthname day year))
20101 (setq tmp (calendar-date-string tmp)))
20102 (setq props (plist-put props 'date tmp)))
20103 (when (setq tmp (plist-get props 'day))
20104 (if (integerp tmp) (setq tmp (calendar-gregorian-from-absolute tmp)))
20105 (let ((calendar-date-display-form '(year "-" month "-" day)))
20106 (setq tmp (calendar-date-string tmp)))
20107 (setq props (plist-put props 'day tmp))
20108 (setq props (plist-put props 'agenda-day tmp)))
20109 (when (setq tmp (plist-get props 'txt))
20110 (when (string-match "\\[#\\([A-Z0-9]\\)\\] ?" tmp)
20111 (plist-put props 'priority-letter (match-string 1 tmp))
20112 (setq tmp (replace-match "" t t tmp)))
20113 (when (and (setq re (plist-get props 'org-todo-regexp))
20114 (setq re (concat "\\`\\.*" re " ?"))
20115 (string-match re tmp))
20116 (plist-put props 'todo (match-string 1 tmp))
20117 (setq tmp (replace-match "" t t tmp)))
20118 (plist-put props 'txt tmp)))
20119 props)
20121 (defun org-agenda-export-csv-mapper (prop)
20122 (let ((res (plist-get org-agenda-info prop)))
20123 (setq res
20124 (cond
20125 ((not res) "")
20126 ((stringp res) res)
20127 (t (prin1-to-string res))))
20128 (while (string-match "," res)
20129 (setq res (replace-match ";" t t res)))
20130 (org-trim res)))
20133 ;;;###autoload
20134 (defun org-store-agenda-views (&rest parameters)
20135 (interactive)
20136 (eval (list 'org-batch-store-agenda-views)))
20138 ;; FIXME, why is this a macro?????
20139 ;;;###autoload
20140 (defmacro org-batch-store-agenda-views (&rest parameters)
20141 "Run all custom agenda commands that have a file argument."
20142 (let ((cmds (org-agenda-normalize-custom-commands org-agenda-custom-commands))
20143 (pop-up-frames nil)
20144 (dir default-directory)
20145 pars cmd thiscmdkey files opts)
20146 (while parameters
20147 (push (list (pop parameters) (if parameters (pop parameters))) pars))
20148 (setq pars (reverse pars))
20149 (save-window-excursion
20150 (while cmds
20151 (setq cmd (pop cmds)
20152 thiscmdkey (car cmd)
20153 opts (nth 4 cmd)
20154 files (nth 5 cmd))
20155 (if (stringp files) (setq files (list files)))
20156 (when files
20157 (eval (list 'let (append org-agenda-exporter-settings opts pars)
20158 (list 'org-agenda nil thiscmdkey)))
20159 (set-buffer org-agenda-buffer-name)
20160 (while files
20161 (eval (list 'let (append org-agenda-exporter-settings opts pars)
20162 (list 'org-write-agenda
20163 (expand-file-name (pop files) dir) t))))
20164 (and (get-buffer org-agenda-buffer-name)
20165 (kill-buffer org-agenda-buffer-name)))))))
20167 (defun org-write-agenda (file &optional nosettings)
20168 "Write the current buffer (an agenda view) as a file.
20169 Depending on the extension of the file name, plain text (.txt),
20170 HTML (.html or .htm) or Postscript (.ps) is produced.
20171 If NOSETTINGS is given, do not scope the settings of
20172 `org-agenda-exporter-settings' into the export commands. This is used when
20173 the settings have already been scoped and we do not wish to overrule other,
20174 higher priority settings."
20175 (interactive "FWrite agenda to file: ")
20176 (if (not (file-writable-p file))
20177 (error "Cannot write agenda to file %s" file))
20178 (cond
20179 ((string-match "\\.html?\\'" file) (require 'htmlize))
20180 ((string-match "\\.ps\\'" file) (require 'ps-print)))
20181 (org-let (if nosettings nil org-agenda-exporter-settings)
20182 '(save-excursion
20183 (save-window-excursion
20184 (cond
20185 ((string-match "\\.html?\\'" file)
20186 (set-buffer (htmlize-buffer (current-buffer)))
20188 (when (and org-agenda-export-html-style
20189 (string-match "<style>" org-agenda-export-html-style))
20190 ;; replace <style> section with org-agenda-export-html-style
20191 (goto-char (point-min))
20192 (kill-region (- (search-forward "<style") 6)
20193 (search-forward "</style>"))
20194 (insert org-agenda-export-html-style))
20195 (write-file file)
20196 (kill-buffer (current-buffer))
20197 (message "HTML written to %s" file))
20198 ((string-match "\\.ps\\'" file)
20199 (ps-print-buffer-with-faces file)
20200 (message "Postscript written to %s" file))
20202 (let ((bs (buffer-string)))
20203 (find-file file)
20204 (insert bs)
20205 (save-buffer 0)
20206 (kill-buffer (current-buffer))
20207 (message "Plain text written to %s" file))))))
20208 (set-buffer org-agenda-buffer-name)))
20210 (defmacro org-no-read-only (&rest body)
20211 "Inhibit read-only for BODY."
20212 `(let ((inhibit-read-only t)) ,@body))
20214 (defun org-check-for-org-mode ()
20215 "Make sure current buffer is in org-mode. Error if not."
20216 (or (org-mode-p)
20217 (error "Cannot execute org-mode agenda command on buffer in %s."
20218 major-mode)))
20220 (defun org-fit-agenda-window ()
20221 "Fit the window to the buffer size."
20222 (and (memq org-agenda-window-setup '(reorganize-frame))
20223 (fboundp 'fit-window-to-buffer)
20224 (fit-window-to-buffer
20226 (floor (* (frame-height) (cdr org-agenda-window-frame-fractions)))
20227 (floor (* (frame-height) (car org-agenda-window-frame-fractions))))))
20229 ;;; Agenda file list
20231 (defun org-agenda-files (&optional unrestricted)
20232 "Get the list of agenda files.
20233 Optional UNRESTRICTED means return the full list even if a restriction
20234 is currently in place."
20235 (let ((files
20236 (cond
20237 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
20238 ((stringp org-agenda-files) (org-read-agenda-file-list))
20239 ((listp org-agenda-files) org-agenda-files)
20240 (t (error "Invalid value of `org-agenda-files'")))))
20241 (setq files (apply 'append
20242 (mapcar (lambda (f)
20243 (if (file-directory-p f)
20244 (directory-files f t
20245 org-agenda-file-regexp)
20246 (list f)))
20247 files)))
20248 (if org-agenda-skip-unavailable-files
20249 (delq nil
20250 (mapcar (function
20251 (lambda (file)
20252 (and (file-readable-p file) file)))
20253 files))
20254 files))) ; `org-check-agenda-file' will remove them from the list
20256 (defun org-edit-agenda-file-list ()
20257 "Edit the list of agenda files.
20258 Depending on setup, this either uses customize to edit the variable
20259 `org-agenda-files', or it visits the file that is holding the list. In the
20260 latter case, the buffer is set up in a way that saving it automatically kills
20261 the buffer and restores the previous window configuration."
20262 (interactive)
20263 (if (stringp org-agenda-files)
20264 (let ((cw (current-window-configuration)))
20265 (find-file org-agenda-files)
20266 (org-set-local 'org-window-configuration cw)
20267 (org-add-hook 'after-save-hook
20268 (lambda ()
20269 (set-window-configuration
20270 (prog1 org-window-configuration
20271 (kill-buffer (current-buffer))))
20272 (org-install-agenda-files-menu)
20273 (message "New agenda file list installed"))
20274 nil 'local)
20275 (message "%s" (substitute-command-keys
20276 "Edit list and finish with \\[save-buffer]")))
20277 (customize-variable 'org-agenda-files)))
20279 (defun org-store-new-agenda-file-list (list)
20280 "Set new value for the agenda file list and save it correcly."
20281 (if (stringp org-agenda-files)
20282 (let ((f org-agenda-files) b)
20283 (while (setq b (find-buffer-visiting f)) (kill-buffer b))
20284 (with-temp-file f
20285 (insert (mapconcat 'identity list "\n") "\n")))
20286 (let ((org-mode-hook nil) (default-major-mode 'fundamental-mode))
20287 (setq org-agenda-files list)
20288 (customize-save-variable 'org-agenda-files org-agenda-files))))
20290 (defun org-read-agenda-file-list ()
20291 "Read the list of agenda files from a file."
20292 (when (stringp org-agenda-files)
20293 (with-temp-buffer
20294 (insert-file-contents org-agenda-files)
20295 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*"))))
20298 ;;;###autoload
20299 (defun org-cycle-agenda-files ()
20300 "Cycle through the files in `org-agenda-files'.
20301 If the current buffer visits an agenda file, find the next one in the list.
20302 If the current buffer does not, find the first agenda file."
20303 (interactive)
20304 (let* ((fs (org-agenda-files t))
20305 (files (append fs (list (car fs))))
20306 (tcf (if buffer-file-name (file-truename buffer-file-name)))
20307 file)
20308 (unless files (error "No agenda files"))
20309 (catch 'exit
20310 (while (setq file (pop files))
20311 (if (equal (file-truename file) tcf)
20312 (when (car files)
20313 (find-file (car files))
20314 (throw 'exit t))))
20315 (find-file (car fs)))
20316 (if (buffer-base-buffer) (switch-to-buffer (buffer-base-buffer)))))
20318 (defun org-agenda-file-to-front (&optional to-end)
20319 "Move/add the current file to the top of the agenda file list.
20320 If the file is not present in the list, it is added to the front. If it is
20321 present, it is moved there. With optional argument TO-END, add/move to the
20322 end of the list."
20323 (interactive "P")
20324 (let ((org-agenda-skip-unavailable-files nil)
20325 (file-alist (mapcar (lambda (x)
20326 (cons (file-truename x) x))
20327 (org-agenda-files t)))
20328 (ctf (file-truename buffer-file-name))
20329 x had)
20330 (setq x (assoc ctf file-alist) had x)
20332 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
20333 (if to-end
20334 (setq file-alist (append (delq x file-alist) (list x)))
20335 (setq file-alist (cons x (delq x file-alist))))
20336 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
20337 (org-install-agenda-files-menu)
20338 (message "File %s to %s of agenda file list"
20339 (if had "moved" "added") (if to-end "end" "front"))))
20341 (defun org-remove-file (&optional file)
20342 "Remove current file from the list of files in variable `org-agenda-files'.
20343 These are the files which are being checked for agenda entries.
20344 Optional argument FILE means, use this file instead of the current."
20345 (interactive)
20346 (let* ((org-agenda-skip-unavailable-files nil)
20347 (file (or file buffer-file-name))
20348 (true-file (file-truename file))
20349 (afile (abbreviate-file-name file))
20350 (files (delq nil (mapcar
20351 (lambda (x)
20352 (if (equal true-file
20353 (file-truename x))
20354 nil x))
20355 (org-agenda-files t)))))
20356 (if (not (= (length files) (length (org-agenda-files t))))
20357 (progn
20358 (org-store-new-agenda-file-list files)
20359 (org-install-agenda-files-menu)
20360 (message "Removed file: %s" afile))
20361 (message "File was not in list: %s (not removed)" afile))))
20363 (defun org-file-menu-entry (file)
20364 (vector file (list 'find-file file) t))
20366 (defun org-check-agenda-file (file)
20367 "Make sure FILE exists. If not, ask user what to do."
20368 (when (not (file-exists-p file))
20369 (message "non-existent file %s. [R]emove from list or [A]bort?"
20370 (abbreviate-file-name file))
20371 (let ((r (downcase (read-char-exclusive))))
20372 (cond
20373 ((equal r ?r)
20374 (org-remove-file file)
20375 (throw 'nextfile t))
20376 (t (error "Abort"))))))
20378 ;;; Agenda prepare and finalize
20380 (defvar org-agenda-multi nil) ; dynammically scoped
20381 (defvar org-agenda-buffer-name "*Org Agenda*")
20382 (defvar org-pre-agenda-window-conf nil)
20383 (defvar org-agenda-name nil)
20384 (defun org-prepare-agenda (&optional name)
20385 (setq org-todo-keywords-for-agenda nil)
20386 (setq org-done-keywords-for-agenda nil)
20387 (if org-agenda-multi
20388 (progn
20389 (setq buffer-read-only nil)
20390 (goto-char (point-max))
20391 (unless (or (bobp) org-agenda-compact-blocks)
20392 (insert "\n" (make-string (window-width) ?=) "\n"))
20393 (narrow-to-region (point) (point-max)))
20394 (org-agenda-reset-markers)
20395 (org-prepare-agenda-buffers (org-agenda-files))
20396 (setq org-todo-keywords-for-agenda
20397 (org-uniquify org-todo-keywords-for-agenda))
20398 (setq org-done-keywords-for-agenda
20399 (org-uniquify org-done-keywords-for-agenda))
20400 (let* ((abuf (get-buffer-create org-agenda-buffer-name))
20401 (awin (get-buffer-window abuf)))
20402 (cond
20403 ((equal (current-buffer) abuf) nil)
20404 (awin (select-window awin))
20405 ((not (setq org-pre-agenda-window-conf (current-window-configuration))))
20406 ((equal org-agenda-window-setup 'current-window)
20407 (switch-to-buffer abuf))
20408 ((equal org-agenda-window-setup 'other-window)
20409 (org-switch-to-buffer-other-window abuf))
20410 ((equal org-agenda-window-setup 'other-frame)
20411 (switch-to-buffer-other-frame abuf))
20412 ((equal org-agenda-window-setup 'reorganize-frame)
20413 (delete-other-windows)
20414 (org-switch-to-buffer-other-window abuf))))
20415 (setq buffer-read-only nil)
20416 (erase-buffer)
20417 (org-agenda-mode)
20418 (and name (not org-agenda-name)
20419 (org-set-local 'org-agenda-name name)))
20420 (setq buffer-read-only nil))
20422 (defun org-finalize-agenda ()
20423 "Finishing touch for the agenda buffer, called just before displaying it."
20424 (unless org-agenda-multi
20425 (save-excursion
20426 (let ((inhibit-read-only t))
20427 (goto-char (point-min))
20428 (while (org-activate-bracket-links (point-max))
20429 (add-text-properties (match-beginning 0) (match-end 0)
20430 '(face org-link)))
20431 (org-agenda-align-tags)
20432 (unless org-agenda-with-colors
20433 (remove-text-properties (point-min) (point-max) '(face nil))))
20434 (if (and (boundp 'org-overriding-columns-format)
20435 org-overriding-columns-format)
20436 (org-set-local 'org-overriding-columns-format
20437 org-overriding-columns-format))
20438 (if (and (boundp 'org-agenda-view-columns-initially)
20439 org-agenda-view-columns-initially)
20440 (org-agenda-columns))
20441 (when org-agenda-fontify-priorities
20442 (org-fontify-priorities))
20443 (run-hooks 'org-finalize-agenda-hook)
20444 (setq org-agenda-type (get-text-property (point) 'org-agenda-type))
20447 (defun org-fontify-priorities ()
20448 "Make highest priority lines bold, and lowest italic."
20449 (interactive)
20450 (mapc (lambda (o) (if (eq (org-overlay-get o 'org-type) 'org-priority)
20451 (org-delete-overlay o)))
20452 (org-overlays-in (point-min) (point-max)))
20453 (save-excursion
20454 (let ((inhibit-read-only t)
20455 b e p ov h l)
20456 (goto-char (point-min))
20457 (while (re-search-forward "\\[#\\(.\\)\\]" nil t)
20458 (setq h (or (get-char-property (point) 'org-highest-priority)
20459 org-highest-priority)
20460 l (or (get-char-property (point) 'org-lowest-priority)
20461 org-lowest-priority)
20462 p (string-to-char (match-string 1))
20463 b (match-beginning 0) e (point-at-eol)
20464 ov (org-make-overlay b e))
20465 (org-overlay-put
20466 ov 'face
20467 (cond ((listp org-agenda-fontify-priorities)
20468 (cdr (assoc p org-agenda-fontify-priorities)))
20469 ((equal p l) 'italic)
20470 ((equal p h) 'bold)))
20471 (org-overlay-put ov 'org-type 'org-priority)))))
20473 (defun org-prepare-agenda-buffers (files)
20474 "Create buffers for all agenda files, protect archived trees and comments."
20475 (interactive)
20476 (let ((pa '(:org-archived t))
20477 (pc '(:org-comment t))
20478 (pall '(:org-archived t :org-comment t))
20479 (inhibit-read-only t)
20480 (rea (concat ":" org-archive-tag ":"))
20481 bmp file re)
20482 (save-excursion
20483 (save-restriction
20484 (while (setq file (pop files))
20485 (if (bufferp file)
20486 (set-buffer file)
20487 (org-check-agenda-file file)
20488 (set-buffer (org-get-agenda-file-buffer file)))
20489 (widen)
20490 (setq bmp (buffer-modified-p))
20491 (org-refresh-category-properties)
20492 (setq org-todo-keywords-for-agenda
20493 (append org-todo-keywords-for-agenda org-todo-keywords-1))
20494 (setq org-done-keywords-for-agenda
20495 (append org-done-keywords-for-agenda org-done-keywords))
20496 (save-excursion
20497 (remove-text-properties (point-min) (point-max) pall)
20498 (when org-agenda-skip-archived-trees
20499 (goto-char (point-min))
20500 (while (re-search-forward rea nil t)
20501 (if (org-on-heading-p t)
20502 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
20503 (goto-char (point-min))
20504 (setq re (concat "^\\*+ +" org-comment-string "\\>"))
20505 (while (re-search-forward re nil t)
20506 (add-text-properties
20507 (match-beginning 0) (org-end-of-subtree t) pc)))
20508 (set-buffer-modified-p bmp))))))
20510 (defvar org-agenda-skip-function nil
20511 "Function to be called at each match during agenda construction.
20512 If this function returns nil, the current match should not be skipped.
20513 Otherwise, the function must return a position from where the search
20514 should be continued.
20515 This may also be a Lisp form, it will be evaluated.
20516 Never set this variable using `setq' or so, because then it will apply
20517 to all future agenda commands. Instead, bind it with `let' to scope
20518 it dynamically into the agenda-constructing command. A good way to set
20519 it is through options in org-agenda-custom-commands.")
20521 (defun org-agenda-skip ()
20522 "Throw to `:skip' in places that should be skipped.
20523 Also moves point to the end of the skipped region, so that search can
20524 continue from there."
20525 (let ((p (point-at-bol)) to fp)
20526 (and org-agenda-skip-archived-trees
20527 (get-text-property p :org-archived)
20528 (org-end-of-subtree t)
20529 (throw :skip t))
20530 (and (get-text-property p :org-comment)
20531 (org-end-of-subtree t)
20532 (throw :skip t))
20533 (if (equal (char-after p) ?#) (throw :skip t))
20534 (when (and (or (setq fp (functionp org-agenda-skip-function))
20535 (consp org-agenda-skip-function))
20536 (setq to (save-excursion
20537 (save-match-data
20538 (if fp
20539 (funcall org-agenda-skip-function)
20540 (eval org-agenda-skip-function))))))
20541 (goto-char to)
20542 (throw :skip t))))
20544 (defvar org-agenda-markers nil
20545 "List of all currently active markers created by `org-agenda'.")
20546 (defvar org-agenda-last-marker-time (time-to-seconds (current-time))
20547 "Creation time of the last agenda marker.")
20549 (defun org-agenda-new-marker (&optional pos)
20550 "Return a new agenda marker.
20551 Org-mode keeps a list of these markers and resets them when they are
20552 no longer in use."
20553 (let ((m (copy-marker (or pos (point)))))
20554 (setq org-agenda-last-marker-time (time-to-seconds (current-time)))
20555 (push m org-agenda-markers)
20558 (defun org-agenda-reset-markers ()
20559 "Reset markers created by `org-agenda'."
20560 (while org-agenda-markers
20561 (move-marker (pop org-agenda-markers) nil)))
20563 (defun org-get-agenda-file-buffer (file)
20564 "Get a buffer visiting FILE. If the buffer needs to be created, add
20565 it to the list of buffers which might be released later."
20566 (let ((buf (org-find-base-buffer-visiting file)))
20567 (if buf
20568 buf ; just return it
20569 ;; Make a new buffer and remember it
20570 (setq buf (find-file-noselect file))
20571 (if buf (push buf org-agenda-new-buffers))
20572 buf)))
20574 (defun org-release-buffers (blist)
20575 "Release all buffers in list, asking the user for confirmation when needed.
20576 When a buffer is unmodified, it is just killed. When modified, it is saved
20577 \(if the user agrees) and then killed."
20578 (let (buf file)
20579 (while (setq buf (pop blist))
20580 (setq file (buffer-file-name buf))
20581 (when (and (buffer-modified-p buf)
20582 file
20583 (y-or-n-p (format "Save file %s? " file)))
20584 (with-current-buffer buf (save-buffer)))
20585 (kill-buffer buf))))
20587 (defun org-get-category (&optional pos)
20588 "Get the category applying to position POS."
20589 (get-text-property (or pos (point)) 'org-category))
20591 ;;; Agenda timeline
20593 (defvar org-agenda-only-exact-dates nil) ; dynamically scoped
20595 (defun org-timeline (&optional include-all)
20596 "Show a time-sorted view of the entries in the current org file.
20597 Only entries with a time stamp of today or later will be listed. With
20598 \\[universal-argument] prefix, all unfinished TODO items will also be shown,
20599 under the current date.
20600 If the buffer contains an active region, only check the region for
20601 dates."
20602 (interactive "P")
20603 (require 'calendar)
20604 (org-compile-prefix-format 'timeline)
20605 (org-set-sorting-strategy 'timeline)
20606 (let* ((dopast t)
20607 (dotodo include-all)
20608 (doclosed org-agenda-show-log)
20609 (entry buffer-file-name)
20610 (date (calendar-current-date))
20611 (beg (if (org-region-active-p) (region-beginning) (point-min)))
20612 (end (if (org-region-active-p) (region-end) (point-max)))
20613 (day-numbers (org-get-all-dates beg end 'no-ranges
20614 t doclosed ; always include today
20615 org-timeline-show-empty-dates))
20616 (org-deadline-warning-days 0)
20617 (org-agenda-only-exact-dates t)
20618 (today (time-to-days (current-time)))
20619 (past t)
20620 args
20621 s e rtn d emptyp)
20622 (setq org-agenda-redo-command
20623 (list 'progn
20624 (list 'org-switch-to-buffer-other-window (current-buffer))
20625 (list 'org-timeline (list 'quote include-all))))
20626 (if (not dopast)
20627 ;; Remove past dates from the list of dates.
20628 (setq day-numbers (delq nil (mapcar (lambda(x)
20629 (if (>= x today) x nil))
20630 day-numbers))))
20631 (org-prepare-agenda (concat "Timeline "
20632 (file-name-nondirectory buffer-file-name)))
20633 (if doclosed (push :closed args))
20634 (push :timestamp args)
20635 (push :deadline args)
20636 (push :scheduled args)
20637 (push :sexp args)
20638 (if dotodo (push :todo args))
20639 (while (setq d (pop day-numbers))
20640 (if (and (listp d) (eq (car d) :omitted))
20641 (progn
20642 (setq s (point))
20643 (insert (format "\n[... %d empty days omitted]\n\n" (cdr d)))
20644 (put-text-property s (1- (point)) 'face 'org-agenda-structure))
20645 (if (listp d) (setq d (car d) emptyp t) (setq emptyp nil))
20646 (if (and (>= d today)
20647 dopast
20648 past)
20649 (progn
20650 (setq past nil)
20651 (insert (make-string 79 ?-) "\n")))
20652 (setq date (calendar-gregorian-from-absolute d))
20653 (setq s (point))
20654 (setq rtn (and (not emptyp)
20655 (apply 'org-agenda-get-day-entries entry
20656 date args)))
20657 (if (or rtn (equal d today) org-timeline-show-empty-dates)
20658 (progn
20659 (insert
20660 (if (stringp org-agenda-format-date)
20661 (format-time-string org-agenda-format-date
20662 (org-time-from-absolute date))
20663 (funcall org-agenda-format-date date))
20664 "\n")
20665 (put-text-property s (1- (point)) 'face 'org-agenda-structure)
20666 (put-text-property s (1- (point)) 'org-date-line t)
20667 (if (equal d today)
20668 (put-text-property s (1- (point)) 'org-today t))
20669 (and rtn (insert (org-finalize-agenda-entries rtn) "\n"))
20670 (put-text-property s (1- (point)) 'day d)))))
20671 (goto-char (point-min))
20672 (goto-char (or (text-property-any (point-min) (point-max) 'org-today t)
20673 (point-min)))
20674 (add-text-properties (point-min) (point-max) '(org-agenda-type timeline))
20675 (org-finalize-agenda)
20676 (setq buffer-read-only t)))
20678 (defun org-get-all-dates (beg end &optional no-ranges force-today inactive empty pre-re)
20679 "Return a list of all relevant day numbers from BEG to END buffer positions.
20680 If NO-RANGES is non-nil, include only the start and end dates of a range,
20681 not every single day in the range. If FORCE-TODAY is non-nil, make
20682 sure that TODAY is included in the list. If INACTIVE is non-nil, also
20683 inactive time stamps (those in square brackets) are included.
20684 When EMPTY is non-nil, also include days without any entries."
20685 (let ((re (concat
20686 (if pre-re pre-re "")
20687 (if inactive org-ts-regexp-both org-ts-regexp)))
20688 dates dates1 date day day1 day2 ts1 ts2)
20689 (if force-today
20690 (setq dates (list (time-to-days (current-time)))))
20691 (save-excursion
20692 (goto-char beg)
20693 (while (re-search-forward re end t)
20694 (setq day (time-to-days (org-time-string-to-time
20695 (substring (match-string 1) 0 10))))
20696 (or (memq day dates) (push day dates)))
20697 (unless no-ranges
20698 (goto-char beg)
20699 (while (re-search-forward org-tr-regexp end t)
20700 (setq ts1 (substring (match-string 1) 0 10)
20701 ts2 (substring (match-string 2) 0 10)
20702 day1 (time-to-days (org-time-string-to-time ts1))
20703 day2 (time-to-days (org-time-string-to-time ts2)))
20704 (while (< (setq day1 (1+ day1)) day2)
20705 (or (memq day1 dates) (push day1 dates)))))
20706 (setq dates (sort dates '<))
20707 (when empty
20708 (while (setq day (pop dates))
20709 (setq day2 (car dates))
20710 (push day dates1)
20711 (when (and day2 empty)
20712 (if (or (eq empty t)
20713 (and (numberp empty) (<= (- day2 day) empty)))
20714 (while (< (setq day (1+ day)) day2)
20715 (push (list day) dates1))
20716 (push (cons :omitted (- day2 day)) dates1))))
20717 (setq dates (nreverse dates1)))
20718 dates)))
20720 ;;; Agenda Daily/Weekly
20722 (defvar org-agenda-overriding-arguments nil) ; dynamically scoped parameter
20723 (defvar org-agenda-start-day nil) ; dynamically scoped parameter
20724 (defvar org-agenda-last-arguments nil
20725 "The arguments of the previous call to org-agenda")
20726 (defvar org-starting-day nil) ; local variable in the agenda buffer
20727 (defvar org-agenda-span nil) ; local variable in the agenda buffer
20728 (defvar org-include-all-loc nil) ; local variable
20729 (defvar org-agenda-remove-date nil) ; dynamically scoped
20731 ;;;###autoload
20732 (defun org-agenda-list (&optional include-all start-day ndays)
20733 "Produce a daily/weekly view from all files in variable `org-agenda-files'.
20734 The view will be for the current day or week, but from the overview buffer
20735 you will be able to go to other days/weeks.
20737 With one \\[universal-argument] prefix argument INCLUDE-ALL,
20738 all unfinished TODO items will also be shown, before the agenda.
20739 This feature is considered obsolete, please use the TODO list or a block
20740 agenda instead.
20742 With a numeric prefix argument in an interactive call, the agenda will
20743 span INCLUDE-ALL days. Lisp programs should instead specify NDAYS to change
20744 the number of days. NDAYS defaults to `org-agenda-ndays'.
20746 START-DAY defaults to TODAY, or to the most recent match for the weekday
20747 given in `org-agenda-start-on-weekday'."
20748 (interactive "P")
20749 (if (and (integerp include-all) (> include-all 0))
20750 (setq ndays include-all include-all nil))
20751 (setq ndays (or ndays org-agenda-ndays)
20752 start-day (or start-day org-agenda-start-day))
20753 (if org-agenda-overriding-arguments
20754 (setq include-all (car org-agenda-overriding-arguments)
20755 start-day (nth 1 org-agenda-overriding-arguments)
20756 ndays (nth 2 org-agenda-overriding-arguments)))
20757 (if (stringp start-day)
20758 ;; Convert to an absolute day number
20759 (setq start-day (time-to-days (org-read-date nil t start-day))))
20760 (setq org-agenda-last-arguments (list include-all start-day ndays))
20761 (org-compile-prefix-format 'agenda)
20762 (org-set-sorting-strategy 'agenda)
20763 (require 'calendar)
20764 (let* ((org-agenda-start-on-weekday
20765 (if (or (equal ndays 7) (and (null ndays) (equal 7 org-agenda-ndays)))
20766 org-agenda-start-on-weekday nil))
20767 (thefiles (org-agenda-files))
20768 (files thefiles)
20769 (today (time-to-days
20770 (time-subtract (current-time)
20771 (list 0 (* 3600 org-extend-today-until) 0))))
20772 (sd (or start-day today))
20773 (start (if (or (null org-agenda-start-on-weekday)
20774 (< org-agenda-ndays 7))
20776 (let* ((nt (calendar-day-of-week
20777 (calendar-gregorian-from-absolute sd)))
20778 (n1 org-agenda-start-on-weekday)
20779 (d (- nt n1)))
20780 (- sd (+ (if (< d 0) 7 0) d)))))
20781 (day-numbers (list start))
20782 (day-cnt 0)
20783 (inhibit-redisplay (not debug-on-error))
20784 s e rtn rtnall file date d start-pos end-pos todayp nd)
20785 (setq org-agenda-redo-command
20786 (list 'org-agenda-list (list 'quote include-all) start-day ndays))
20787 ;; Make the list of days
20788 (setq ndays (or ndays org-agenda-ndays)
20789 nd ndays)
20790 (while (> ndays 1)
20791 (push (1+ (car day-numbers)) day-numbers)
20792 (setq ndays (1- ndays)))
20793 (setq day-numbers (nreverse day-numbers))
20794 (org-prepare-agenda "Day/Week")
20795 (org-set-local 'org-starting-day (car day-numbers))
20796 (org-set-local 'org-include-all-loc include-all)
20797 (org-set-local 'org-agenda-span
20798 (org-agenda-ndays-to-span nd))
20799 (when (and (or include-all org-agenda-include-all-todo)
20800 (member today day-numbers))
20801 (setq files thefiles
20802 rtnall nil)
20803 (while (setq file (pop files))
20804 (catch 'nextfile
20805 (org-check-agenda-file file)
20806 (setq date (calendar-gregorian-from-absolute today)
20807 rtn (org-agenda-get-day-entries
20808 file date :todo))
20809 (setq rtnall (append rtnall rtn))))
20810 (when rtnall
20811 (insert "ALL CURRENTLY OPEN TODO ITEMS:\n")
20812 (add-text-properties (point-min) (1- (point))
20813 (list 'face 'org-agenda-structure))
20814 (insert (org-finalize-agenda-entries rtnall) "\n")))
20815 (unless org-agenda-compact-blocks
20816 (setq s (point))
20817 (insert (capitalize (symbol-name (org-agenda-ndays-to-span nd)))
20818 "-agenda:\n")
20819 (add-text-properties s (1- (point)) (list 'face 'org-agenda-structure
20820 'org-date-line t)))
20821 (while (setq d (pop day-numbers))
20822 (setq date (calendar-gregorian-from-absolute d)
20823 s (point))
20824 (if (or (setq todayp (= d today))
20825 (and (not start-pos) (= d sd)))
20826 (setq start-pos (point))
20827 (if (and start-pos (not end-pos))
20828 (setq end-pos (point))))
20829 (setq files thefiles
20830 rtnall nil)
20831 (while (setq file (pop files))
20832 (catch 'nextfile
20833 (org-check-agenda-file file)
20834 (if org-agenda-show-log
20835 (setq rtn (org-agenda-get-day-entries
20836 file date
20837 :deadline :scheduled :timestamp :sexp :closed))
20838 (setq rtn (org-agenda-get-day-entries
20839 file date
20840 :deadline :scheduled :sexp :timestamp)))
20841 (setq rtnall (append rtnall rtn))))
20842 (if org-agenda-include-diary
20843 (progn
20844 (require 'diary-lib)
20845 (setq rtn (org-get-entries-from-diary date))
20846 (setq rtnall (append rtnall rtn))))
20847 (if (or rtnall org-agenda-show-all-dates)
20848 (progn
20849 (setq day-cnt (1+ day-cnt))
20850 (insert
20851 (if (stringp org-agenda-format-date)
20852 (format-time-string org-agenda-format-date
20853 (org-time-from-absolute date))
20854 (funcall org-agenda-format-date date))
20855 "\n")
20856 (put-text-property s (1- (point)) 'face 'org-agenda-structure)
20857 (put-text-property s (1- (point)) 'org-date-line t)
20858 (put-text-property s (1- (point)) 'org-day-cnt day-cnt)
20859 (if todayp (put-text-property s (1- (point)) 'org-today t))
20860 (if rtnall (insert
20861 (org-finalize-agenda-entries
20862 (org-agenda-add-time-grid-maybe
20863 rtnall nd todayp))
20864 "\n"))
20865 (put-text-property s (1- (point)) 'day d)
20866 (put-text-property s (1- (point)) 'org-day-cnt day-cnt))))
20867 (goto-char (point-min))
20868 (org-fit-agenda-window)
20869 (unless (and (pos-visible-in-window-p (point-min))
20870 (pos-visible-in-window-p (point-max)))
20871 (goto-char (1- (point-max)))
20872 (recenter -1)
20873 (if (not (pos-visible-in-window-p (or start-pos 1)))
20874 (progn
20875 (goto-char (or start-pos 1))
20876 (recenter 1))))
20877 (goto-char (or start-pos 1))
20878 (add-text-properties (point-min) (point-max) '(org-agenda-type agenda))
20879 (org-finalize-agenda)
20880 (setq buffer-read-only t)
20881 (message "")))
20883 (defun org-agenda-ndays-to-span (n)
20884 (cond ((< n 7) 'day) ((= n 7) 'week) ((< n 32) 'month) (t 'year)))
20886 ;;; Agenda word search
20888 (defvar org-agenda-search-history nil)
20890 ;;;###autoload
20891 (defun org-search-view (&optional arg string)
20892 "Show all entries that contain words or regular expressions.
20893 If the first character of the search string is an asterisks,
20894 search only the headlines.
20896 The search string is broken into \"words\" by splitting at whitespace.
20897 The individual words are then interpreted as a boolean expression with
20898 logical AND. Words prefixed with a minus must not occur in the entry.
20899 Words without a prefix or prefixed with a plus must occur in the entry.
20900 Matching is case-insensitive and the words are enclosed by word delimiters.
20902 Words enclosed by curly braces are interpreted as regular expressions
20903 that must or must not match in the entry.
20905 This command searches the agenda files, and in addition the files listed
20906 in `org-agenda-text-search-extra-files'."
20907 (interactive "P")
20908 (org-compile-prefix-format 'search)
20909 (org-set-sorting-strategy 'search)
20910 (org-prepare-agenda "SEARCH")
20911 (let* ((props (list 'face nil
20912 'done-face 'org-done
20913 'org-not-done-regexp org-not-done-regexp
20914 'org-todo-regexp org-todo-regexp
20915 'mouse-face 'highlight
20916 'keymap org-agenda-keymap
20917 'help-echo (format "mouse-2 or RET jump to location")))
20918 regexp rtn rtnall files file pos
20919 marker priority category tags c neg re
20920 ee txt beg end words regexps+ regexps- hdl-only buffer beg1 str)
20921 (unless (and (not arg)
20922 (stringp string)
20923 (string-match "\\S-" string))
20924 (setq string (read-string "[+-]Word/{Regexp} ...: "
20925 (cond
20926 ((integerp arg) (cons string arg))
20927 (arg string))
20928 'org-agenda-search-history)))
20929 (setq org-agenda-redo-command
20930 (list 'org-search-view 'current-prefix-arg string))
20931 (setq org-agenda-query-string string)
20933 (if (equal (string-to-char string) ?*)
20934 (setq hdl-only t
20935 words (substring string 1))
20936 (setq words string))
20937 (setq words (org-split-string words))
20938 (mapc (lambda (w)
20939 (setq c (string-to-char w))
20940 (if (equal c ?-)
20941 (setq neg t w (substring w 1))
20942 (if (equal c ?+)
20943 (setq neg nil w (substring w 1))
20944 (setq neg nil)))
20945 (if (string-match "\\`{.*}\\'" w)
20946 (setq re (substring w 1 -1))
20947 (setq re (concat "\\<" (regexp-quote (downcase w)) "\\>")))
20948 (if neg (push re regexps-) (push re regexps+)))
20949 words)
20950 (setq regexps+ (sort regexps+ (lambda (a b) (> (length a) (length b)))))
20951 (if (not regexps+)
20952 (setq regexp (concat "^" org-outline-regexp))
20953 (setq regexp (pop regexps+))
20954 (if hdl-only (setq regexp (concat "^" org-outline-regexp ".*?"
20955 regexp))))
20956 (setq files (append (org-agenda-files) org-agenda-text-search-extra-files)
20957 rtnall nil)
20958 (while (setq file (pop files))
20959 (setq ee nil)
20960 (catch 'nextfile
20961 (org-check-agenda-file file)
20962 (setq buffer (if (file-exists-p file)
20963 (org-get-agenda-file-buffer file)
20964 (error "No such file %s" file)))
20965 (if (not buffer)
20966 ;; If file does not exist, make sure an error message is sent
20967 (setq rtn (list (format "ORG-AGENDA-ERROR: No such org-file %s"
20968 file))))
20969 (with-current-buffer buffer
20970 (unless (org-mode-p)
20971 (error "Agenda file %s is not in `org-mode'" file))
20972 (let ((case-fold-search t))
20973 (save-excursion
20974 (save-restriction
20975 (if org-agenda-restrict
20976 (narrow-to-region org-agenda-restrict-begin
20977 org-agenda-restrict-end)
20978 (widen))
20979 (goto-char (point-min))
20980 (unless (or (org-on-heading-p)
20981 (outline-next-heading))
20982 (throw 'nextfile t))
20983 (goto-char (max (point-min) (1- (point))))
20984 (while (re-search-forward regexp nil t)
20985 (org-back-to-heading t)
20986 (skip-chars-forward "* ")
20987 (setq beg (point-at-bol)
20988 beg1 (point)
20989 end (progn (outline-next-heading) (point)))
20990 (catch :skip
20991 (goto-char beg)
20992 (org-agenda-skip)
20993 (setq str (buffer-substring-no-properties
20994 (point-at-bol)
20995 (if hdl-only (point-at-eol) end)))
20996 (mapc (lambda (wr) (when (string-match wr str)
20997 (goto-char (1- end))
20998 (throw :skip t)))
20999 regexps-)
21000 (mapc (lambda (wr) (unless (string-match wr str)
21001 (goto-char (1- end))
21002 (throw :skip t)))
21003 regexps+)
21004 (goto-char beg)
21005 (setq marker (org-agenda-new-marker (point))
21006 category (org-get-category)
21007 tags (org-get-tags-at (point))
21008 txt (org-format-agenda-item
21010 (buffer-substring-no-properties
21011 beg1 (point-at-eol))
21012 category tags))
21013 (org-add-props txt props
21014 'org-marker marker 'org-hd-marker marker
21015 'priority 1000 'org-category category
21016 'type "search")
21017 (push txt ee)
21018 (goto-char (1- end)))))))))
21019 (setq rtn (nreverse ee))
21020 (setq rtnall (append rtnall rtn)))
21021 (if org-agenda-overriding-header
21022 (insert (org-add-props (copy-sequence org-agenda-overriding-header)
21023 nil 'face 'org-agenda-structure) "\n")
21024 (insert "Search words: ")
21025 (add-text-properties (point-min) (1- (point))
21026 (list 'face 'org-agenda-structure))
21027 (setq pos (point))
21028 (insert string "\n")
21029 (add-text-properties pos (1- (point)) (list 'face 'org-warning))
21030 (setq pos (point))
21031 (unless org-agenda-multi
21032 (insert "Press `[', `]' to add/sub word, `{', `}' to add/sub regexp, `C-u r' to edit\n")
21033 (add-text-properties pos (1- (point))
21034 (list 'face 'org-agenda-structure))))
21035 (when rtnall
21036 (insert (org-finalize-agenda-entries rtnall) "\n"))
21037 (goto-char (point-min))
21038 (org-fit-agenda-window)
21039 (add-text-properties (point-min) (point-max) '(org-agenda-type search))
21040 (org-finalize-agenda)
21041 (setq buffer-read-only t)))
21043 ;;; Agenda TODO list
21045 (defvar org-select-this-todo-keyword nil)
21046 (defvar org-last-arg nil)
21048 ;;;###autoload
21049 (defun org-todo-list (arg)
21050 "Show all TODO entries from all agenda file in a single list.
21051 The prefix arg can be used to select a specific TODO keyword and limit
21052 the list to these. When using \\[universal-argument], you will be prompted
21053 for a keyword. A numeric prefix directly selects the Nth keyword in
21054 `org-todo-keywords-1'."
21055 (interactive "P")
21056 (require 'calendar)
21057 (org-compile-prefix-format 'todo)
21058 (org-set-sorting-strategy 'todo)
21059 (org-prepare-agenda "TODO")
21060 (let* ((today (time-to-days (current-time)))
21061 (date (calendar-gregorian-from-absolute today))
21062 (kwds org-todo-keywords-for-agenda)
21063 (completion-ignore-case t)
21064 (org-select-this-todo-keyword
21065 (if (stringp arg) arg
21066 (and arg (integerp arg) (> arg 0)
21067 (nth (1- arg) kwds))))
21068 rtn rtnall files file pos)
21069 (when (equal arg '(4))
21070 (setq org-select-this-todo-keyword
21071 (completing-read "Keyword (or KWD1|K2D2|...): "
21072 (mapcar 'list kwds) nil nil)))
21073 (and (equal 0 arg) (setq org-select-this-todo-keyword nil))
21074 (org-set-local 'org-last-arg arg)
21075 (setq org-agenda-redo-command
21076 '(org-todo-list (or current-prefix-arg org-last-arg)))
21077 (setq files (org-agenda-files)
21078 rtnall nil)
21079 (while (setq file (pop files))
21080 (catch 'nextfile
21081 (org-check-agenda-file file)
21082 (setq rtn (org-agenda-get-day-entries file date :todo))
21083 (setq rtnall (append rtnall rtn))))
21084 (if org-agenda-overriding-header
21085 (insert (org-add-props (copy-sequence org-agenda-overriding-header)
21086 nil 'face 'org-agenda-structure) "\n")
21087 (insert "Global list of TODO items of type: ")
21088 (add-text-properties (point-min) (1- (point))
21089 (list 'face 'org-agenda-structure))
21090 (setq pos (point))
21091 (insert (or org-select-this-todo-keyword "ALL") "\n")
21092 (add-text-properties pos (1- (point)) (list 'face 'org-warning))
21093 (setq pos (point))
21094 (unless org-agenda-multi
21095 (insert "Available with `N r': (0)ALL")
21096 (let ((n 0) s)
21097 (mapc (lambda (x)
21098 (setq s (format "(%d)%s" (setq n (1+ n)) x))
21099 (if (> (+ (current-column) (string-width s) 1) (frame-width))
21100 (insert "\n "))
21101 (insert " " s))
21102 kwds))
21103 (insert "\n"))
21104 (add-text-properties pos (1- (point)) (list 'face 'org-agenda-structure)))
21105 (when rtnall
21106 (insert (org-finalize-agenda-entries rtnall) "\n"))
21107 (goto-char (point-min))
21108 (org-fit-agenda-window)
21109 (add-text-properties (point-min) (point-max) '(org-agenda-type todo))
21110 (org-finalize-agenda)
21111 (setq buffer-read-only t)))
21113 ;;; Agenda tags match
21115 ;;;###autoload
21116 (defun org-tags-view (&optional todo-only match)
21117 "Show all headlines for all `org-agenda-files' matching a TAGS criterion.
21118 The prefix arg TODO-ONLY limits the search to TODO entries."
21119 (interactive "P")
21120 (org-compile-prefix-format 'tags)
21121 (org-set-sorting-strategy 'tags)
21122 (let* ((org-tags-match-list-sublevels
21123 (if todo-only t org-tags-match-list-sublevels))
21124 (completion-ignore-case t)
21125 rtn rtnall files file pos matcher
21126 buffer)
21127 (setq matcher (org-make-tags-matcher match)
21128 match (car matcher) matcher (cdr matcher))
21129 (org-prepare-agenda (concat "TAGS " match))
21130 (setq org-agenda-redo-command
21131 (list 'org-tags-view (list 'quote todo-only)
21132 (list 'if 'current-prefix-arg nil match)))
21133 (setq files (org-agenda-files)
21134 rtnall nil)
21135 (while (setq file (pop files))
21136 (catch 'nextfile
21137 (org-check-agenda-file file)
21138 (setq buffer (if (file-exists-p file)
21139 (org-get-agenda-file-buffer file)
21140 (error "No such file %s" file)))
21141 (if (not buffer)
21142 ;; If file does not exist, merror message to agenda
21143 (setq rtn (list
21144 (format "ORG-AGENDA-ERROR: No such org-file %s" file))
21145 rtnall (append rtnall rtn))
21146 (with-current-buffer buffer
21147 (unless (org-mode-p)
21148 (error "Agenda file %s is not in `org-mode'" file))
21149 (save-excursion
21150 (save-restriction
21151 (if org-agenda-restrict
21152 (narrow-to-region org-agenda-restrict-begin
21153 org-agenda-restrict-end)
21154 (widen))
21155 (setq rtn (org-scan-tags 'agenda matcher todo-only))
21156 (setq rtnall (append rtnall rtn))))))))
21157 (if org-agenda-overriding-header
21158 (insert (org-add-props (copy-sequence org-agenda-overriding-header)
21159 nil 'face 'org-agenda-structure) "\n")
21160 (insert "Headlines with TAGS match: ")
21161 (add-text-properties (point-min) (1- (point))
21162 (list 'face 'org-agenda-structure))
21163 (setq pos (point))
21164 (insert match "\n")
21165 (add-text-properties pos (1- (point)) (list 'face 'org-warning))
21166 (setq pos (point))
21167 (unless org-agenda-multi
21168 (insert "Press `C-u r' to search again with new search string\n"))
21169 (add-text-properties pos (1- (point)) (list 'face 'org-agenda-structure)))
21170 (when rtnall
21171 (insert (org-finalize-agenda-entries rtnall) "\n"))
21172 (goto-char (point-min))
21173 (org-fit-agenda-window)
21174 (add-text-properties (point-min) (point-max) '(org-agenda-type tags))
21175 (org-finalize-agenda)
21176 (setq buffer-read-only t)))
21178 ;;; Agenda Finding stuck projects
21180 (defvar org-agenda-skip-regexp nil
21181 "Regular expression used in skipping subtrees for the agenda.
21182 This is basically a temporary global variable that can be set and then
21183 used by user-defined selections using `org-agenda-skip-function'.")
21185 (defvar org-agenda-overriding-header nil
21186 "When this is set during todo and tags searches, will replace header.")
21188 (defun org-agenda-skip-subtree-when-regexp-matches ()
21189 "Checks if the current subtree contains match for `org-agenda-skip-regexp'.
21190 If yes, it returns the end position of this tree, causing agenda commands
21191 to skip this subtree. This is a function that can be put into
21192 `org-agenda-skip-function' for the duration of a command."
21193 (let ((end (save-excursion (org-end-of-subtree t)))
21194 skip)
21195 (save-excursion
21196 (setq skip (re-search-forward org-agenda-skip-regexp end t)))
21197 (and skip end)))
21199 (defun org-agenda-skip-entry-if (&rest conditions)
21200 "Skip entry if any of CONDITIONS is true.
21201 See `org-agenda-skip-if' for details."
21202 (org-agenda-skip-if nil conditions))
21204 (defun org-agenda-skip-subtree-if (&rest conditions)
21205 "Skip entry if any of CONDITIONS is true.
21206 See `org-agenda-skip-if' for details."
21207 (org-agenda-skip-if t conditions))
21209 (defun org-agenda-skip-if (subtree conditions)
21210 "Checks current entity for CONDITIONS.
21211 If SUBTREE is non-nil, the entire subtree is checked. Otherwise, only
21212 the entry, i.e. the text before the next heading is checked.
21214 CONDITIONS is a list of symbols, boolean OR is used to combine the results
21215 from different tests. Valid conditions are:
21217 scheduled Check if there is a scheduled cookie
21218 notscheduled Check if there is no scheduled cookie
21219 deadline Check if there is a deadline
21220 notdeadline Check if there is no deadline
21221 regexp Check if regexp matches
21222 notregexp Check if regexp does not match.
21224 The regexp is taken from the conditions list, it must come right after
21225 the `regexp' or `notregexp' element.
21227 If any of these conditions is met, this function returns the end point of
21228 the entity, causing the search to continue from there. This is a function
21229 that can be put into `org-agenda-skip-function' for the duration of a command."
21230 (let (beg end m)
21231 (org-back-to-heading t)
21232 (setq beg (point)
21233 end (if subtree
21234 (progn (org-end-of-subtree t) (point))
21235 (progn (outline-next-heading) (1- (point)))))
21236 (goto-char beg)
21237 (and
21239 (and (memq 'scheduled conditions)
21240 (re-search-forward org-scheduled-time-regexp end t))
21241 (and (memq 'notscheduled conditions)
21242 (not (re-search-forward org-scheduled-time-regexp end t)))
21243 (and (memq 'deadline conditions)
21244 (re-search-forward org-deadline-time-regexp end t))
21245 (and (memq 'notdeadline conditions)
21246 (not (re-search-forward org-deadline-time-regexp end t)))
21247 (and (setq m (memq 'regexp conditions))
21248 (stringp (nth 1 m))
21249 (re-search-forward (nth 1 m) end t))
21250 (and (setq m (memq 'notregexp conditions))
21251 (stringp (nth 1 m))
21252 (not (re-search-forward (nth 1 m) end t))))
21253 end)))
21255 ;;;###autoload
21256 (defun org-agenda-list-stuck-projects (&rest ignore)
21257 "Create agenda view for projects that are stuck.
21258 Stuck projects are project that have no next actions. For the definitions
21259 of what a project is and how to check if it stuck, customize the variable
21260 `org-stuck-projects'.
21261 MATCH is being ignored."
21262 (interactive)
21263 (let* ((org-agenda-skip-function 'org-agenda-skip-subtree-when-regexp-matches)
21264 ;; FIXME: we could have used org-agenda-skip-if here.
21265 (org-agenda-overriding-header "List of stuck projects: ")
21266 (matcher (nth 0 org-stuck-projects))
21267 (todo (nth 1 org-stuck-projects))
21268 (todo-wds (if (member "*" todo)
21269 (progn
21270 (org-prepare-agenda-buffers (org-agenda-files))
21271 (org-delete-all
21272 org-done-keywords-for-agenda
21273 (copy-sequence org-todo-keywords-for-agenda)))
21274 todo))
21275 (todo-re (concat "^\\*+[ \t]+\\("
21276 (mapconcat 'identity todo-wds "\\|")
21277 "\\)\\>"))
21278 (tags (nth 2 org-stuck-projects))
21279 (tags-re (if (member "*" tags)
21280 (org-re "^\\*+ .*:[[:alnum:]_@]+:[ \t]*$")
21281 (concat "^\\*+ .*:\\("
21282 (mapconcat 'identity tags "\\|")
21283 (org-re "\\):[[:alnum:]_@:]*[ \t]*$"))))
21284 (gen-re (nth 3 org-stuck-projects))
21285 (re-list
21286 (delq nil
21287 (list
21288 (if todo todo-re)
21289 (if tags tags-re)
21290 (and gen-re (stringp gen-re) (string-match "\\S-" gen-re)
21291 gen-re)))))
21292 (setq org-agenda-skip-regexp
21293 (if re-list
21294 (mapconcat 'identity re-list "\\|")
21295 (error "No information how to identify unstuck projects")))
21296 (org-tags-view nil matcher)
21297 (with-current-buffer org-agenda-buffer-name
21298 (setq org-agenda-redo-command
21299 '(org-agenda-list-stuck-projects
21300 (or current-prefix-arg org-last-arg))))))
21302 ;;; Diary integration
21304 (defvar org-disable-agenda-to-diary nil) ;Dynamically-scoped param.
21306 (defun org-get-entries-from-diary (date)
21307 "Get the (Emacs Calendar) diary entries for DATE."
21308 (let* ((fancy-diary-buffer "*temporary-fancy-diary-buffer*")
21309 (diary-display-hook '(fancy-diary-display))
21310 (pop-up-frames nil)
21311 (list-diary-entries-hook
21312 (cons 'org-diary-default-entry list-diary-entries-hook))
21313 (diary-file-name-prefix-function nil) ; turn this feature off
21314 (diary-modify-entry-list-string-function 'org-modify-diary-entry-string)
21315 entries
21316 (org-disable-agenda-to-diary t))
21317 (save-excursion
21318 (save-window-excursion
21319 (funcall (if (fboundp 'diary-list-entries)
21320 'diary-list-entries 'list-diary-entries)
21321 date 1)))
21322 (if (not (get-buffer fancy-diary-buffer))
21323 (setq entries nil)
21324 (with-current-buffer fancy-diary-buffer
21325 (setq buffer-read-only nil)
21326 (if (zerop (buffer-size))
21327 ;; No entries
21328 (setq entries nil)
21329 ;; Omit the date and other unnecessary stuff
21330 (org-agenda-cleanup-fancy-diary)
21331 ;; Add prefix to each line and extend the text properties
21332 (if (zerop (buffer-size))
21333 (setq entries nil)
21334 (setq entries (buffer-substring (point-min) (- (point-max) 1)))))
21335 (set-buffer-modified-p nil)
21336 (kill-buffer fancy-diary-buffer)))
21337 (when entries
21338 (setq entries (org-split-string entries "\n"))
21339 (setq entries
21340 (mapcar
21341 (lambda (x)
21342 (setq x (org-format-agenda-item "" x "Diary" nil 'time))
21343 ;; Extend the text properties to the beginning of the line
21344 (org-add-props x (text-properties-at (1- (length x)) x)
21345 'type "diary" 'date date))
21346 entries)))))
21348 (defun org-agenda-cleanup-fancy-diary ()
21349 "Remove unwanted stuff in buffer created by `fancy-diary-display'.
21350 This gets rid of the date, the underline under the date, and
21351 the dummy entry installed by `org-mode' to ensure non-empty diary for each
21352 date. It also removes lines that contain only whitespace."
21353 (goto-char (point-min))
21354 (if (looking-at ".*?:[ \t]*")
21355 (progn
21356 (replace-match "")
21357 (re-search-forward "\n=+$" nil t)
21358 (replace-match "")
21359 (while (re-search-backward "^ +\n?" nil t) (replace-match "")))
21360 (re-search-forward "\n=+$" nil t)
21361 (delete-region (point-min) (min (point-max) (1+ (match-end 0)))))
21362 (goto-char (point-min))
21363 (while (re-search-forward "^ +\n" nil t)
21364 (replace-match ""))
21365 (goto-char (point-min))
21366 (if (re-search-forward "^Org-mode dummy\n?" nil t)
21367 (replace-match "")))
21369 ;; Make sure entries from the diary have the right text properties.
21370 (eval-after-load "diary-lib"
21371 '(if (boundp 'diary-modify-entry-list-string-function)
21372 ;; We can rely on the hook, nothing to do
21374 ;; Hook not avaiable, must use advice to make this work
21375 (defadvice add-to-diary-list (before org-mark-diary-entry activate)
21376 "Make the position visible."
21377 (if (and org-disable-agenda-to-diary ;; called from org-agenda
21378 (stringp string)
21379 buffer-file-name)
21380 (setq string (org-modify-diary-entry-string string))))))
21382 (defun org-modify-diary-entry-string (string)
21383 "Add text properties to string, allowing org-mode to act on it."
21384 (org-add-props string nil
21385 'mouse-face 'highlight
21386 'keymap org-agenda-keymap
21387 'help-echo (if buffer-file-name
21388 (format "mouse-2 or RET jump to diary file %s"
21389 (abbreviate-file-name buffer-file-name))
21391 'org-agenda-diary-link t
21392 'org-marker (org-agenda-new-marker (point-at-bol))))
21394 (defun org-diary-default-entry ()
21395 "Add a dummy entry to the diary.
21396 Needed to avoid empty dates which mess up holiday display."
21397 ;; Catch the error if dealing with the new add-to-diary-alist
21398 (when org-disable-agenda-to-diary
21399 (condition-case nil
21400 (add-to-diary-list original-date "Org-mode dummy" "")
21401 (error
21402 (add-to-diary-list original-date "Org-mode dummy" "" nil)))))
21404 ;;;###autoload
21405 (defun org-diary (&rest args)
21406 "Return diary information from org-files.
21407 This function can be used in a \"sexp\" diary entry in the Emacs calendar.
21408 It accesses org files and extracts information from those files to be
21409 listed in the diary. The function accepts arguments specifying what
21410 items should be listed. The following arguments are allowed:
21412 :timestamp List the headlines of items containing a date stamp or
21413 date range matching the selected date. Deadlines will
21414 also be listed, on the expiration day.
21416 :sexp List entries resulting from diary-like sexps.
21418 :deadline List any deadlines past due, or due within
21419 `org-deadline-warning-days'. The listing occurs only
21420 in the diary for *today*, not at any other date. If
21421 an entry is marked DONE, it is no longer listed.
21423 :scheduled List all items which are scheduled for the given date.
21424 The diary for *today* also contains items which were
21425 scheduled earlier and are not yet marked DONE.
21427 :todo List all TODO items from the org-file. This may be a
21428 long list - so this is not turned on by default.
21429 Like deadlines, these entries only show up in the
21430 diary for *today*, not at any other date.
21432 The call in the diary file should look like this:
21434 &%%(org-diary) ~/path/to/some/orgfile.org
21436 Use a separate line for each org file to check. Or, if you omit the file name,
21437 all files listed in `org-agenda-files' will be checked automatically:
21439 &%%(org-diary)
21441 If you don't give any arguments (as in the example above), the default
21442 arguments (:deadline :scheduled :timestamp :sexp) are used.
21443 So the example above may also be written as
21445 &%%(org-diary :deadline :timestamp :sexp :scheduled)
21447 The function expects the lisp variables `entry' and `date' to be provided
21448 by the caller, because this is how the calendar works. Don't use this
21449 function from a program - use `org-agenda-get-day-entries' instead."
21450 (when (> (- (time-to-seconds (current-time))
21451 org-agenda-last-marker-time)
21453 (org-agenda-reset-markers))
21454 (org-compile-prefix-format 'agenda)
21455 (org-set-sorting-strategy 'agenda)
21456 (setq args (or args '(:deadline :scheduled :timestamp :sexp)))
21457 (let* ((files (if (and entry (stringp entry) (string-match "\\S-" entry))
21458 (list entry)
21459 (org-agenda-files t)))
21460 file rtn results)
21461 (org-prepare-agenda-buffers files)
21462 ;; If this is called during org-agenda, don't return any entries to
21463 ;; the calendar. Org Agenda will list these entries itself.
21464 (if org-disable-agenda-to-diary (setq files nil))
21465 (while (setq file (pop files))
21466 (setq rtn (apply 'org-agenda-get-day-entries file date args))
21467 (setq results (append results rtn)))
21468 (if results
21469 (concat (org-finalize-agenda-entries results) "\n"))))
21471 ;;; Agenda entry finders
21473 (defun org-agenda-get-day-entries (file date &rest args)
21474 "Does the work for `org-diary' and `org-agenda'.
21475 FILE is the path to a file to be checked for entries. DATE is date like
21476 the one returned by `calendar-current-date'. ARGS are symbols indicating
21477 which kind of entries should be extracted. For details about these, see
21478 the documentation of `org-diary'."
21479 (setq args (or args '(:deadline :scheduled :timestamp :sexp)))
21480 (let* ((org-startup-folded nil)
21481 (org-startup-align-all-tables nil)
21482 (buffer (if (file-exists-p file)
21483 (org-get-agenda-file-buffer file)
21484 (error "No such file %s" file)))
21485 arg results rtn)
21486 (if (not buffer)
21487 ;; If file does not exist, make sure an error message ends up in diary
21488 (list (format "ORG-AGENDA-ERROR: No such org-file %s" file))
21489 (with-current-buffer buffer
21490 (unless (org-mode-p)
21491 (error "Agenda file %s is not in `org-mode'" file))
21492 (let ((case-fold-search nil))
21493 (save-excursion
21494 (save-restriction
21495 (if org-agenda-restrict
21496 (narrow-to-region org-agenda-restrict-begin
21497 org-agenda-restrict-end)
21498 (widen))
21499 ;; The way we repeatedly append to `results' makes it O(n^2) :-(
21500 (while (setq arg (pop args))
21501 (cond
21502 ((and (eq arg :todo)
21503 (equal date (calendar-current-date)))
21504 (setq rtn (org-agenda-get-todos))
21505 (setq results (append results rtn)))
21506 ((eq arg :timestamp)
21507 (setq rtn (org-agenda-get-blocks))
21508 (setq results (append results rtn))
21509 (setq rtn (org-agenda-get-timestamps))
21510 (setq results (append results rtn)))
21511 ((eq arg :sexp)
21512 (setq rtn (org-agenda-get-sexps))
21513 (setq results (append results rtn)))
21514 ((eq arg :scheduled)
21515 (setq rtn (org-agenda-get-scheduled))
21516 (setq results (append results rtn)))
21517 ((eq arg :closed)
21518 (setq rtn (org-agenda-get-closed))
21519 (setq results (append results rtn)))
21520 ((eq arg :deadline)
21521 (setq rtn (org-agenda-get-deadlines))
21522 (setq results (append results rtn))))))))
21523 results))))
21525 (defun org-entry-is-todo-p ()
21526 (member (org-get-todo-state) org-not-done-keywords))
21528 (defun org-entry-is-done-p ()
21529 (member (org-get-todo-state) org-done-keywords))
21531 (defun org-get-todo-state ()
21532 (save-excursion
21533 (org-back-to-heading t)
21534 (and (looking-at org-todo-line-regexp)
21535 (match-end 2)
21536 (match-string 2))))
21538 (defun org-at-date-range-p (&optional inactive-ok)
21539 "Is the cursor inside a date range?"
21540 (interactive)
21541 (save-excursion
21542 (catch 'exit
21543 (let ((pos (point)))
21544 (skip-chars-backward "^[<\r\n")
21545 (skip-chars-backward "<[")
21546 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
21547 (>= (match-end 0) pos)
21548 (throw 'exit t))
21549 (skip-chars-backward "^<[\r\n")
21550 (skip-chars-backward "<[")
21551 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
21552 (>= (match-end 0) pos)
21553 (throw 'exit t)))
21554 nil)))
21556 (defun org-agenda-get-todos ()
21557 "Return the TODO information for agenda display."
21558 (let* ((props (list 'face nil
21559 'done-face 'org-done
21560 'org-not-done-regexp org-not-done-regexp
21561 'org-todo-regexp org-todo-regexp
21562 'mouse-face 'highlight
21563 'keymap org-agenda-keymap
21564 'help-echo
21565 (format "mouse-2 or RET jump to org file %s"
21566 (abbreviate-file-name buffer-file-name))))
21567 ;; FIXME: get rid of the \n at some point but watch out
21568 (regexp (concat "^\\*+[ \t]+\\("
21569 (if org-select-this-todo-keyword
21570 (if (equal org-select-this-todo-keyword "*")
21571 org-todo-regexp
21572 (concat "\\<\\("
21573 (mapconcat 'identity (org-split-string org-select-this-todo-keyword "|") "\\|")
21574 "\\)\\>"))
21575 org-not-done-regexp)
21576 "[^\n\r]*\\)"))
21577 marker priority category tags
21578 ee txt beg end)
21579 (goto-char (point-min))
21580 (while (re-search-forward regexp nil t)
21581 (catch :skip
21582 (save-match-data
21583 (beginning-of-line)
21584 (setq beg (point) end (progn (outline-next-heading) (point)))
21585 (when (or (and org-agenda-todo-ignore-with-date (goto-char beg)
21586 (re-search-forward org-ts-regexp end t))
21587 (and org-agenda-todo-ignore-scheduled (goto-char beg)
21588 (re-search-forward org-scheduled-time-regexp end t))
21589 (and org-agenda-todo-ignore-deadlines (goto-char beg)
21590 (re-search-forward org-deadline-time-regexp end t)
21591 (org-deadline-close (match-string 1))))
21592 (goto-char (1+ beg))
21593 (or org-agenda-todo-list-sublevels (org-end-of-subtree 'invisible))
21594 (throw :skip nil)))
21595 (goto-char beg)
21596 (org-agenda-skip)
21597 (goto-char (match-beginning 1))
21598 (setq marker (org-agenda-new-marker (match-beginning 0))
21599 category (org-get-category)
21600 tags (org-get-tags-at (point))
21601 txt (org-format-agenda-item "" (match-string 1) category tags)
21602 priority (1+ (org-get-priority txt)))
21603 (org-add-props txt props
21604 'org-marker marker 'org-hd-marker marker
21605 'priority priority 'org-category category
21606 'type "todo")
21607 (push txt ee)
21608 (if org-agenda-todo-list-sublevels
21609 (goto-char (match-end 1))
21610 (org-end-of-subtree 'invisible))))
21611 (nreverse ee)))
21613 (defconst org-agenda-no-heading-message
21614 "No heading for this item in buffer or region.")
21616 (defun org-agenda-get-timestamps ()
21617 "Return the date stamp information for agenda display."
21618 (let* ((props (list 'face nil
21619 'org-not-done-regexp org-not-done-regexp
21620 'org-todo-regexp org-todo-regexp
21621 'mouse-face 'highlight
21622 'keymap org-agenda-keymap
21623 'help-echo
21624 (format "mouse-2 or RET jump to org file %s"
21625 (abbreviate-file-name buffer-file-name))))
21626 (d1 (calendar-absolute-from-gregorian date))
21627 (remove-re
21628 (concat
21629 (regexp-quote
21630 (format-time-string
21631 "<%Y-%m-%d"
21632 (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
21633 ".*?>"))
21634 (regexp
21635 (concat
21636 (regexp-quote
21637 (substring
21638 (format-time-string
21639 (car org-time-stamp-formats)
21640 (apply 'encode-time ; DATE bound by calendar
21641 (list 0 0 0 (nth 1 date) (car date) (nth 2 date))))
21642 0 11))
21643 "\\|\\(<[0-9]+-[0-9]+-[0-9]+[^>\n]+?\\+[0-9]+[dwmy]>\\)"
21644 "\\|\\(<%%\\(([^>\n]+)\\)>\\)"))
21645 marker hdmarker deadlinep scheduledp donep tmp priority category
21646 ee txt timestr tags b0 b3 e3 head)
21647 (goto-char (point-min))
21648 (while (re-search-forward regexp nil t)
21649 (setq b0 (match-beginning 0)
21650 b3 (match-beginning 3) e3 (match-end 3))
21651 (catch :skip
21652 (and (org-at-date-range-p) (throw :skip nil))
21653 (org-agenda-skip)
21654 (if (and (match-end 1)
21655 (not (= d1 (org-time-string-to-absolute (match-string 1) d1))))
21656 (throw :skip nil))
21657 (if (and e3
21658 (not (org-diary-sexp-entry (buffer-substring b3 e3) "" date)))
21659 (throw :skip nil))
21660 (setq marker (org-agenda-new-marker b0)
21661 category (org-get-category b0)
21662 tmp (buffer-substring (max (point-min)
21663 (- b0 org-ds-keyword-length))
21665 timestr (if b3 "" (buffer-substring b0 (point-at-eol)))
21666 deadlinep (string-match org-deadline-regexp tmp)
21667 scheduledp (string-match org-scheduled-regexp tmp)
21668 donep (org-entry-is-done-p))
21669 (if (or scheduledp deadlinep) (throw :skip t))
21670 (if (string-match ">" timestr)
21671 ;; substring should only run to end of time stamp
21672 (setq timestr (substring timestr 0 (match-end 0))))
21673 (save-excursion
21674 (if (re-search-backward "^\\*+ " nil t)
21675 (progn
21676 (goto-char (match-beginning 0))
21677 (setq hdmarker (org-agenda-new-marker)
21678 tags (org-get-tags-at))
21679 (looking-at "\\*+[ \t]+\\([^\r\n]+\\)")
21680 (setq head (match-string 1))
21681 (and org-agenda-skip-timestamp-if-done donep (throw :skip t))
21682 (setq txt (org-format-agenda-item
21683 nil head category tags timestr nil
21684 remove-re)))
21685 (setq txt org-agenda-no-heading-message))
21686 (setq priority (org-get-priority txt))
21687 (org-add-props txt props
21688 'org-marker marker 'org-hd-marker hdmarker)
21689 (org-add-props txt nil 'priority priority
21690 'org-category category 'date date
21691 'type "timestamp")
21692 (push txt ee))
21693 (outline-next-heading)))
21694 (nreverse ee)))
21696 (defun org-agenda-get-sexps ()
21697 "Return the sexp information for agenda display."
21698 (require 'diary-lib)
21699 (let* ((props (list 'face nil
21700 'mouse-face 'highlight
21701 'keymap org-agenda-keymap
21702 'help-echo
21703 (format "mouse-2 or RET jump to org file %s"
21704 (abbreviate-file-name buffer-file-name))))
21705 (regexp "^&?%%(")
21706 marker category ee txt tags entry result beg b sexp sexp-entry)
21707 (goto-char (point-min))
21708 (while (re-search-forward regexp nil t)
21709 (catch :skip
21710 (org-agenda-skip)
21711 (setq beg (match-beginning 0))
21712 (goto-char (1- (match-end 0)))
21713 (setq b (point))
21714 (forward-sexp 1)
21715 (setq sexp (buffer-substring b (point)))
21716 (setq sexp-entry (if (looking-at "[ \t]*\\(\\S-.*\\)")
21717 (org-trim (match-string 1))
21718 ""))
21719 (setq result (org-diary-sexp-entry sexp sexp-entry date))
21720 (when result
21721 (setq marker (org-agenda-new-marker beg)
21722 category (org-get-category beg))
21724 (if (string-match "\\S-" result)
21725 (setq txt result)
21726 (setq txt "SEXP entry returned empty string"))
21728 (setq txt (org-format-agenda-item
21729 "" txt category tags 'time))
21730 (org-add-props txt props 'org-marker marker)
21731 (org-add-props txt nil
21732 'org-category category 'date date
21733 'type "sexp")
21734 (push txt ee))))
21735 (nreverse ee)))
21737 (defun org-agenda-get-closed ()
21738 "Return the logged TODO entries for agenda display."
21739 (let* ((props (list 'mouse-face 'highlight
21740 'org-not-done-regexp org-not-done-regexp
21741 'org-todo-regexp org-todo-regexp
21742 'keymap org-agenda-keymap
21743 'help-echo
21744 (format "mouse-2 or RET jump to org file %s"
21745 (abbreviate-file-name buffer-file-name))))
21746 (regexp (concat
21747 "\\<\\(" org-closed-string "\\|" org-clock-string "\\) *\\["
21748 (regexp-quote
21749 (substring
21750 (format-time-string
21751 (car org-time-stamp-formats)
21752 (apply 'encode-time ; DATE bound by calendar
21753 (list 0 0 0 (nth 1 date) (car date) (nth 2 date))))
21754 1 11))))
21755 marker hdmarker priority category tags closedp
21756 ee txt timestr)
21757 (goto-char (point-min))
21758 (while (re-search-forward regexp nil t)
21759 (catch :skip
21760 (org-agenda-skip)
21761 (setq marker (org-agenda-new-marker (match-beginning 0))
21762 closedp (equal (match-string 1) org-closed-string)
21763 category (org-get-category (match-beginning 0))
21764 timestr (buffer-substring (match-beginning 0) (point-at-eol))
21765 ;; donep (org-entry-is-done-p)
21767 (if (string-match "\\]" timestr)
21768 ;; substring should only run to end of time stamp
21769 (setq timestr (substring timestr 0 (match-end 0))))
21770 (save-excursion
21771 (if (re-search-backward "^\\*+ " nil t)
21772 (progn
21773 (goto-char (match-beginning 0))
21774 (setq hdmarker (org-agenda-new-marker)
21775 tags (org-get-tags-at))
21776 (looking-at "\\*+[ \t]+\\([^\r\n]+\\)")
21777 (setq txt (org-format-agenda-item
21778 (if closedp "Closed: " "Clocked: ")
21779 (match-string 1) category tags timestr)))
21780 (setq txt org-agenda-no-heading-message))
21781 (setq priority 100000)
21782 (org-add-props txt props
21783 'org-marker marker 'org-hd-marker hdmarker 'face 'org-done
21784 'priority priority 'org-category category
21785 'type "closed" 'date date
21786 'undone-face 'org-warning 'done-face 'org-done)
21787 (push txt ee))
21788 (goto-char (point-at-eol))))
21789 (nreverse ee)))
21791 (defun org-agenda-get-deadlines ()
21792 "Return the deadline information for agenda display."
21793 (let* ((props (list 'mouse-face 'highlight
21794 'org-not-done-regexp org-not-done-regexp
21795 'org-todo-regexp org-todo-regexp
21796 'keymap org-agenda-keymap
21797 'help-echo
21798 (format "mouse-2 or RET jump to org file %s"
21799 (abbreviate-file-name buffer-file-name))))
21800 (regexp org-deadline-time-regexp)
21801 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
21802 (d1 (calendar-absolute-from-gregorian date)) ; DATE bound by calendar
21803 d2 diff dfrac wdays pos pos1 category tags
21804 ee txt head face s upcomingp donep timestr)
21805 (goto-char (point-min))
21806 (while (re-search-forward regexp nil t)
21807 (catch :skip
21808 (org-agenda-skip)
21809 (setq s (match-string 1)
21810 pos (1- (match-beginning 1))
21811 d2 (org-time-string-to-absolute (match-string 1) d1 'past)
21812 diff (- d2 d1)
21813 wdays (org-get-wdays s)
21814 dfrac (/ (* 1.0 (- wdays diff)) (max wdays 1))
21815 upcomingp (and todayp (> diff 0)))
21816 ;; When to show a deadline in the calendar:
21817 ;; If the expiration is within wdays warning time.
21818 ;; Past-due deadlines are only shown on the current date
21819 (if (or (and (<= diff wdays)
21820 (and todayp (not org-agenda-only-exact-dates)))
21821 (= diff 0))
21822 (save-excursion
21823 (setq category (org-get-category))
21824 (if (re-search-backward "^\\*+[ \t]+" nil t)
21825 (progn
21826 (goto-char (match-end 0))
21827 (setq pos1 (match-beginning 0))
21828 (setq tags (org-get-tags-at pos1))
21829 (setq head (buffer-substring-no-properties
21830 (point)
21831 (progn (skip-chars-forward "^\r\n")
21832 (point))))
21833 (setq donep (string-match org-looking-at-done-regexp head))
21834 (if (string-match " \\([012]?[0-9]:[0-9][0-9]\\)" s)
21835 (setq timestr
21836 (concat (substring s (match-beginning 1)) " "))
21837 (setq timestr 'time))
21838 (if (and donep
21839 (or org-agenda-skip-deadline-if-done
21840 (not (= diff 0))))
21841 (setq txt nil)
21842 (setq txt (org-format-agenda-item
21843 (if (= diff 0)
21844 (car org-agenda-deadline-leaders)
21845 (format (nth 1 org-agenda-deadline-leaders)
21846 diff))
21847 head category tags timestr))))
21848 (setq txt org-agenda-no-heading-message))
21849 (when txt
21850 (setq face (org-agenda-deadline-face dfrac))
21851 (org-add-props txt props
21852 'org-marker (org-agenda-new-marker pos)
21853 'org-hd-marker (org-agenda-new-marker pos1)
21854 'priority (+ (- diff)
21855 (org-get-priority txt))
21856 'org-category category
21857 'type (if upcomingp "upcoming-deadline" "deadline")
21858 'date (if upcomingp date d2)
21859 'face (if donep 'org-done face)
21860 'undone-face face 'done-face 'org-done)
21861 (push txt ee))))))
21862 (nreverse ee)))
21864 (defun org-agenda-deadline-face (fraction)
21865 "Return the face to displaying a deadline item.
21866 FRACTION is what fraction of the head-warning time has passed."
21867 (let ((faces org-agenda-deadline-faces) f)
21868 (catch 'exit
21869 (while (setq f (pop faces))
21870 (if (>= fraction (car f)) (throw 'exit (cdr f)))))))
21872 (defun org-agenda-get-scheduled ()
21873 "Return the scheduled information for agenda display."
21874 (let* ((props (list 'org-not-done-regexp org-not-done-regexp
21875 'org-todo-regexp org-todo-regexp
21876 'done-face 'org-done
21877 'mouse-face 'highlight
21878 'keymap org-agenda-keymap
21879 'help-echo
21880 (format "mouse-2 or RET jump to org file %s"
21881 (abbreviate-file-name buffer-file-name))))
21882 (regexp org-scheduled-time-regexp)
21883 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
21884 (d1 (calendar-absolute-from-gregorian date)) ; DATE bound by calendar
21885 d2 diff pos pos1 category tags
21886 ee txt head pastschedp donep face timestr s)
21887 (goto-char (point-min))
21888 (while (re-search-forward regexp nil t)
21889 (catch :skip
21890 (org-agenda-skip)
21891 (setq s (match-string 1)
21892 pos (1- (match-beginning 1))
21893 d2 (org-time-string-to-absolute (match-string 1) d1 'past)
21894 ;;; is this right?
21895 ;;; do we need to do this for deadleine too????
21896 ;;; d2 (org-time-string-to-absolute (match-string 1) (if todayp nil d1))
21897 diff (- d2 d1))
21898 (setq pastschedp (and todayp (< diff 0)))
21899 ;; When to show a scheduled item in the calendar:
21900 ;; If it is on or past the date.
21901 (if (or (and (< diff 0)
21902 (and todayp (not org-agenda-only-exact-dates)))
21903 (= diff 0))
21904 (save-excursion
21905 (setq category (org-get-category))
21906 (if (re-search-backward "^\\*+[ \t]+" nil t)
21907 (progn
21908 (goto-char (match-end 0))
21909 (setq pos1 (match-beginning 0))
21910 (setq tags (org-get-tags-at))
21911 (setq head (buffer-substring-no-properties
21912 (point)
21913 (progn (skip-chars-forward "^\r\n") (point))))
21914 (setq donep (string-match org-looking-at-done-regexp head))
21915 (if (string-match " \\([012]?[0-9]:[0-9][0-9]\\)" s)
21916 (setq timestr
21917 (concat (substring s (match-beginning 1)) " "))
21918 (setq timestr 'time))
21919 (if (and donep
21920 (or org-agenda-skip-scheduled-if-done
21921 (not (= diff 0))))
21922 (setq txt nil)
21923 (setq txt (org-format-agenda-item
21924 (if (= diff 0)
21925 (car org-agenda-scheduled-leaders)
21926 (format (nth 1 org-agenda-scheduled-leaders)
21927 (- 1 diff)))
21928 head category tags timestr))))
21929 (setq txt org-agenda-no-heading-message))
21930 (when txt
21931 (setq face (if pastschedp
21932 'org-scheduled-previously
21933 'org-scheduled-today))
21934 (org-add-props txt props
21935 'undone-face face
21936 'face (if donep 'org-done face)
21937 'org-marker (org-agenda-new-marker pos)
21938 'org-hd-marker (org-agenda-new-marker pos1)
21939 'type (if pastschedp "past-scheduled" "scheduled")
21940 'date (if pastschedp d2 date)
21941 'priority (+ 94 (- 5 diff) (org-get-priority txt))
21942 'org-category category)
21943 (push txt ee))))))
21944 (nreverse ee)))
21946 (defun org-agenda-get-blocks ()
21947 "Return the date-range information for agenda display."
21948 (let* ((props (list 'face nil
21949 'org-not-done-regexp org-not-done-regexp
21950 'org-todo-regexp org-todo-regexp
21951 'mouse-face 'highlight
21952 'keymap org-agenda-keymap
21953 'help-echo
21954 (format "mouse-2 or RET jump to org file %s"
21955 (abbreviate-file-name buffer-file-name))))
21956 (regexp org-tr-regexp)
21957 (d0 (calendar-absolute-from-gregorian date))
21958 marker hdmarker ee txt d1 d2 s1 s2 timestr category tags pos
21959 donep head)
21960 (goto-char (point-min))
21961 (while (re-search-forward regexp nil t)
21962 (catch :skip
21963 (org-agenda-skip)
21964 (setq pos (point))
21965 (setq timestr (match-string 0)
21966 s1 (match-string 1)
21967 s2 (match-string 2)
21968 d1 (time-to-days (org-time-string-to-time s1))
21969 d2 (time-to-days (org-time-string-to-time s2)))
21970 (if (and (> (- d0 d1) -1) (> (- d2 d0) -1))
21971 ;; Only allow days between the limits, because the normal
21972 ;; date stamps will catch the limits.
21973 (save-excursion
21974 (setq marker (org-agenda-new-marker (point)))
21975 (setq category (org-get-category))
21976 (if (re-search-backward "^\\*+ " nil t)
21977 (progn
21978 (goto-char (match-beginning 0))
21979 (setq hdmarker (org-agenda-new-marker (point)))
21980 (setq tags (org-get-tags-at))
21981 (looking-at "\\*+[ \t]+\\([^\r\n]+\\)")
21982 (setq head (match-string 1))
21983 (and org-agenda-skip-timestamp-if-done
21984 (org-entry-is-done-p)
21985 (throw :skip t))
21986 (setq txt (org-format-agenda-item
21987 (format (if (= d1 d2) "" "(%d/%d): ")
21988 (1+ (- d0 d1)) (1+ (- d2 d1)))
21989 head category tags
21990 (if (= d0 d1) timestr))))
21991 (setq txt org-agenda-no-heading-message))
21992 (org-add-props txt props
21993 'org-marker marker 'org-hd-marker hdmarker
21994 'type "block" 'date date
21995 'priority (org-get-priority txt) 'org-category category)
21996 (push txt ee)))
21997 (goto-char pos)))
21998 ;; Sort the entries by expiration date.
21999 (nreverse ee)))
22001 ;;; Agenda presentation and sorting
22003 (defconst org-plain-time-of-day-regexp
22004 (concat
22005 "\\(\\<[012]?[0-9]"
22006 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
22007 "\\(--?"
22008 "\\(\\<[012]?[0-9]"
22009 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
22010 "\\)?")
22011 "Regular expression to match a plain time or time range.
22012 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
22013 groups carry important information:
22014 0 the full match
22015 1 the first time, range or not
22016 8 the second time, if it is a range.")
22018 (defconst org-plain-time-extension-regexp
22019 (concat
22020 "\\(\\<[012]?[0-9]"
22021 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
22022 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
22023 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
22024 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
22025 groups carry important information:
22026 0 the full match
22027 7 hours of duration
22028 9 minutes of duration")
22030 (defconst org-stamp-time-of-day-regexp
22031 (concat
22032 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
22033 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
22034 "\\(--?"
22035 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
22036 "Regular expression to match a timestamp time or time range.
22037 After a match, the following groups carry important information:
22038 0 the full match
22039 1 date plus weekday, for backreferencing to make sure both times on same day
22040 2 the first time, range or not
22041 4 the second time, if it is a range.")
22043 (defvar org-prefix-has-time nil
22044 "A flag, set by `org-compile-prefix-format'.
22045 The flag is set if the currently compiled format contains a `%t'.")
22046 (defvar org-prefix-has-tag nil
22047 "A flag, set by `org-compile-prefix-format'.
22048 The flag is set if the currently compiled format contains a `%T'.")
22050 (defun org-format-agenda-item (extra txt &optional category tags dotime
22051 noprefix remove-re)
22052 "Format TXT to be inserted into the agenda buffer.
22053 In particular, it adds the prefix and corresponding text properties. EXTRA
22054 must be a string and replaces the `%s' specifier in the prefix format.
22055 CATEGORY (string, symbol or nil) may be used to overrule the default
22056 category taken from local variable or file name. It will replace the `%c'
22057 specifier in the format. DOTIME, when non-nil, indicates that a
22058 time-of-day should be extracted from TXT for sorting of this entry, and for
22059 the `%t' specifier in the format. When DOTIME is a string, this string is
22060 searched for a time before TXT is. NOPREFIX is a flag and indicates that
22061 only the correctly processes TXT should be returned - this is used by
22062 `org-agenda-change-all-lines'. TAGS can be the tags of the headline.
22063 Any match of REMOVE-RE will be removed from TXT."
22064 (save-match-data
22065 ;; Diary entries sometimes have extra whitespace at the beginning
22066 (if (string-match "^ +" txt) (setq txt (replace-match "" nil nil txt)))
22067 (let* ((category (or category
22068 org-category
22069 (if buffer-file-name
22070 (file-name-sans-extension
22071 (file-name-nondirectory buffer-file-name))
22072 "")))
22073 (tag (if tags (nth (1- (length tags)) tags) ""))
22074 time ; time and tag are needed for the eval of the prefix format
22075 (ts (if dotime (concat (if (stringp dotime) dotime "") txt)))
22076 (time-of-day (and dotime (org-get-time-of-day ts)))
22077 stamp plain s0 s1 s2 rtn srp)
22078 (when (and dotime time-of-day org-prefix-has-time)
22079 ;; Extract starting and ending time and move them to prefix
22080 (when (or (setq stamp (string-match org-stamp-time-of-day-regexp ts))
22081 (setq plain (string-match org-plain-time-of-day-regexp ts)))
22082 (setq s0 (match-string 0 ts)
22083 srp (and stamp (match-end 3))
22084 s1 (match-string (if plain 1 2) ts)
22085 s2 (match-string (if plain 8 (if srp 4 6)) ts))
22087 ;; If the times are in TXT (not in DOTIMES), and the prefix will list
22088 ;; them, we might want to remove them there to avoid duplication.
22089 ;; The user can turn this off with a variable.
22090 (if (and org-agenda-remove-times-when-in-prefix (or stamp plain)
22091 (string-match (concat (regexp-quote s0) " *") txt)
22092 (not (equal ?\] (string-to-char (substring txt (match-end 0)))))
22093 (if (eq org-agenda-remove-times-when-in-prefix 'beg)
22094 (= (match-beginning 0) 0)
22096 (setq txt (replace-match "" nil nil txt))))
22097 ;; Normalize the time(s) to 24 hour
22098 (if s1 (setq s1 (org-get-time-of-day s1 'string t)))
22099 (if s2 (setq s2 (org-get-time-of-day s2 'string t))))
22101 (when (and s1 (not s2) org-agenda-default-appointment-duration
22102 (string-match "\\([0-9]+\\):\\([0-9]+\\)" s1))
22103 (let ((m (+ (string-to-number (match-string 2 s1))
22104 (* 60 (string-to-number (match-string 1 s1)))
22105 org-agenda-default-appointment-duration))
22107 (setq h (/ m 60) m (- m (* h 60)))
22108 (setq s2 (format "%02d:%02d" h m))))
22110 (when (string-match (org-re "\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$")
22111 txt)
22112 ;; Tags are in the string
22113 (if (or (eq org-agenda-remove-tags t)
22114 (and org-agenda-remove-tags
22115 org-prefix-has-tag))
22116 (setq txt (replace-match "" t t txt))
22117 (setq txt (replace-match
22118 (concat (make-string (max (- 50 (length txt)) 1) ?\ )
22119 (match-string 2 txt))
22120 t t txt))))
22122 (when remove-re
22123 (while (string-match remove-re txt)
22124 (setq txt (replace-match "" t t txt))))
22126 ;; Create the final string
22127 (if noprefix
22128 (setq rtn txt)
22129 ;; Prepare the variables needed in the eval of the compiled format
22130 (setq time (cond (s2 (concat s1 "-" s2))
22131 (s1 (concat s1 "......"))
22132 (t ""))
22133 extra (or extra "")
22134 category (if (symbolp category) (symbol-name category) category))
22135 ;; Evaluate the compiled format
22136 (setq rtn (concat (eval org-prefix-format-compiled) txt)))
22138 ;; And finally add the text properties
22139 (org-add-props rtn nil
22140 'org-category (downcase category) 'tags tags
22141 'org-highest-priority org-highest-priority
22142 'org-lowest-priority org-lowest-priority
22143 'prefix-length (- (length rtn) (length txt))
22144 'time-of-day time-of-day
22145 'txt txt
22146 'time time
22147 'extra extra
22148 'dotime dotime))))
22150 (defvar org-agenda-sorting-strategy) ;; because the def is in a let form
22151 (defvar org-agenda-sorting-strategy-selected nil)
22153 (defun org-agenda-add-time-grid-maybe (list ndays todayp)
22154 (catch 'exit
22155 (cond ((not org-agenda-use-time-grid) (throw 'exit list))
22156 ((and todayp (member 'today (car org-agenda-time-grid))))
22157 ((and (= ndays 1) (member 'daily (car org-agenda-time-grid))))
22158 ((member 'weekly (car org-agenda-time-grid)))
22159 (t (throw 'exit list)))
22160 (let* ((have (delq nil (mapcar
22161 (lambda (x) (get-text-property 1 'time-of-day x))
22162 list)))
22163 (string (nth 1 org-agenda-time-grid))
22164 (gridtimes (nth 2 org-agenda-time-grid))
22165 (req (car org-agenda-time-grid))
22166 (remove (member 'remove-match req))
22167 new time)
22168 (if (and (member 'require-timed req) (not have))
22169 ;; don't show empty grid
22170 (throw 'exit list))
22171 (while (setq time (pop gridtimes))
22172 (unless (and remove (member time have))
22173 (setq time (int-to-string time))
22174 (push (org-format-agenda-item
22175 nil string "" nil
22176 (concat (substring time 0 -2) ":" (substring time -2)))
22177 new)
22178 (put-text-property
22179 1 (length (car new)) 'face 'org-time-grid (car new))))
22180 (if (member 'time-up org-agenda-sorting-strategy-selected)
22181 (append new list)
22182 (append list new)))))
22184 (defun org-compile-prefix-format (key)
22185 "Compile the prefix format into a Lisp form that can be evaluated.
22186 The resulting form is returned and stored in the variable
22187 `org-prefix-format-compiled'."
22188 (setq org-prefix-has-time nil org-prefix-has-tag nil)
22189 (let ((s (cond
22190 ((stringp org-agenda-prefix-format)
22191 org-agenda-prefix-format)
22192 ((assq key org-agenda-prefix-format)
22193 (cdr (assq key org-agenda-prefix-format)))
22194 (t " %-12:c%?-12t% s")))
22195 (start 0)
22196 varform vars var e c f opt)
22197 (while (string-match "%\\(\\?\\)?\\([-+]?[0-9.]*\\)\\([ .;,:!?=|/<>]?\\)\\([cts]\\)"
22198 s start)
22199 (setq var (cdr (assoc (match-string 4 s)
22200 '(("c" . category) ("t" . time) ("s" . extra)
22201 ("T" . tag))))
22202 c (or (match-string 3 s) "")
22203 opt (match-beginning 1)
22204 start (1+ (match-beginning 0)))
22205 (if (equal var 'time) (setq org-prefix-has-time t))
22206 (if (equal var 'tag) (setq org-prefix-has-tag t))
22207 (setq f (concat "%" (match-string 2 s) "s"))
22208 (if opt
22209 (setq varform
22210 `(if (equal "" ,var)
22212 (format ,f (if (equal "" ,var) "" (concat ,var ,c)))))
22213 (setq varform `(format ,f (if (equal ,var "") "" (concat ,var ,c)))))
22214 (setq s (replace-match "%s" t nil s))
22215 (push varform vars))
22216 (setq vars (nreverse vars))
22217 (setq org-prefix-format-compiled `(format ,s ,@vars))))
22219 (defun org-set-sorting-strategy (key)
22220 (if (symbolp (car org-agenda-sorting-strategy))
22221 ;; the old format
22222 (setq org-agenda-sorting-strategy-selected org-agenda-sorting-strategy)
22223 (setq org-agenda-sorting-strategy-selected
22224 (or (cdr (assq key org-agenda-sorting-strategy))
22225 (cdr (assq 'agenda org-agenda-sorting-strategy))
22226 '(time-up category-keep priority-down)))))
22228 (defun org-get-time-of-day (s &optional string mod24)
22229 "Check string S for a time of day.
22230 If found, return it as a military time number between 0 and 2400.
22231 If not found, return nil.
22232 The optional STRING argument forces conversion into a 5 character wide string
22233 HH:MM."
22234 (save-match-data
22235 (when
22236 (or (string-match "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)\\([AaPp][Mm]\\)?\\> *" s)
22237 (string-match "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\([AaPp][Mm]\\)\\> *" s))
22238 (let* ((h (string-to-number (match-string 1 s)))
22239 (m (if (match-end 3) (string-to-number (match-string 3 s)) 0))
22240 (ampm (if (match-end 4) (downcase (match-string 4 s))))
22241 (am-p (equal ampm "am"))
22242 (h1 (cond ((not ampm) h)
22243 ((= h 12) (if am-p 0 12))
22244 (t (+ h (if am-p 0 12)))))
22245 (h2 (if (and string mod24 (not (and (= m 0) (= h1 24))))
22246 (mod h1 24) h1))
22247 (t0 (+ (* 100 h2) m))
22248 (t1 (concat (if (>= h1 24) "+" " ")
22249 (if (< t0 100) "0" "")
22250 (if (< t0 10) "0" "")
22251 (int-to-string t0))))
22252 (if string (concat (substring t1 -4 -2) ":" (substring t1 -2)) t0)))))
22254 (defun org-finalize-agenda-entries (list &optional nosort)
22255 "Sort and concatenate the agenda items."
22256 (setq list (mapcar 'org-agenda-highlight-todo list))
22257 (if nosort
22258 list
22259 (mapconcat 'identity (sort list 'org-entries-lessp) "\n")))
22261 (defun org-agenda-highlight-todo (x)
22262 (let (re pl)
22263 (if (eq x 'line)
22264 (save-excursion
22265 (beginning-of-line 1)
22266 (setq re (get-text-property (point) 'org-todo-regexp))
22267 (goto-char (+ (point) (or (get-text-property (point) 'prefix-length) 0)))
22268 (when (looking-at (concat "[ \t]*\\.*" re " +"))
22269 (add-text-properties (match-beginning 0) (match-end 0)
22270 (list 'face (org-get-todo-face 0)))
22271 (let ((s (buffer-substring (match-beginning 1) (match-end 1))))
22272 (delete-region (match-beginning 1) (1- (match-end 0)))
22273 (goto-char (match-beginning 1))
22274 (insert (format org-agenda-todo-keyword-format s)))))
22275 (setq re (concat (get-text-property 0 'org-todo-regexp x))
22276 pl (get-text-property 0 'prefix-length x))
22277 (when (and re
22278 (equal (string-match (concat "\\(\\.*\\)" re "\\( +\\)")
22279 x (or pl 0)) pl))
22280 (add-text-properties
22281 (or (match-end 1) (match-end 0)) (match-end 0)
22282 (list 'face (org-get-todo-face (match-string 2 x)))
22284 (setq x (concat (substring x 0 (match-end 1))
22285 (format org-agenda-todo-keyword-format
22286 (match-string 2 x))
22288 (substring x (match-end 3)))))
22289 x)))
22291 (defsubst org-cmp-priority (a b)
22292 "Compare the priorities of string A and B."
22293 (let ((pa (or (get-text-property 1 'priority a) 0))
22294 (pb (or (get-text-property 1 'priority b) 0)))
22295 (cond ((> pa pb) +1)
22296 ((< pa pb) -1)
22297 (t nil))))
22299 (defsubst org-cmp-category (a b)
22300 "Compare the string values of categories of strings A and B."
22301 (let ((ca (or (get-text-property 1 'org-category a) ""))
22302 (cb (or (get-text-property 1 'org-category b) "")))
22303 (cond ((string-lessp ca cb) -1)
22304 ((string-lessp cb ca) +1)
22305 (t nil))))
22307 (defsubst org-cmp-tag (a b)
22308 "Compare the string values of categories of strings A and B."
22309 (let ((ta (car (last (get-text-property 1 'tags a))))
22310 (tb (car (last (get-text-property 1 'tags b)))))
22311 (cond ((not ta) +1)
22312 ((not tb) -1)
22313 ((string-lessp ta tb) -1)
22314 ((string-lessp tb ta) +1)
22315 (t nil))))
22317 (defsubst org-cmp-time (a b)
22318 "Compare the time-of-day values of strings A and B."
22319 (let* ((def (if org-sort-agenda-notime-is-late 9901 -1))
22320 (ta (or (get-text-property 1 'time-of-day a) def))
22321 (tb (or (get-text-property 1 'time-of-day b) def)))
22322 (cond ((< ta tb) -1)
22323 ((< tb ta) +1)
22324 (t nil))))
22326 (defun org-entries-lessp (a b)
22327 "Predicate for sorting agenda entries."
22328 ;; The following variables will be used when the form is evaluated.
22329 ;; So even though the compiler complains, keep them.
22330 (let* ((time-up (org-cmp-time a b))
22331 (time-down (if time-up (- time-up) nil))
22332 (priority-up (org-cmp-priority a b))
22333 (priority-down (if priority-up (- priority-up) nil))
22334 (category-up (org-cmp-category a b))
22335 (category-down (if category-up (- category-up) nil))
22336 (category-keep (if category-up +1 nil))
22337 (tag-up (org-cmp-tag a b))
22338 (tag-down (if tag-up (- tag-up) nil)))
22339 (cdr (assoc
22340 (eval (cons 'or org-agenda-sorting-strategy-selected))
22341 '((-1 . t) (1 . nil) (nil . nil))))))
22343 ;;; Agenda restriction lock
22345 (defvar org-agenda-restriction-lock-overlay (org-make-overlay 1 1)
22346 "Overlay to mark the headline to which arenda commands are restricted.")
22347 (org-overlay-put org-agenda-restriction-lock-overlay
22348 'face 'org-agenda-restriction-lock)
22349 (org-overlay-put org-agenda-restriction-lock-overlay
22350 'help-echo "Agendas are currently limited to this subtree.")
22351 (org-detach-overlay org-agenda-restriction-lock-overlay)
22352 (defvar org-speedbar-restriction-lock-overlay (org-make-overlay 1 1)
22353 "Overlay marking the agenda restriction line in speedbar.")
22354 (org-overlay-put org-speedbar-restriction-lock-overlay
22355 'face 'org-agenda-restriction-lock)
22356 (org-overlay-put org-speedbar-restriction-lock-overlay
22357 'help-echo "Agendas are currently limited to this item.")
22358 (org-detach-overlay org-speedbar-restriction-lock-overlay)
22360 (defun org-agenda-set-restriction-lock (&optional type)
22361 "Set restriction lock for agenda, to current subtree or file.
22362 Restriction will be the file if TYPE is `file', or if type is the
22363 universal prefix '(4), or if the cursor is before the first headline
22364 in the file. Otherwise, restriction will be to the current subtree."
22365 (interactive "P")
22366 (and (equal type '(4)) (setq type 'file))
22367 (setq type (cond
22368 (type type)
22369 ((org-at-heading-p) 'subtree)
22370 ((condition-case nil (org-back-to-heading t) (error nil))
22371 'subtree)
22372 (t 'file)))
22373 (if (eq type 'subtree)
22374 (progn
22375 (setq org-agenda-restrict t)
22376 (setq org-agenda-overriding-restriction 'subtree)
22377 (put 'org-agenda-files 'org-restrict
22378 (list (buffer-file-name (buffer-base-buffer))))
22379 (org-back-to-heading t)
22380 (org-move-overlay org-agenda-restriction-lock-overlay (point) (point-at-eol))
22381 (move-marker org-agenda-restrict-begin (point))
22382 (move-marker org-agenda-restrict-end
22383 (save-excursion (org-end-of-subtree t)))
22384 (message "Locking agenda restriction to subtree"))
22385 (put 'org-agenda-files 'org-restrict
22386 (list (buffer-file-name (buffer-base-buffer))))
22387 (setq org-agenda-restrict nil)
22388 (setq org-agenda-overriding-restriction 'file)
22389 (move-marker org-agenda-restrict-begin nil)
22390 (move-marker org-agenda-restrict-end nil)
22391 (message "Locking agenda restriction to file"))
22392 (setq current-prefix-arg nil)
22393 (org-agenda-maybe-redo))
22395 (defun org-agenda-remove-restriction-lock (&optional noupdate)
22396 "Remove the agenda restriction lock."
22397 (interactive "P")
22398 (org-detach-overlay org-agenda-restriction-lock-overlay)
22399 (org-detach-overlay org-speedbar-restriction-lock-overlay)
22400 (setq org-agenda-overriding-restriction nil)
22401 (setq org-agenda-restrict nil)
22402 (put 'org-agenda-files 'org-restrict nil)
22403 (move-marker org-agenda-restrict-begin nil)
22404 (move-marker org-agenda-restrict-end nil)
22405 (setq current-prefix-arg nil)
22406 (message "Agenda restriction lock removed")
22407 (or noupdate (org-agenda-maybe-redo)))
22409 (defun org-agenda-maybe-redo ()
22410 "If there is any window showing the agenda view, update it."
22411 (let ((w (get-buffer-window org-agenda-buffer-name t))
22412 (w0 (selected-window)))
22413 (when w
22414 (select-window w)
22415 (org-agenda-redo)
22416 (select-window w0)
22417 (if org-agenda-overriding-restriction
22418 (message "Agenda view shifted to new %s restriction"
22419 org-agenda-overriding-restriction)
22420 (message "Agenda restriction lock removed")))))
22422 ;;; Agenda commands
22424 (defun org-agenda-check-type (error &rest types)
22425 "Check if agenda buffer is of allowed type.
22426 If ERROR is non-nil, throw an error, otherwise just return nil."
22427 (if (memq org-agenda-type types)
22429 (if error
22430 (error "Not allowed in %s-type agenda buffers" org-agenda-type)
22431 nil)))
22433 (defun org-agenda-quit ()
22434 "Exit agenda by removing the window or the buffer."
22435 (interactive)
22436 (let ((buf (current-buffer)))
22437 (if (not (one-window-p)) (delete-window))
22438 (kill-buffer buf)
22439 (org-agenda-reset-markers)
22440 (org-columns-remove-overlays))
22441 ;; Maybe restore the pre-agenda window configuration.
22442 (and org-agenda-restore-windows-after-quit
22443 (not (eq org-agenda-window-setup 'other-frame))
22444 org-pre-agenda-window-conf
22445 (set-window-configuration org-pre-agenda-window-conf)))
22447 (defun org-agenda-exit ()
22448 "Exit agenda by removing the window or the buffer.
22449 Also kill all Org-mode buffers which have been loaded by `org-agenda'.
22450 Org-mode buffers visited directly by the user will not be touched."
22451 (interactive)
22452 (org-release-buffers org-agenda-new-buffers)
22453 (setq org-agenda-new-buffers nil)
22454 (org-agenda-quit))
22456 (defun org-agenda-execute (arg)
22457 "Execute another agenda command, keeping same window.\\<global-map>
22458 So this is just a shortcut for `\\[org-agenda]', available in the agenda."
22459 (interactive "P")
22460 (let ((org-agenda-window-setup 'current-window))
22461 (org-agenda arg)))
22463 (defun org-save-all-org-buffers ()
22464 "Save all Org-mode buffers without user confirmation."
22465 (interactive)
22466 (message "Saving all Org-mode buffers...")
22467 (save-some-buffers t 'org-mode-p)
22468 (message "Saving all Org-mode buffers... done"))
22470 (defun org-agenda-redo ()
22471 "Rebuild Agenda.
22472 When this is the global TODO list, a prefix argument will be interpreted."
22473 (interactive)
22474 (let* ((org-agenda-keep-modes t)
22475 (line (org-current-line))
22476 (window-line (- line (org-current-line (window-start))))
22477 (lprops (get 'org-agenda-redo-command 'org-lprops)))
22478 (message "Rebuilding agenda buffer...")
22479 (org-let lprops '(eval org-agenda-redo-command))
22480 (setq org-agenda-undo-list nil
22481 org-agenda-pending-undo-list nil)
22482 (message "Rebuilding agenda buffer...done")
22483 (goto-line line)
22484 (recenter window-line)))
22486 (defun org-agenda-manipulate-query-add ()
22487 "Manipulate the query by adding a search term with positive selection.
22488 Positive selection means, the term must be matched for selection of an entry."
22489 (interactive)
22490 (org-agenda-manipulate-query ?\[))
22491 (defun org-agenda-manipulate-query-subtract ()
22492 "Manipulate the query by adding a search term with negative selection.
22493 Negative selection means, term must not be matched for selection of an entry."
22494 (interactive)
22495 (org-agenda-manipulate-query ?\]))
22496 (defun org-agenda-manipulate-query-add-re ()
22497 "Manipulate the query by adding a search regexp with positive selection.
22498 Positive selection means, the regexp must match for selection of an entry."
22499 (interactive)
22500 (org-agenda-manipulate-query ?\{))
22501 (defun org-agenda-manipulate-query-subtract-re ()
22502 "Manipulate the query by adding a search regexp with negative selection.
22503 Negative selection means, regexp must not match for selection of an entry."
22504 (interactive)
22505 (org-agenda-manipulate-query ?\}))
22506 (defun org-agenda-manipulate-query (char)
22507 (cond
22508 ((eq org-agenda-type 'search)
22509 (org-add-to-string
22510 'org-agenda-query-string
22511 (cdr (assoc char '((?\[ . " +") (?\] . " -")
22512 (?\{ . " +{}") (?\} . " -{}")))))
22513 (setq org-agenda-redo-command
22514 (list 'org-search-view
22515 (+ (length org-agenda-query-string)
22516 (if (member char '(?\{ ?\})) 0 1))
22517 org-agenda-query-string))
22518 (set-register org-agenda-query-register org-agenda-query-string)
22519 (org-agenda-redo))
22520 (t (error "Canot manipulate query for %s-type agenda buffers"
22521 org-agenda-type))))
22523 (defun org-add-to-string (var string)
22524 (set var (concat (symbol-value var) string)))
22526 (defun org-agenda-goto-date (date)
22527 "Jump to DATE in agenda."
22528 (interactive (list (org-read-date)))
22529 (org-agenda-list nil date))
22531 (defun org-agenda-goto-today ()
22532 "Go to today."
22533 (interactive)
22534 (org-agenda-check-type t 'timeline 'agenda)
22535 (let ((tdpos (text-property-any (point-min) (point-max) 'org-today t)))
22536 (cond
22537 (tdpos (goto-char tdpos))
22538 ((eq org-agenda-type 'agenda)
22539 (let* ((sd (time-to-days
22540 (time-subtract (current-time)
22541 (list 0 (* 3600 org-extend-today-until) 0))))
22542 (comp (org-agenda-compute-time-span sd org-agenda-span))
22543 (org-agenda-overriding-arguments org-agenda-last-arguments))
22544 (setf (nth 1 org-agenda-overriding-arguments) (car comp))
22545 (setf (nth 2 org-agenda-overriding-arguments) (cdr comp))
22546 (org-agenda-redo)
22547 (org-agenda-find-same-or-today-or-agenda)))
22548 (t (error "Cannot find today")))))
22550 (defun org-agenda-find-same-or-today-or-agenda (&optional cnt)
22551 (goto-char
22552 (or (and cnt (text-property-any (point-min) (point-max) 'org-day-cnt cnt))
22553 (text-property-any (point-min) (point-max) 'org-today t)
22554 (text-property-any (point-min) (point-max) 'org-agenda-type 'agenda)
22555 (point-min))))
22557 (defun org-agenda-later (arg)
22558 "Go forward in time by thee current span.
22559 With prefix ARG, go forward that many times the current span."
22560 (interactive "p")
22561 (org-agenda-check-type t 'agenda)
22562 (let* ((span org-agenda-span)
22563 (sd org-starting-day)
22564 (greg (calendar-gregorian-from-absolute sd))
22565 (cnt (get-text-property (point) 'org-day-cnt))
22566 greg2 nd)
22567 (cond
22568 ((eq span 'day)
22569 (setq sd (+ arg sd) nd 1))
22570 ((eq span 'week)
22571 (setq sd (+ (* 7 arg) sd) nd 7))
22572 ((eq span 'month)
22573 (setq greg2 (list (+ (car greg) arg) (nth 1 greg) (nth 2 greg))
22574 sd (calendar-absolute-from-gregorian greg2))
22575 (setcar greg2 (1+ (car greg2)))
22576 (setq nd (- (calendar-absolute-from-gregorian greg2) sd)))
22577 ((eq span 'year)
22578 (setq greg2 (list (car greg) (nth 1 greg) (+ arg (nth 2 greg)))
22579 sd (calendar-absolute-from-gregorian greg2))
22580 (setcar (nthcdr 2 greg2) (1+ (nth 2 greg2)))
22581 (setq nd (- (calendar-absolute-from-gregorian greg2) sd))))
22582 (let ((org-agenda-overriding-arguments
22583 (list (car org-agenda-last-arguments) sd nd t)))
22584 (org-agenda-redo)
22585 (org-agenda-find-same-or-today-or-agenda cnt))))
22587 (defun org-agenda-earlier (arg)
22588 "Go backward in time by the current span.
22589 With prefix ARG, go backward that many times the current span."
22590 (interactive "p")
22591 (org-agenda-later (- arg)))
22593 (defun org-agenda-day-view ()
22594 "Switch to daily view for agenda."
22595 (interactive)
22596 (setq org-agenda-ndays 1)
22597 (org-agenda-change-time-span 'day))
22598 (defun org-agenda-week-view ()
22599 "Switch to daily view for agenda."
22600 (interactive)
22601 (setq org-agenda-ndays 7)
22602 (org-agenda-change-time-span 'week))
22603 (defun org-agenda-month-view ()
22604 "Switch to daily view for agenda."
22605 (interactive)
22606 (org-agenda-change-time-span 'month))
22607 (defun org-agenda-year-view ()
22608 "Switch to daily view for agenda."
22609 (interactive)
22610 (if (y-or-n-p "Are you sure you want to compute the agenda for an entire year? ")
22611 (org-agenda-change-time-span 'year)
22612 (error "Abort")))
22614 (defun org-agenda-change-time-span (span)
22615 "Change the agenda view to SPAN.
22616 SPAN may be `day', `week', `month', `year'."
22617 (org-agenda-check-type t 'agenda)
22618 (if (equal org-agenda-span span)
22619 (error "Viewing span is already \"%s\"" span))
22620 (let* ((sd (or (get-text-property (point) 'day)
22621 org-starting-day))
22622 (computed (org-agenda-compute-time-span sd span))
22623 (org-agenda-overriding-arguments
22624 (list (car org-agenda-last-arguments)
22625 (car computed) (cdr computed) t)))
22626 (org-agenda-redo)
22627 (org-agenda-find-same-or-today-or-agenda))
22628 (org-agenda-set-mode-name)
22629 (message "Switched to %s view" span))
22631 (defun org-agenda-compute-time-span (sd span)
22632 "Compute starting date and number of days for agenda.
22633 SPAN may be `day', `week', `month', `year'. The return value
22634 is a cons cell with the starting date and the number of days,
22635 so that the date SD will be in that range."
22636 (let* ((greg (calendar-gregorian-from-absolute sd))
22638 (cond
22639 ((eq span 'day)
22640 (setq nd 1))
22641 ((eq span 'week)
22642 (let* ((nt (calendar-day-of-week
22643 (calendar-gregorian-from-absolute sd)))
22644 (d (if org-agenda-start-on-weekday
22645 (- nt org-agenda-start-on-weekday)
22646 0)))
22647 (setq sd (- sd (+ (if (< d 0) 7 0) d)))
22648 (setq nd 7)))
22649 ((eq span 'month)
22650 (setq sd (calendar-absolute-from-gregorian
22651 (list (car greg) 1 (nth 2 greg)))
22652 nd (- (calendar-absolute-from-gregorian
22653 (list (1+ (car greg)) 1 (nth 2 greg)))
22654 sd)))
22655 ((eq span 'year)
22656 (setq sd (calendar-absolute-from-gregorian
22657 (list 1 1 (nth 2 greg)))
22658 nd (- (calendar-absolute-from-gregorian
22659 (list 1 1 (1+ (nth 2 greg))))
22660 sd))))
22661 (cons sd nd)))
22663 ;; FIXME: does not work if user makes date format that starts with a blank
22664 (defun org-agenda-next-date-line (&optional arg)
22665 "Jump to the next line indicating a date in agenda buffer."
22666 (interactive "p")
22667 (org-agenda-check-type t 'agenda 'timeline)
22668 (beginning-of-line 1)
22669 (if (looking-at "^\\S-") (forward-char 1))
22670 (if (not (re-search-forward "^\\S-" nil t arg))
22671 (progn
22672 (backward-char 1)
22673 (error "No next date after this line in this buffer")))
22674 (goto-char (match-beginning 0)))
22676 (defun org-agenda-previous-date-line (&optional arg)
22677 "Jump to the previous line indicating a date in agenda buffer."
22678 (interactive "p")
22679 (org-agenda-check-type t 'agenda 'timeline)
22680 (beginning-of-line 1)
22681 (if (not (re-search-backward "^\\S-" nil t arg))
22682 (error "No previous date before this line in this buffer")))
22684 ;; Initialize the highlight
22685 (defvar org-hl (org-make-overlay 1 1))
22686 (org-overlay-put org-hl 'face 'highlight)
22688 (defun org-highlight (begin end &optional buffer)
22689 "Highlight a region with overlay."
22690 (funcall (if (featurep 'xemacs) 'set-extent-endpoints 'move-overlay)
22691 org-hl begin end (or buffer (current-buffer))))
22693 (defun org-unhighlight ()
22694 "Detach overlay INDEX."
22695 (funcall (if (featurep 'xemacs) 'detach-extent 'delete-overlay) org-hl))
22697 ;; FIXME this is currently not used.
22698 (defun org-highlight-until-next-command (beg end &optional buffer)
22699 (org-highlight beg end buffer)
22700 (add-hook 'pre-command-hook 'org-unhighlight-once))
22701 (defun org-unhighlight-once ()
22702 (remove-hook 'pre-command-hook 'org-unhighlight-once)
22703 (org-unhighlight))
22705 (defun org-agenda-follow-mode ()
22706 "Toggle follow mode in an agenda buffer."
22707 (interactive)
22708 (setq org-agenda-follow-mode (not org-agenda-follow-mode))
22709 (org-agenda-set-mode-name)
22710 (message "Follow mode is %s"
22711 (if org-agenda-follow-mode "on" "off")))
22713 (defun org-agenda-log-mode ()
22714 "Toggle log mode in an agenda buffer."
22715 (interactive)
22716 (org-agenda-check-type t 'agenda 'timeline)
22717 (setq org-agenda-show-log (not org-agenda-show-log))
22718 (org-agenda-set-mode-name)
22719 (org-agenda-redo)
22720 (message "Log mode is %s"
22721 (if org-agenda-show-log "on" "off")))
22723 (defun org-agenda-toggle-diary ()
22724 "Toggle diary inclusion in an agenda buffer."
22725 (interactive)
22726 (org-agenda-check-type t 'agenda)
22727 (setq org-agenda-include-diary (not org-agenda-include-diary))
22728 (org-agenda-redo)
22729 (org-agenda-set-mode-name)
22730 (message "Diary inclusion turned %s"
22731 (if org-agenda-include-diary "on" "off")))
22733 (defun org-agenda-toggle-time-grid ()
22734 "Toggle time grid in an agenda buffer."
22735 (interactive)
22736 (org-agenda-check-type t 'agenda)
22737 (setq org-agenda-use-time-grid (not org-agenda-use-time-grid))
22738 (org-agenda-redo)
22739 (org-agenda-set-mode-name)
22740 (message "Time-grid turned %s"
22741 (if org-agenda-use-time-grid "on" "off")))
22743 (defun org-agenda-set-mode-name ()
22744 "Set the mode name to indicate all the small mode settings."
22745 (setq mode-name
22746 (concat "Org-Agenda"
22747 (if (equal org-agenda-ndays 1) " Day" "")
22748 (if (equal org-agenda-ndays 7) " Week" "")
22749 (if org-agenda-follow-mode " Follow" "")
22750 (if org-agenda-include-diary " Diary" "")
22751 (if org-agenda-use-time-grid " Grid" "")
22752 (if org-agenda-show-log " Log" "")))
22753 (force-mode-line-update))
22755 (defun org-agenda-post-command-hook ()
22756 (and (eolp) (not (bolp)) (backward-char 1))
22757 (setq org-agenda-type (get-text-property (point) 'org-agenda-type))
22758 (if (and org-agenda-follow-mode
22759 (get-text-property (point) 'org-marker))
22760 (org-agenda-show)))
22762 (defun org-agenda-show-priority ()
22763 "Show the priority of the current item.
22764 This priority is composed of the main priority given with the [#A] cookies,
22765 and by additional input from the age of a schedules or deadline entry."
22766 (interactive)
22767 (let* ((pri (get-text-property (point-at-bol) 'priority)))
22768 (message "Priority is %d" (if pri pri -1000))))
22770 (defun org-agenda-show-tags ()
22771 "Show the tags applicable to the current item."
22772 (interactive)
22773 (let* ((tags (get-text-property (point-at-bol) 'tags)))
22774 (if tags
22775 (message "Tags are :%s:"
22776 (org-no-properties (mapconcat 'identity tags ":")))
22777 (message "No tags associated with this line"))))
22779 (defun org-agenda-goto (&optional highlight)
22780 "Go to the Org-mode file which contains the item at point."
22781 (interactive)
22782 (let* ((marker (or (get-text-property (point) 'org-marker)
22783 (org-agenda-error)))
22784 (buffer (marker-buffer marker))
22785 (pos (marker-position marker)))
22786 (switch-to-buffer-other-window buffer)
22787 (widen)
22788 (goto-char pos)
22789 (when (org-mode-p)
22790 (org-show-context 'agenda)
22791 (save-excursion
22792 (and (outline-next-heading)
22793 (org-flag-heading nil)))) ; show the next heading
22794 (recenter (/ (window-height) 2))
22795 (run-hooks 'org-agenda-after-show-hook)
22796 (and highlight (org-highlight (point-at-bol) (point-at-eol)))))
22798 (defvar org-agenda-after-show-hook nil
22799 "Normal hook run after an item has been shown from the agenda.
22800 Point is in the buffer where the item originated.")
22802 (defun org-agenda-kill ()
22803 "Kill the entry or subtree belonging to the current agenda entry."
22804 (interactive)
22805 (or (eq major-mode 'org-agenda-mode) (error "Not in agenda"))
22806 (let* ((marker (or (get-text-property (point) 'org-marker)
22807 (org-agenda-error)))
22808 (buffer (marker-buffer marker))
22809 (pos (marker-position marker))
22810 (type (get-text-property (point) 'type))
22811 dbeg dend (n 0) conf)
22812 (org-with-remote-undo buffer
22813 (with-current-buffer buffer
22814 (save-excursion
22815 (goto-char pos)
22816 (if (and (org-mode-p) (not (member type '("sexp"))))
22817 (setq dbeg (progn (org-back-to-heading t) (point))
22818 dend (org-end-of-subtree t t))
22819 (setq dbeg (point-at-bol)
22820 dend (min (point-max) (1+ (point-at-eol)))))
22821 (goto-char dbeg)
22822 (while (re-search-forward "^[ \t]*\\S-" dend t) (setq n (1+ n)))))
22823 (setq conf (or (eq t org-agenda-confirm-kill)
22824 (and (numberp org-agenda-confirm-kill)
22825 (> n org-agenda-confirm-kill))))
22826 (and conf
22827 (not (y-or-n-p
22828 (format "Delete entry with %d lines in buffer \"%s\"? "
22829 n (buffer-name buffer))))
22830 (error "Abort"))
22831 (org-remove-subtree-entries-from-agenda buffer dbeg dend)
22832 (with-current-buffer buffer (delete-region dbeg dend))
22833 (message "Agenda item and source killed"))))
22835 (defun org-agenda-archive ()
22836 "Kill the entry or subtree belonging to the current agenda entry."
22837 (interactive)
22838 (or (eq major-mode 'org-agenda-mode) (error "Not in agenda"))
22839 (let* ((marker (or (get-text-property (point) 'org-marker)
22840 (org-agenda-error)))
22841 (buffer (marker-buffer marker))
22842 (pos (marker-position marker)))
22843 (org-with-remote-undo buffer
22844 (with-current-buffer buffer
22845 (if (org-mode-p)
22846 (save-excursion
22847 (goto-char pos)
22848 (org-remove-subtree-entries-from-agenda)
22849 (org-back-to-heading t)
22850 (org-archive-subtree))
22851 (error "Archiving works only in Org-mode files"))))))
22853 (defun org-remove-subtree-entries-from-agenda (&optional buf beg end)
22854 "Remove all lines in the agenda that correspond to a given subtree.
22855 The subtree is the one in buffer BUF, starting at BEG and ending at END.
22856 If this information is not given, the function uses the tree at point."
22857 (let ((buf (or buf (current-buffer))) m p)
22858 (save-excursion
22859 (unless (and beg end)
22860 (org-back-to-heading t)
22861 (setq beg (point))
22862 (org-end-of-subtree t)
22863 (setq end (point)))
22864 (set-buffer (get-buffer org-agenda-buffer-name))
22865 (save-excursion
22866 (goto-char (point-max))
22867 (beginning-of-line 1)
22868 (while (not (bobp))
22869 (when (and (setq m (get-text-property (point) 'org-marker))
22870 (equal buf (marker-buffer m))
22871 (setq p (marker-position m))
22872 (>= p beg)
22873 (<= p end))
22874 (let ((inhibit-read-only t))
22875 (delete-region (point-at-bol) (1+ (point-at-eol)))))
22876 (beginning-of-line 0))))))
22878 (defun org-agenda-open-link ()
22879 "Follow the link in the current line, if any."
22880 (interactive)
22881 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local)
22882 (save-excursion
22883 (save-restriction
22884 (narrow-to-region (point-at-bol) (point-at-eol))
22885 (org-open-at-point))))
22887 (defun org-agenda-copy-local-variable (var)
22888 "Get a variable from a referenced buffer and install it here."
22889 (let ((m (get-text-property (point) 'org-marker)))
22890 (when (and m (buffer-live-p (marker-buffer m)))
22891 (org-set-local var (with-current-buffer (marker-buffer m)
22892 (symbol-value var))))))
22894 (defun org-agenda-switch-to (&optional delete-other-windows)
22895 "Go to the Org-mode file which contains the item at point."
22896 (interactive)
22897 (let* ((marker (or (get-text-property (point) 'org-marker)
22898 (org-agenda-error)))
22899 (buffer (marker-buffer marker))
22900 (pos (marker-position marker)))
22901 (switch-to-buffer buffer)
22902 (and delete-other-windows (delete-other-windows))
22903 (widen)
22904 (goto-char pos)
22905 (when (org-mode-p)
22906 (org-show-context 'agenda)
22907 (save-excursion
22908 (and (outline-next-heading)
22909 (org-flag-heading nil)))))) ; show the next heading
22911 (defun org-agenda-goto-mouse (ev)
22912 "Go to the Org-mode file which contains the item at the mouse click."
22913 (interactive "e")
22914 (mouse-set-point ev)
22915 (org-agenda-goto))
22917 (defun org-agenda-show ()
22918 "Display the Org-mode file which contains the item at point."
22919 (interactive)
22920 (let ((win (selected-window)))
22921 (org-agenda-goto t)
22922 (select-window win)))
22924 (defun org-agenda-recenter (arg)
22925 "Display the Org-mode file which contains the item at point and recenter."
22926 (interactive "P")
22927 (let ((win (selected-window)))
22928 (org-agenda-goto t)
22929 (recenter arg)
22930 (select-window win)))
22932 (defun org-agenda-show-mouse (ev)
22933 "Display the Org-mode file which contains the item at the mouse click."
22934 (interactive "e")
22935 (mouse-set-point ev)
22936 (org-agenda-show))
22938 (defun org-agenda-check-no-diary ()
22939 "Check if the entry is a diary link and abort if yes."
22940 (if (get-text-property (point) 'org-agenda-diary-link)
22941 (org-agenda-error)))
22943 (defun org-agenda-error ()
22944 (error "Command not allowed in this line"))
22946 (defun org-agenda-tree-to-indirect-buffer ()
22947 "Show the subtree corresponding to the current entry in an indirect buffer.
22948 This calls the command `org-tree-to-indirect-buffer' from the original
22949 Org-mode buffer.
22950 With numerical prefix arg ARG, go up to this level and then take that tree.
22951 With a C-u prefix, make a separate frame for this tree (i.e. don't use the
22952 dedicated frame)."
22953 (interactive)
22954 (org-agenda-check-no-diary)
22955 (let* ((marker (or (get-text-property (point) 'org-marker)
22956 (org-agenda-error)))
22957 (buffer (marker-buffer marker))
22958 (pos (marker-position marker)))
22959 (with-current-buffer buffer
22960 (save-excursion
22961 (goto-char pos)
22962 (call-interactively 'org-tree-to-indirect-buffer)))))
22964 (defvar org-last-heading-marker (make-marker)
22965 "Marker pointing to the headline that last changed its TODO state
22966 by a remote command from the agenda.")
22968 (defun org-agenda-todo-nextset ()
22969 "Switch TODO entry to next sequence."
22970 (interactive)
22971 (org-agenda-todo 'nextset))
22973 (defun org-agenda-todo-previousset ()
22974 "Switch TODO entry to previous sequence."
22975 (interactive)
22976 (org-agenda-todo 'previousset))
22978 (defun org-agenda-todo (&optional arg)
22979 "Cycle TODO state of line at point, also in Org-mode file.
22980 This changes the line at point, all other lines in the agenda referring to
22981 the same tree node, and the headline of the tree node in the Org-mode file."
22982 (interactive "P")
22983 (org-agenda-check-no-diary)
22984 (let* ((col (current-column))
22985 (marker (or (get-text-property (point) 'org-marker)
22986 (org-agenda-error)))
22987 (buffer (marker-buffer marker))
22988 (pos (marker-position marker))
22989 (hdmarker (get-text-property (point) 'org-hd-marker))
22990 (inhibit-read-only t)
22991 newhead)
22992 (org-with-remote-undo buffer
22993 (with-current-buffer buffer
22994 (widen)
22995 (goto-char pos)
22996 (org-show-context 'agenda)
22997 (save-excursion
22998 (and (outline-next-heading)
22999 (org-flag-heading nil))) ; show the next heading
23000 (org-todo arg)
23001 (and (bolp) (forward-char 1))
23002 (setq newhead (org-get-heading))
23003 (save-excursion
23004 (org-back-to-heading)
23005 (move-marker org-last-heading-marker (point))))
23006 (beginning-of-line 1)
23007 (save-excursion
23008 (org-agenda-change-all-lines newhead hdmarker 'fixface))
23009 (move-to-column col))))
23011 (defun org-agenda-change-all-lines (newhead hdmarker &optional fixface)
23012 "Change all lines in the agenda buffer which match HDMARKER.
23013 The new content of the line will be NEWHEAD (as modified by
23014 `org-format-agenda-item'). HDMARKER is checked with
23015 `equal' against all `org-hd-marker' text properties in the file.
23016 If FIXFACE is non-nil, the face of each item is modified acording to
23017 the new TODO state."
23018 (let* ((inhibit-read-only t)
23019 props m pl undone-face done-face finish new dotime cat tags)
23020 (save-excursion
23021 (goto-char (point-max))
23022 (beginning-of-line 1)
23023 (while (not finish)
23024 (setq finish (bobp))
23025 (when (and (setq m (get-text-property (point) 'org-hd-marker))
23026 (equal m hdmarker))
23027 (setq props (text-properties-at (point))
23028 dotime (get-text-property (point) 'dotime)
23029 cat (get-text-property (point) 'org-category)
23030 tags (get-text-property (point) 'tags)
23031 new (org-format-agenda-item "x" newhead cat tags dotime 'noprefix)
23032 pl (get-text-property (point) 'prefix-length)
23033 undone-face (get-text-property (point) 'undone-face)
23034 done-face (get-text-property (point) 'done-face))
23035 (move-to-column pl)
23036 (cond
23037 ((equal new "")
23038 (beginning-of-line 1)
23039 (and (looking-at ".*\n?") (replace-match "")))
23040 ((looking-at ".*")
23041 (replace-match new t t)
23042 (beginning-of-line 1)
23043 (add-text-properties (point-at-bol) (point-at-eol) props)
23044 (when fixface
23045 (add-text-properties
23046 (point-at-bol) (point-at-eol)
23047 (list 'face
23048 (if org-last-todo-state-is-todo
23049 undone-face done-face))))
23050 (org-agenda-highlight-todo 'line)
23051 (beginning-of-line 1))
23052 (t (error "Line update did not work"))))
23053 (beginning-of-line 0)))
23054 (org-finalize-agenda)))
23056 (defun org-agenda-align-tags (&optional line)
23057 "Align all tags in agenda items to `org-agenda-tags-column'."
23058 (let ((inhibit-read-only t) l c)
23059 (save-excursion
23060 (goto-char (if line (point-at-bol) (point-min)))
23061 (while (re-search-forward (org-re "\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$")
23062 (if line (point-at-eol) nil) t)
23063 (add-text-properties
23064 (match-beginning 2) (match-end 2)
23065 (list 'face (list 'org-tag (get-text-property
23066 (match-beginning 2) 'face))))
23067 (setq l (- (match-end 2) (match-beginning 2))
23068 c (if (< org-agenda-tags-column 0)
23069 (- (abs org-agenda-tags-column) l)
23070 org-agenda-tags-column))
23071 (delete-region (match-beginning 1) (match-end 1))
23072 (goto-char (match-beginning 1))
23073 (insert (org-add-props
23074 (make-string (max 1 (- c (current-column))) ?\ )
23075 (text-properties-at (point))))))))
23077 (defun org-agenda-priority-up ()
23078 "Increase the priority of line at point, also in Org-mode file."
23079 (interactive)
23080 (org-agenda-priority 'up))
23082 (defun org-agenda-priority-down ()
23083 "Decrease the priority of line at point, also in Org-mode file."
23084 (interactive)
23085 (org-agenda-priority 'down))
23087 (defun org-agenda-priority (&optional force-direction)
23088 "Set the priority of line at point, also in Org-mode file.
23089 This changes the line at point, all other lines in the agenda referring to
23090 the same tree node, and the headline of the tree node in the Org-mode file."
23091 (interactive)
23092 (org-agenda-check-no-diary)
23093 (let* ((marker (or (get-text-property (point) 'org-marker)
23094 (org-agenda-error)))
23095 (hdmarker (get-text-property (point) 'org-hd-marker))
23096 (buffer (marker-buffer hdmarker))
23097 (pos (marker-position hdmarker))
23098 (inhibit-read-only t)
23099 newhead)
23100 (org-with-remote-undo buffer
23101 (with-current-buffer buffer
23102 (widen)
23103 (goto-char pos)
23104 (org-show-context 'agenda)
23105 (save-excursion
23106 (and (outline-next-heading)
23107 (org-flag-heading nil))) ; show the next heading
23108 (funcall 'org-priority force-direction)
23109 (end-of-line 1)
23110 (setq newhead (org-get-heading)))
23111 (org-agenda-change-all-lines newhead hdmarker)
23112 (beginning-of-line 1))))
23114 (defun org-get-tags-at (&optional pos)
23115 "Get a list of all headline tags applicable at POS.
23116 POS defaults to point. If tags are inherited, the list contains
23117 the targets in the same sequence as the headlines appear, i.e.
23118 the tags of the current headline come last."
23119 (interactive)
23120 (let (tags lastpos)
23121 (save-excursion
23122 (save-restriction
23123 (widen)
23124 (goto-char (or pos (point)))
23125 (save-match-data
23126 (org-back-to-heading t)
23127 (condition-case nil
23128 (while (not (equal lastpos (point)))
23129 (setq lastpos (point))
23130 (if (looking-at (org-re "[^\r\n]+?:\\([[:alnum:]_@:]+\\):[ \t]*$"))
23131 (setq tags (append (org-split-string
23132 (org-match-string-no-properties 1) ":")
23133 tags)))
23134 (or org-use-tag-inheritance (error ""))
23135 (org-up-heading-all 1))
23136 (error nil))))
23137 tags)))
23139 ;; FIXME: should fix the tags property of the agenda line.
23140 (defun org-agenda-set-tags ()
23141 "Set tags for the current headline."
23142 (interactive)
23143 (org-agenda-check-no-diary)
23144 (if (and (org-region-active-p) (interactive-p))
23145 (call-interactively 'org-change-tag-in-region)
23146 (org-agenda-show) ;;; FIXME This is a stupid hack and should not be needed
23147 (let* ((hdmarker (or (get-text-property (point) 'org-hd-marker)
23148 (org-agenda-error)))
23149 (buffer (marker-buffer hdmarker))
23150 (pos (marker-position hdmarker))
23151 (inhibit-read-only t)
23152 newhead)
23153 (org-with-remote-undo buffer
23154 (with-current-buffer buffer
23155 (widen)
23156 (goto-char pos)
23157 (save-excursion
23158 (org-show-context 'agenda))
23159 (save-excursion
23160 (and (outline-next-heading)
23161 (org-flag-heading nil))) ; show the next heading
23162 (goto-char pos)
23163 (call-interactively 'org-set-tags)
23164 (end-of-line 1)
23165 (setq newhead (org-get-heading)))
23166 (org-agenda-change-all-lines newhead hdmarker)
23167 (beginning-of-line 1)))))
23169 (defun org-agenda-toggle-archive-tag ()
23170 "Toggle the archive tag for the current entry."
23171 (interactive)
23172 (org-agenda-check-no-diary)
23173 (org-agenda-show) ;;; FIXME This is a stupid hack and should not be needed
23174 (let* ((hdmarker (or (get-text-property (point) 'org-hd-marker)
23175 (org-agenda-error)))
23176 (buffer (marker-buffer hdmarker))
23177 (pos (marker-position hdmarker))
23178 (inhibit-read-only t)
23179 newhead)
23180 (org-with-remote-undo buffer
23181 (with-current-buffer buffer
23182 (widen)
23183 (goto-char pos)
23184 (org-show-context 'agenda)
23185 (save-excursion
23186 (and (outline-next-heading)
23187 (org-flag-heading nil))) ; show the next heading
23188 (call-interactively 'org-toggle-archive-tag)
23189 (end-of-line 1)
23190 (setq newhead (org-get-heading)))
23191 (org-agenda-change-all-lines newhead hdmarker)
23192 (beginning-of-line 1))))
23194 (defun org-agenda-date-later (arg &optional what)
23195 "Change the date of this item to one day later."
23196 (interactive "p")
23197 (org-agenda-check-type t 'agenda 'timeline)
23198 (org-agenda-check-no-diary)
23199 (let* ((marker (or (get-text-property (point) 'org-marker)
23200 (org-agenda-error)))
23201 (buffer (marker-buffer marker))
23202 (pos (marker-position marker)))
23203 (org-with-remote-undo buffer
23204 (with-current-buffer buffer
23205 (widen)
23206 (goto-char pos)
23207 (if (not (org-at-timestamp-p))
23208 (error "Cannot find time stamp"))
23209 (org-timestamp-change arg (or what 'day)))
23210 (org-agenda-show-new-time marker org-last-changed-timestamp))
23211 (message "Time stamp changed to %s" org-last-changed-timestamp)))
23213 (defun org-agenda-date-earlier (arg &optional what)
23214 "Change the date of this item to one day earlier."
23215 (interactive "p")
23216 (org-agenda-date-later (- arg) what))
23218 (defun org-agenda-show-new-time (marker stamp &optional prefix)
23219 "Show new date stamp via text properties."
23220 ;; We use text properties to make this undoable
23221 (let ((inhibit-read-only t))
23222 (setq stamp (concat " " prefix " => " stamp))
23223 (save-excursion
23224 (goto-char (point-max))
23225 (while (not (bobp))
23226 (when (equal marker (get-text-property (point) 'org-marker))
23227 (move-to-column (- (window-width) (length stamp)) t)
23228 (if (featurep 'xemacs)
23229 ;; Use `duplicable' property to trigger undo recording
23230 (let ((ex (make-extent nil nil))
23231 (gl (make-glyph stamp)))
23232 (set-glyph-face gl 'secondary-selection)
23233 (set-extent-properties
23234 ex (list 'invisible t 'end-glyph gl 'duplicable t))
23235 (insert-extent ex (1- (point)) (point-at-eol)))
23236 (add-text-properties
23237 (1- (point)) (point-at-eol)
23238 (list 'display (org-add-props stamp nil
23239 'face 'secondary-selection))))
23240 (beginning-of-line 1))
23241 (beginning-of-line 0)))))
23243 (defun org-agenda-date-prompt (arg)
23244 "Change the date of this item. Date is prompted for, with default today.
23245 The prefix ARG is passed to the `org-time-stamp' command and can therefore
23246 be used to request time specification in the time stamp."
23247 (interactive "P")
23248 (org-agenda-check-type t 'agenda 'timeline)
23249 (org-agenda-check-no-diary)
23250 (let* ((marker (or (get-text-property (point) 'org-marker)
23251 (org-agenda-error)))
23252 (buffer (marker-buffer marker))
23253 (pos (marker-position marker)))
23254 (org-with-remote-undo buffer
23255 (with-current-buffer buffer
23256 (widen)
23257 (goto-char pos)
23258 (if (not (org-at-timestamp-p))
23259 (error "Cannot find time stamp"))
23260 (org-time-stamp arg)
23261 (message "Time stamp changed to %s" org-last-changed-timestamp)))))
23263 (defun org-agenda-schedule (arg)
23264 "Schedule the item at point."
23265 (interactive "P")
23266 (org-agenda-check-type t 'agenda 'timeline 'todo 'tags)
23267 (org-agenda-check-no-diary)
23268 (let* ((marker (or (get-text-property (point) 'org-marker)
23269 (org-agenda-error)))
23270 (buffer (marker-buffer marker))
23271 (pos (marker-position marker))
23272 (org-insert-labeled-timestamps-at-point nil)
23274 (message "%s" (marker-insertion-type marker)) (sit-for 3)
23275 (set-marker-insertion-type marker t)
23276 (org-with-remote-undo buffer
23277 (with-current-buffer buffer
23278 (widen)
23279 (goto-char pos)
23280 (setq ts (org-schedule arg)))
23281 (org-agenda-show-new-time marker ts "S"))
23282 (message "Item scheduled for %s" ts)))
23284 (defun org-agenda-deadline (arg)
23285 "Schedule the item at point."
23286 (interactive "P")
23287 (org-agenda-check-type t 'agenda 'timeline 'todo 'tags)
23288 (org-agenda-check-no-diary)
23289 (let* ((marker (or (get-text-property (point) 'org-marker)
23290 (org-agenda-error)))
23291 (buffer (marker-buffer marker))
23292 (pos (marker-position marker))
23293 (org-insert-labeled-timestamps-at-point nil)
23295 (org-with-remote-undo buffer
23296 (with-current-buffer buffer
23297 (widen)
23298 (goto-char pos)
23299 (setq ts (org-deadline arg)))
23300 (org-agenda-show-new-time marker ts "S"))
23301 (message "Deadline for this item set to %s" ts)))
23303 (defun org-get-heading (&optional no-tags)
23304 "Return the heading of the current entry, without the stars."
23305 (save-excursion
23306 (org-back-to-heading t)
23307 (if (looking-at
23308 (if no-tags
23309 (org-re "\\*+[ \t]+\\([^\n\r]*?\\)\\([ \t]+:[[:alnum:]:_@]+:[ \t]*\\)?$")
23310 "\\*+[ \t]+\\([^\r\n]*\\)"))
23311 (match-string 1) "")))
23313 (defun org-agenda-clock-in (&optional arg)
23314 "Start the clock on the currently selected item."
23315 (interactive "P")
23316 (org-agenda-check-no-diary)
23317 (let* ((marker (or (get-text-property (point) 'org-marker)
23318 (org-agenda-error)))
23319 (pos (marker-position marker)))
23320 (org-with-remote-undo (marker-buffer marker)
23321 (with-current-buffer (marker-buffer marker)
23322 (widen)
23323 (goto-char pos)
23324 (org-clock-in)))))
23326 (defun org-agenda-clock-out (&optional arg)
23327 "Stop the currently running clock."
23328 (interactive "P")
23329 (unless (marker-buffer org-clock-marker)
23330 (error "No running clock"))
23331 (org-with-remote-undo (marker-buffer org-clock-marker)
23332 (org-clock-out)))
23334 (defun org-agenda-clock-cancel (&optional arg)
23335 "Cancel the currently running clock."
23336 (interactive "P")
23337 (unless (marker-buffer org-clock-marker)
23338 (error "No running clock"))
23339 (org-with-remote-undo (marker-buffer org-clock-marker)
23340 (org-clock-cancel)))
23342 (defun org-agenda-diary-entry ()
23343 "Make a diary entry, like the `i' command from the calendar.
23344 All the standard commands work: block, weekly etc."
23345 (interactive)
23346 (org-agenda-check-type t 'agenda 'timeline)
23347 (require 'diary-lib)
23348 (let* ((char (progn
23349 (message "Diary entry: [d]ay [w]eekly [m]onthly [y]early [a]nniversary [b]lock [c]yclic")
23350 (read-char-exclusive)))
23351 (cmd (cdr (assoc char
23352 '((?d . insert-diary-entry)
23353 (?w . insert-weekly-diary-entry)
23354 (?m . insert-monthly-diary-entry)
23355 (?y . insert-yearly-diary-entry)
23356 (?a . insert-anniversary-diary-entry)
23357 (?b . insert-block-diary-entry)
23358 (?c . insert-cyclic-diary-entry)))))
23359 (oldf (symbol-function 'calendar-cursor-to-date))
23360 ; (buf (get-file-buffer (substitute-in-file-name diary-file)))
23361 (point (point))
23362 (mark (or (mark t) (point))))
23363 (unless cmd
23364 (error "No command associated with <%c>" char))
23365 (unless (and (get-text-property point 'day)
23366 (or (not (equal ?b char))
23367 (get-text-property mark 'day)))
23368 (error "Don't know which date to use for diary entry"))
23369 ;; We implement this by hacking the `calendar-cursor-to-date' function
23370 ;; and the `calendar-mark-ring' variable. Saves a lot of code.
23371 (let ((calendar-mark-ring
23372 (list (calendar-gregorian-from-absolute
23373 (or (get-text-property mark 'day)
23374 (get-text-property point 'day))))))
23375 (unwind-protect
23376 (progn
23377 (fset 'calendar-cursor-to-date
23378 (lambda (&optional error)
23379 (calendar-gregorian-from-absolute
23380 (get-text-property point 'day))))
23381 (call-interactively cmd))
23382 (fset 'calendar-cursor-to-date oldf)))))
23385 (defun org-agenda-execute-calendar-command (cmd)
23386 "Execute a calendar command from the agenda, with the date associated to
23387 the cursor position."
23388 (org-agenda-check-type t 'agenda 'timeline)
23389 (require 'diary-lib)
23390 (unless (get-text-property (point) 'day)
23391 (error "Don't know which date to use for calendar command"))
23392 (let* ((oldf (symbol-function 'calendar-cursor-to-date))
23393 (point (point))
23394 (date (calendar-gregorian-from-absolute
23395 (get-text-property point 'day)))
23396 ;; the following 3 vars are needed in the calendar
23397 (displayed-day (extract-calendar-day date))
23398 (displayed-month (extract-calendar-month date))
23399 (displayed-year (extract-calendar-year date)))
23400 (unwind-protect
23401 (progn
23402 (fset 'calendar-cursor-to-date
23403 (lambda (&optional error)
23404 (calendar-gregorian-from-absolute
23405 (get-text-property point 'day))))
23406 (call-interactively cmd))
23407 (fset 'calendar-cursor-to-date oldf))))
23409 (defun org-agenda-phases-of-moon ()
23410 "Display the phases of the moon for the 3 months around the cursor date."
23411 (interactive)
23412 (org-agenda-execute-calendar-command 'calendar-phases-of-moon))
23414 (defun org-agenda-holidays ()
23415 "Display the holidays for the 3 months around the cursor date."
23416 (interactive)
23417 (org-agenda-execute-calendar-command 'list-calendar-holidays))
23419 (defun org-agenda-sunrise-sunset (arg)
23420 "Display sunrise and sunset for the cursor date.
23421 Latitude and longitude can be specified with the variables
23422 `calendar-latitude' and `calendar-longitude'. When called with prefix
23423 argument, latitude and longitude will be prompted for."
23424 (interactive "P")
23425 (let ((calendar-longitude (if arg nil calendar-longitude))
23426 (calendar-latitude (if arg nil calendar-latitude))
23427 (calendar-location-name
23428 (if arg "the given coordinates" calendar-location-name)))
23429 (org-agenda-execute-calendar-command 'calendar-sunrise-sunset)))
23431 (defun org-agenda-goto-calendar ()
23432 "Open the Emacs calendar with the date at the cursor."
23433 (interactive)
23434 (org-agenda-check-type t 'agenda 'timeline)
23435 (let* ((day (or (get-text-property (point) 'day)
23436 (error "Don't know which date to open in calendar")))
23437 (date (calendar-gregorian-from-absolute day))
23438 (calendar-move-hook nil)
23439 (view-calendar-holidays-initially nil)
23440 (view-diary-entries-initially nil))
23441 (calendar)
23442 (calendar-goto-date date)))
23444 (defun org-calendar-goto-agenda ()
23445 "Compute the Org-mode agenda for the calendar date displayed at the cursor.
23446 This is a command that has to be installed in `calendar-mode-map'."
23447 (interactive)
23448 (org-agenda-list nil (calendar-absolute-from-gregorian
23449 (calendar-cursor-to-date))
23450 nil))
23452 (defun org-agenda-convert-date ()
23453 (interactive)
23454 (org-agenda-check-type t 'agenda 'timeline)
23455 (let ((day (get-text-property (point) 'day))
23456 date s)
23457 (unless day
23458 (error "Don't know which date to convert"))
23459 (setq date (calendar-gregorian-from-absolute day))
23460 (setq s (concat
23461 "Gregorian: " (calendar-date-string date) "\n"
23462 "ISO: " (calendar-iso-date-string date) "\n"
23463 "Day of Yr: " (calendar-day-of-year-string date) "\n"
23464 "Julian: " (calendar-julian-date-string date) "\n"
23465 "Astron. JD: " (calendar-astro-date-string date)
23466 " (Julian date number at noon UTC)\n"
23467 "Hebrew: " (calendar-hebrew-date-string date) " (until sunset)\n"
23468 "Islamic: " (calendar-islamic-date-string date) " (until sunset)\n"
23469 "French: " (calendar-french-date-string date) "\n"
23470 "Baha'i: " (calendar-bahai-date-string date) " (until sunset)\n"
23471 "Mayan: " (calendar-mayan-date-string date) "\n"
23472 "Coptic: " (calendar-coptic-date-string date) "\n"
23473 "Ethiopic: " (calendar-ethiopic-date-string date) "\n"
23474 "Persian: " (calendar-persian-date-string date) "\n"
23475 "Chinese: " (calendar-chinese-date-string date) "\n"))
23476 (with-output-to-temp-buffer "*Dates*"
23477 (princ s))
23478 (if (fboundp 'fit-window-to-buffer)
23479 (fit-window-to-buffer (get-buffer-window "*Dates*")))))
23482 ;;;; Embedded LaTeX
23484 (defvar org-cdlatex-mode-map (make-sparse-keymap)
23485 "Keymap for the minor `org-cdlatex-mode'.")
23487 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
23488 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
23489 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
23490 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
23491 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
23493 (defvar org-cdlatex-texmathp-advice-is-done nil
23494 "Flag remembering if we have applied the advice to texmathp already.")
23496 (define-minor-mode org-cdlatex-mode
23497 "Toggle the minor `org-cdlatex-mode'.
23498 This mode supports entering LaTeX environment and math in LaTeX fragments
23499 in Org-mode.
23500 \\{org-cdlatex-mode-map}"
23501 nil " OCDL" nil
23502 (when org-cdlatex-mode (require 'cdlatex))
23503 (unless org-cdlatex-texmathp-advice-is-done
23504 (setq org-cdlatex-texmathp-advice-is-done t)
23505 (defadvice texmathp (around org-math-always-on activate)
23506 "Always return t in org-mode buffers.
23507 This is because we want to insert math symbols without dollars even outside
23508 the LaTeX math segments. If Orgmode thinks that point is actually inside
23509 en embedded LaTeX fragement, let texmathp do its job.
23510 \\[org-cdlatex-mode-map]"
23511 (interactive)
23512 (let (p)
23513 (cond
23514 ((not (org-mode-p)) ad-do-it)
23515 ((eq this-command 'cdlatex-math-symbol)
23516 (setq ad-return-value t
23517 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
23519 (let ((p (org-inside-LaTeX-fragment-p)))
23520 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
23521 (setq ad-return-value t
23522 texmathp-why '("Org-mode embedded math" . 0))
23523 (if p ad-do-it)))))))))
23525 (defun turn-on-org-cdlatex ()
23526 "Unconditionally turn on `org-cdlatex-mode'."
23527 (org-cdlatex-mode 1))
23529 (defun org-inside-LaTeX-fragment-p ()
23530 "Test if point is inside a LaTeX fragment.
23531 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
23532 sequence appearing also before point.
23533 Even though the matchers for math are configurable, this function assumes
23534 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
23535 delimiters are skipped when they have been removed by customization.
23536 The return value is nil, or a cons cell with the delimiter and
23537 and the position of this delimiter.
23539 This function does a reasonably good job, but can locally be fooled by
23540 for example currency specifications. For example it will assume being in
23541 inline math after \"$22.34\". The LaTeX fragment formatter will only format
23542 fragments that are properly closed, but during editing, we have to live
23543 with the uncertainty caused by missing closing delimiters. This function
23544 looks only before point, not after."
23545 (catch 'exit
23546 (let ((pos (point))
23547 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
23548 (lim (progn
23549 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
23550 (point)))
23551 dd-on str (start 0) m re)
23552 (goto-char pos)
23553 (when dodollar
23554 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
23555 re (nth 1 (assoc "$" org-latex-regexps)))
23556 (while (string-match re str start)
23557 (cond
23558 ((= (match-end 0) (length str))
23559 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
23560 ((= (match-end 0) (- (length str) 5))
23561 (throw 'exit nil))
23562 (t (setq start (match-end 0))))))
23563 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
23564 (goto-char pos)
23565 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
23566 (and (match-beginning 2) (throw 'exit nil))
23567 ;; count $$
23568 (while (re-search-backward "\\$\\$" lim t)
23569 (setq dd-on (not dd-on)))
23570 (goto-char pos)
23571 (if dd-on (cons "$$" m))))))
23574 (defun org-try-cdlatex-tab ()
23575 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
23576 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
23577 - inside a LaTeX fragment, or
23578 - after the first word in a line, where an abbreviation expansion could
23579 insert a LaTeX environment."
23580 (when org-cdlatex-mode
23581 (cond
23582 ((save-excursion
23583 (skip-chars-backward "a-zA-Z0-9*")
23584 (skip-chars-backward " \t")
23585 (bolp))
23586 (cdlatex-tab) t)
23587 ((org-inside-LaTeX-fragment-p)
23588 (cdlatex-tab) t)
23589 (t nil))))
23591 (defun org-cdlatex-underscore-caret (&optional arg)
23592 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
23593 Revert to the normal definition outside of these fragments."
23594 (interactive "P")
23595 (if (org-inside-LaTeX-fragment-p)
23596 (call-interactively 'cdlatex-sub-superscript)
23597 (let (org-cdlatex-mode)
23598 (call-interactively (key-binding (vector last-input-event))))))
23600 (defun org-cdlatex-math-modify (&optional arg)
23601 "Execute `cdlatex-math-modify' in LaTeX fragments.
23602 Revert to the normal definition outside of these fragments."
23603 (interactive "P")
23604 (if (org-inside-LaTeX-fragment-p)
23605 (call-interactively 'cdlatex-math-modify)
23606 (let (org-cdlatex-mode)
23607 (call-interactively (key-binding (vector last-input-event))))))
23609 (defvar org-latex-fragment-image-overlays nil
23610 "List of overlays carrying the images of latex fragments.")
23611 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
23613 (defun org-remove-latex-fragment-image-overlays ()
23614 "Remove all overlays with LaTeX fragment images in current buffer."
23615 (mapc 'org-delete-overlay org-latex-fragment-image-overlays)
23616 (setq org-latex-fragment-image-overlays nil))
23618 (defun org-preview-latex-fragment (&optional subtree)
23619 "Preview the LaTeX fragment at point, or all locally or globally.
23620 If the cursor is in a LaTeX fragment, create the image and overlay
23621 it over the source code. If there is no fragment at point, display
23622 all fragments in the current text, from one headline to the next. With
23623 prefix SUBTREE, display all fragments in the current subtree. With a
23624 double prefix `C-u C-u', or when the cursor is before the first headline,
23625 display all fragments in the buffer.
23626 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
23627 (interactive "P")
23628 (org-remove-latex-fragment-image-overlays)
23629 (save-excursion
23630 (save-restriction
23631 (let (beg end at msg)
23632 (cond
23633 ((or (equal subtree '(16))
23634 (not (save-excursion
23635 (re-search-backward (concat "^" outline-regexp) nil t))))
23636 (setq beg (point-min) end (point-max)
23637 msg "Creating images for buffer...%s"))
23638 ((equal subtree '(4))
23639 (org-back-to-heading)
23640 (setq beg (point) end (org-end-of-subtree t)
23641 msg "Creating images for subtree...%s"))
23643 (if (setq at (org-inside-LaTeX-fragment-p))
23644 (goto-char (max (point-min) (- (cdr at) 2)))
23645 (org-back-to-heading))
23646 (setq beg (point) end (progn (outline-next-heading) (point))
23647 msg (if at "Creating image...%s"
23648 "Creating images for entry...%s"))))
23649 (message msg "")
23650 (narrow-to-region beg end)
23651 (goto-char beg)
23652 (org-format-latex
23653 (concat "ltxpng/" (file-name-sans-extension
23654 (file-name-nondirectory
23655 buffer-file-name)))
23656 default-directory 'overlays msg at 'forbuffer)
23657 (message msg "done. Use `C-c C-c' to remove images.")))))
23659 (defvar org-latex-regexps
23660 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
23661 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
23662 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
23663 ("$" "\\([^$]\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([ .,?;:'\")\000]\\|$\\)" 2 nil)
23664 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
23665 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 t)
23666 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 t))
23667 "Regular expressions for matching embedded LaTeX.")
23669 (defun org-format-latex (prefix &optional dir overlays msg at forbuffer)
23670 "Replace LaTeX fragments with links to an image, and produce images."
23671 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
23672 (let* ((prefixnodir (file-name-nondirectory prefix))
23673 (absprefix (expand-file-name prefix dir))
23674 (todir (file-name-directory absprefix))
23675 (opt org-format-latex-options)
23676 (matchers (plist-get opt :matchers))
23677 (re-list org-latex-regexps)
23678 (cnt 0) txt link beg end re e checkdir
23679 m n block linkfile movefile ov)
23680 ;; Check if there are old images files with this prefix, and remove them
23681 (when (file-directory-p todir)
23682 (mapc 'delete-file
23683 (directory-files
23684 todir 'full
23685 (concat (regexp-quote prefixnodir) "_[0-9]+\\.png$"))))
23686 ;; Check the different regular expressions
23687 (while (setq e (pop re-list))
23688 (setq m (car e) re (nth 1 e) n (nth 2 e)
23689 block (if (nth 3 e) "\n\n" ""))
23690 (when (member m matchers)
23691 (goto-char (point-min))
23692 (while (re-search-forward re nil t)
23693 (when (or (not at) (equal (cdr at) (match-beginning n)))
23694 (setq txt (match-string n)
23695 beg (match-beginning n) end (match-end n)
23696 cnt (1+ cnt)
23697 linkfile (format "%s_%04d.png" prefix cnt)
23698 movefile (format "%s_%04d.png" absprefix cnt)
23699 link (concat block "[[file:" linkfile "]]" block))
23700 (if msg (message msg cnt))
23701 (goto-char beg)
23702 (unless checkdir ; make sure the directory exists
23703 (setq checkdir t)
23704 (or (file-directory-p todir) (make-directory todir)))
23705 (org-create-formula-image
23706 txt movefile opt forbuffer)
23707 (if overlays
23708 (progn
23709 (setq ov (org-make-overlay beg end))
23710 (if (featurep 'xemacs)
23711 (progn
23712 (org-overlay-put ov 'invisible t)
23713 (org-overlay-put
23714 ov 'end-glyph
23715 (make-glyph (vector 'png :file movefile))))
23716 (org-overlay-put
23717 ov 'display
23718 (list 'image :type 'png :file movefile :ascent 'center)))
23719 (push ov org-latex-fragment-image-overlays)
23720 (goto-char end))
23721 (delete-region beg end)
23722 (insert link))))))))
23724 ;; This function borrows from Ganesh Swami's latex2png.el
23725 (defun org-create-formula-image (string tofile options buffer)
23726 (let* ((tmpdir (if (featurep 'xemacs)
23727 (temp-directory)
23728 temporary-file-directory))
23729 (texfilebase (make-temp-name
23730 (expand-file-name "orgtex" tmpdir)))
23731 (texfile (concat texfilebase ".tex"))
23732 (dvifile (concat texfilebase ".dvi"))
23733 (pngfile (concat texfilebase ".png"))
23734 (fnh (face-attribute 'default :height nil))
23735 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
23736 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
23737 (fg (or (plist-get options (if buffer :foreground :html-foreground))
23738 "Black"))
23739 (bg (or (plist-get options (if buffer :background :html-background))
23740 "Transparent")))
23741 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
23742 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
23743 (with-temp-file texfile
23744 (insert org-format-latex-header
23745 "\n\\begin{document}\n" string "\n\\end{document}\n"))
23746 (let ((dir default-directory))
23747 (condition-case nil
23748 (progn
23749 (cd tmpdir)
23750 (call-process "latex" nil nil nil texfile))
23751 (error nil))
23752 (cd dir))
23753 (if (not (file-exists-p dvifile))
23754 (progn (message "Failed to create dvi file from %s" texfile) nil)
23755 (call-process "dvipng" nil nil nil
23756 "-E" "-fg" fg "-bg" bg
23757 "-D" dpi
23758 ;;"-x" scale "-y" scale
23759 "-T" "tight"
23760 "-o" pngfile
23761 dvifile)
23762 (if (not (file-exists-p pngfile))
23763 (progn (message "Failed to create png file from %s" texfile) nil)
23764 ;; Use the requested file name and clean up
23765 (copy-file pngfile tofile 'replace)
23766 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
23767 (delete-file (concat texfilebase e)))
23768 pngfile))))
23770 (defun org-dvipng-color (attr)
23771 "Return an rgb color specification for dvipng."
23772 (apply 'format "rgb %s %s %s"
23773 (mapcar 'org-normalize-color
23774 (color-values (face-attribute 'default attr nil)))))
23776 (defun org-normalize-color (value)
23777 "Return string to be used as color value for an RGB component."
23778 (format "%g" (/ value 65535.0)))
23780 ;;;; Exporting
23782 ;;; Variables, constants, and parameter plists
23784 (defconst org-level-max 20)
23786 (defvar org-export-html-preamble nil
23787 "Preamble, to be inserted just after <body>. Set by publishing functions.")
23788 (defvar org-export-html-postamble nil
23789 "Preamble, to be inserted just before </body>. Set by publishing functions.")
23790 (defvar org-export-html-auto-preamble t
23791 "Should default preamble be inserted? Set by publishing functions.")
23792 (defvar org-export-html-auto-postamble t
23793 "Should default postamble be inserted? Set by publishing functions.")
23794 (defvar org-current-export-file nil) ; dynamically scoped parameter
23795 (defvar org-current-export-dir nil) ; dynamically scoped parameter
23798 (defconst org-export-plist-vars
23799 '((:language . org-export-default-language)
23800 (:customtime . org-display-custom-times)
23801 (:headline-levels . org-export-headline-levels)
23802 (:section-numbers . org-export-with-section-numbers)
23803 (:table-of-contents . org-export-with-toc)
23804 (:preserve-breaks . org-export-preserve-breaks)
23805 (:archived-trees . org-export-with-archived-trees)
23806 (:emphasize . org-export-with-emphasize)
23807 (:sub-superscript . org-export-with-sub-superscripts)
23808 (:special-strings . org-export-with-special-strings)
23809 (:footnotes . org-export-with-footnotes)
23810 (:drawers . org-export-with-drawers)
23811 (:tags . org-export-with-tags)
23812 (:TeX-macros . org-export-with-TeX-macros)
23813 (:LaTeX-fragments . org-export-with-LaTeX-fragments)
23814 (:skip-before-1st-heading . org-export-skip-text-before-1st-heading)
23815 (:fixed-width . org-export-with-fixed-width)
23816 (:timestamps . org-export-with-timestamps)
23817 (:author-info . org-export-author-info)
23818 (:time-stamp-file . org-export-time-stamp-file)
23819 (:tables . org-export-with-tables)
23820 (:table-auto-headline . org-export-highlight-first-table-line)
23821 (:style . org-export-html-style)
23822 (:agenda-style . org-agenda-export-html-style)
23823 (:convert-org-links . org-export-html-link-org-files-as-html)
23824 (:inline-images . org-export-html-inline-images)
23825 (:html-extension . org-export-html-extension)
23826 (:html-table-tag . org-export-html-table-tag)
23827 (:expand-quoted-html . org-export-html-expand)
23828 (:timestamp . org-export-html-with-timestamp)
23829 (:publishing-directory . org-export-publishing-directory)
23830 (:preamble . org-export-html-preamble)
23831 (:postamble . org-export-html-postamble)
23832 (:auto-preamble . org-export-html-auto-preamble)
23833 (:auto-postamble . org-export-html-auto-postamble)
23834 (:author . user-full-name)
23835 (:email . user-mail-address)))
23837 (defun org-default-export-plist ()
23838 "Return the property list with default settings for the export variables."
23839 (let ((l org-export-plist-vars) rtn e)
23840 (while (setq e (pop l))
23841 (setq rtn (cons (car e) (cons (symbol-value (cdr e)) rtn))))
23842 rtn))
23844 (defun org-infile-export-plist ()
23845 "Return the property list with file-local settings for export."
23846 (save-excursion
23847 (save-restriction
23848 (widen)
23849 (goto-char 0)
23850 (let ((re (org-make-options-regexp
23851 '("TITLE" "AUTHOR" "DATE" "EMAIL" "TEXT" "OPTIONS" "LANGUAGE")))
23852 p key val text options)
23853 (while (re-search-forward re nil t)
23854 (setq key (org-match-string-no-properties 1)
23855 val (org-match-string-no-properties 2))
23856 (cond
23857 ((string-equal key "TITLE") (setq p (plist-put p :title val)))
23858 ((string-equal key "AUTHOR")(setq p (plist-put p :author val)))
23859 ((string-equal key "EMAIL") (setq p (plist-put p :email val)))
23860 ((string-equal key "DATE") (setq p (plist-put p :date val)))
23861 ((string-equal key "LANGUAGE") (setq p (plist-put p :language val)))
23862 ((string-equal key "TEXT")
23863 (setq text (if text (concat text "\n" val) val)))
23864 ((string-equal key "OPTIONS") (setq options val))))
23865 (setq p (plist-put p :text text))
23866 (when options
23867 (let ((op '(("H" . :headline-levels)
23868 ("num" . :section-numbers)
23869 ("toc" . :table-of-contents)
23870 ("\\n" . :preserve-breaks)
23871 ("@" . :expand-quoted-html)
23872 (":" . :fixed-width)
23873 ("|" . :tables)
23874 ("^" . :sub-superscript)
23875 ("-" . :special-strings)
23876 ("f" . :footnotes)
23877 ("d" . :drawers)
23878 ("tags" . :tags)
23879 ("*" . :emphasize)
23880 ("TeX" . :TeX-macros)
23881 ("LaTeX" . :LaTeX-fragments)
23882 ("skip" . :skip-before-1st-heading)
23883 ("author" . :author-info)
23884 ("timestamp" . :time-stamp-file)))
23886 (while (setq o (pop op))
23887 (if (string-match (concat (regexp-quote (car o))
23888 ":\\([^ \t\n\r;,.]*\\)")
23889 options)
23890 (setq p (plist-put p (cdr o)
23891 (car (read-from-string
23892 (match-string 1 options)))))))))
23893 p))))
23895 (defun org-export-directory (type plist)
23896 (let* ((val (plist-get plist :publishing-directory))
23897 (dir (if (listp val)
23898 (or (cdr (assoc type val)) ".")
23899 val)))
23900 dir))
23902 (defun org-skip-comments (lines)
23903 "Skip lines starting with \"#\" and subtrees starting with COMMENT."
23904 (let ((re1 (concat "^\\(\\*+\\)[ \t]+" org-comment-string))
23905 (re2 "^\\(\\*+\\)[ \t\n\r]")
23906 (case-fold-search nil)
23907 rtn line level)
23908 (while (setq line (pop lines))
23909 (cond
23910 ((and (string-match re1 line)
23911 (setq level (- (match-end 1) (match-beginning 1))))
23912 ;; Beginning of a COMMENT subtree. Skip it.
23913 (while (and (setq line (pop lines))
23914 (or (not (string-match re2 line))
23915 (> (- (match-end 1) (match-beginning 1)) level))))
23916 (setq lines (cons line lines)))
23917 ((string-match "^#" line)
23918 ;; an ordinary comment line
23920 ((and org-export-table-remove-special-lines
23921 (string-match "^[ \t]*|" line)
23922 (or (string-match "^[ \t]*| *[!_^] *|" line)
23923 (and (string-match "| *<[0-9]+> *|" line)
23924 (not (string-match "| *[^ <|]" line)))))
23925 ;; a special table line that should be removed
23927 (t (setq rtn (cons line rtn)))))
23928 (nreverse rtn)))
23930 (defun org-export (&optional arg)
23931 (interactive)
23932 (let ((help "[t] insert the export option template
23933 \[v] limit export to visible part of outline tree
23935 \[a] export as ASCII
23937 \[h] export as HTML
23938 \[H] export as HTML to temporary buffer
23939 \[R] export region as HTML
23940 \[b] export as HTML and browse immediately
23941 \[x] export as XOXO
23943 \[l] export as LaTeX
23944 \[L] export as LaTeX to temporary buffer
23946 \[i] export current file as iCalendar file
23947 \[I] export all agenda files as iCalendar files
23948 \[c] export agenda files into combined iCalendar file
23950 \[F] publish current file
23951 \[P] publish current project
23952 \[X] publish... (project will be prompted for)
23953 \[A] publish all projects")
23954 (cmds
23955 '((?t . org-insert-export-options-template)
23956 (?v . org-export-visible)
23957 (?a . org-export-as-ascii)
23958 (?h . org-export-as-html)
23959 (?b . org-export-as-html-and-open)
23960 (?H . org-export-as-html-to-buffer)
23961 (?R . org-export-region-as-html)
23962 (?x . org-export-as-xoxo)
23963 (?l . org-export-as-latex)
23964 (?L . org-export-as-latex-to-buffer)
23965 (?i . org-export-icalendar-this-file)
23966 (?I . org-export-icalendar-all-agenda-files)
23967 (?c . org-export-icalendar-combine-agenda-files)
23968 (?F . org-publish-current-file)
23969 (?P . org-publish-current-project)
23970 (?X . org-publish)
23971 (?A . org-publish-all)))
23972 r1 r2 ass)
23973 (save-window-excursion
23974 (delete-other-windows)
23975 (with-output-to-temp-buffer "*Org Export/Publishing Help*"
23976 (princ help))
23977 (message "Select command: ")
23978 (setq r1 (read-char-exclusive)))
23979 (setq r2 (if (< r1 27) (+ r1 96) r1))
23980 (if (setq ass (assq r2 cmds))
23981 (call-interactively (cdr ass))
23982 (error "No command associated with key %c" r1))))
23984 (defconst org-html-entities
23985 '(("nbsp")
23986 ("iexcl")
23987 ("cent")
23988 ("pound")
23989 ("curren")
23990 ("yen")
23991 ("brvbar")
23992 ("vert" . "&#124;")
23993 ("sect")
23994 ("uml")
23995 ("copy")
23996 ("ordf")
23997 ("laquo")
23998 ("not")
23999 ("shy")
24000 ("reg")
24001 ("macr")
24002 ("deg")
24003 ("plusmn")
24004 ("sup2")
24005 ("sup3")
24006 ("acute")
24007 ("micro")
24008 ("para")
24009 ("middot")
24010 ("odot"."o")
24011 ("star"."*")
24012 ("cedil")
24013 ("sup1")
24014 ("ordm")
24015 ("raquo")
24016 ("frac14")
24017 ("frac12")
24018 ("frac34")
24019 ("iquest")
24020 ("Agrave")
24021 ("Aacute")
24022 ("Acirc")
24023 ("Atilde")
24024 ("Auml")
24025 ("Aring") ("AA"."&Aring;")
24026 ("AElig")
24027 ("Ccedil")
24028 ("Egrave")
24029 ("Eacute")
24030 ("Ecirc")
24031 ("Euml")
24032 ("Igrave")
24033 ("Iacute")
24034 ("Icirc")
24035 ("Iuml")
24036 ("ETH")
24037 ("Ntilde")
24038 ("Ograve")
24039 ("Oacute")
24040 ("Ocirc")
24041 ("Otilde")
24042 ("Ouml")
24043 ("times")
24044 ("Oslash")
24045 ("Ugrave")
24046 ("Uacute")
24047 ("Ucirc")
24048 ("Uuml")
24049 ("Yacute")
24050 ("THORN")
24051 ("szlig")
24052 ("agrave")
24053 ("aacute")
24054 ("acirc")
24055 ("atilde")
24056 ("auml")
24057 ("aring")
24058 ("aelig")
24059 ("ccedil")
24060 ("egrave")
24061 ("eacute")
24062 ("ecirc")
24063 ("euml")
24064 ("igrave")
24065 ("iacute")
24066 ("icirc")
24067 ("iuml")
24068 ("eth")
24069 ("ntilde")
24070 ("ograve")
24071 ("oacute")
24072 ("ocirc")
24073 ("otilde")
24074 ("ouml")
24075 ("divide")
24076 ("oslash")
24077 ("ugrave")
24078 ("uacute")
24079 ("ucirc")
24080 ("uuml")
24081 ("yacute")
24082 ("thorn")
24083 ("yuml")
24084 ("fnof")
24085 ("Alpha")
24086 ("Beta")
24087 ("Gamma")
24088 ("Delta")
24089 ("Epsilon")
24090 ("Zeta")
24091 ("Eta")
24092 ("Theta")
24093 ("Iota")
24094 ("Kappa")
24095 ("Lambda")
24096 ("Mu")
24097 ("Nu")
24098 ("Xi")
24099 ("Omicron")
24100 ("Pi")
24101 ("Rho")
24102 ("Sigma")
24103 ("Tau")
24104 ("Upsilon")
24105 ("Phi")
24106 ("Chi")
24107 ("Psi")
24108 ("Omega")
24109 ("alpha")
24110 ("beta")
24111 ("gamma")
24112 ("delta")
24113 ("epsilon")
24114 ("varepsilon"."&epsilon;")
24115 ("zeta")
24116 ("eta")
24117 ("theta")
24118 ("iota")
24119 ("kappa")
24120 ("lambda")
24121 ("mu")
24122 ("nu")
24123 ("xi")
24124 ("omicron")
24125 ("pi")
24126 ("rho")
24127 ("sigmaf") ("varsigma"."&sigmaf;")
24128 ("sigma")
24129 ("tau")
24130 ("upsilon")
24131 ("phi")
24132 ("chi")
24133 ("psi")
24134 ("omega")
24135 ("thetasym") ("vartheta"."&thetasym;")
24136 ("upsih")
24137 ("piv")
24138 ("bull") ("bullet"."&bull;")
24139 ("hellip") ("dots"."&hellip;")
24140 ("prime")
24141 ("Prime")
24142 ("oline")
24143 ("frasl")
24144 ("weierp")
24145 ("image")
24146 ("real")
24147 ("trade")
24148 ("alefsym")
24149 ("larr") ("leftarrow"."&larr;") ("gets"."&larr;")
24150 ("uarr") ("uparrow"."&uarr;")
24151 ("rarr") ("to"."&rarr;") ("rightarrow"."&rarr;")
24152 ("darr")("downarrow"."&darr;")
24153 ("harr") ("leftrightarrow"."&harr;")
24154 ("crarr") ("hookleftarrow"."&crarr;") ; has round hook, not quite CR
24155 ("lArr") ("Leftarrow"."&lArr;")
24156 ("uArr") ("Uparrow"."&uArr;")
24157 ("rArr") ("Rightarrow"."&rArr;")
24158 ("dArr") ("Downarrow"."&dArr;")
24159 ("hArr") ("Leftrightarrow"."&hArr;")
24160 ("forall")
24161 ("part") ("partial"."&part;")
24162 ("exist") ("exists"."&exist;")
24163 ("empty") ("emptyset"."&empty;")
24164 ("nabla")
24165 ("isin") ("in"."&isin;")
24166 ("notin")
24167 ("ni")
24168 ("prod")
24169 ("sum")
24170 ("minus")
24171 ("lowast") ("ast"."&lowast;")
24172 ("radic")
24173 ("prop") ("proptp"."&prop;")
24174 ("infin") ("infty"."&infin;")
24175 ("ang") ("angle"."&ang;")
24176 ("and") ("wedge"."&and;")
24177 ("or") ("vee"."&or;")
24178 ("cap")
24179 ("cup")
24180 ("int")
24181 ("there4")
24182 ("sim")
24183 ("cong") ("simeq"."&cong;")
24184 ("asymp")("approx"."&asymp;")
24185 ("ne") ("neq"."&ne;")
24186 ("equiv")
24187 ("le")
24188 ("ge")
24189 ("sub") ("subset"."&sub;")
24190 ("sup") ("supset"."&sup;")
24191 ("nsub")
24192 ("sube")
24193 ("supe")
24194 ("oplus")
24195 ("otimes")
24196 ("perp")
24197 ("sdot") ("cdot"."&sdot;")
24198 ("lceil")
24199 ("rceil")
24200 ("lfloor")
24201 ("rfloor")
24202 ("lang")
24203 ("rang")
24204 ("loz") ("Diamond"."&loz;")
24205 ("spades") ("spadesuit"."&spades;")
24206 ("clubs") ("clubsuit"."&clubs;")
24207 ("hearts") ("diamondsuit"."&hearts;")
24208 ("diams") ("diamondsuit"."&diams;")
24209 ("smile"."&#9786;") ("blacksmile"."&#9787;") ("sad"."&#9785;")
24210 ("quot")
24211 ("amp")
24212 ("lt")
24213 ("gt")
24214 ("OElig")
24215 ("oelig")
24216 ("Scaron")
24217 ("scaron")
24218 ("Yuml")
24219 ("circ")
24220 ("tilde")
24221 ("ensp")
24222 ("emsp")
24223 ("thinsp")
24224 ("zwnj")
24225 ("zwj")
24226 ("lrm")
24227 ("rlm")
24228 ("ndash")
24229 ("mdash")
24230 ("lsquo")
24231 ("rsquo")
24232 ("sbquo")
24233 ("ldquo")
24234 ("rdquo")
24235 ("bdquo")
24236 ("dagger")
24237 ("Dagger")
24238 ("permil")
24239 ("lsaquo")
24240 ("rsaquo")
24241 ("euro")
24243 ("arccos"."arccos")
24244 ("arcsin"."arcsin")
24245 ("arctan"."arctan")
24246 ("arg"."arg")
24247 ("cos"."cos")
24248 ("cosh"."cosh")
24249 ("cot"."cot")
24250 ("coth"."coth")
24251 ("csc"."csc")
24252 ("deg"."deg")
24253 ("det"."det")
24254 ("dim"."dim")
24255 ("exp"."exp")
24256 ("gcd"."gcd")
24257 ("hom"."hom")
24258 ("inf"."inf")
24259 ("ker"."ker")
24260 ("lg"."lg")
24261 ("lim"."lim")
24262 ("liminf"."liminf")
24263 ("limsup"."limsup")
24264 ("ln"."ln")
24265 ("log"."log")
24266 ("max"."max")
24267 ("min"."min")
24268 ("Pr"."Pr")
24269 ("sec"."sec")
24270 ("sin"."sin")
24271 ("sinh"."sinh")
24272 ("sup"."sup")
24273 ("tan"."tan")
24274 ("tanh"."tanh")
24276 "Entities for TeX->HTML translation.
24277 Entries can be like (\"ent\"), in which case \"\\ent\" will be translated to
24278 \"&ent;\". An entry can also be a dotted pair like (\"ent\".\"&other;\").
24279 In that case, \"\\ent\" will be translated to \"&other;\".
24280 The list contains HTML entities for Latin-1, Greek and other symbols.
24281 It is supplemented by a number of commonly used TeX macros with appropriate
24282 translations. There is currently no way for users to extend this.")
24284 ;;; General functions for all backends
24286 (defun org-cleaned-string-for-export (string &rest parameters)
24287 "Cleanup a buffer STRING so that links can be created safely."
24288 (interactive)
24289 (let* ((re-radio (and org-target-link-regexp
24290 (concat "\\([^<]\\)\\(" org-target-link-regexp "\\)")))
24291 (re-plain-link (concat "\\([^[<]\\)" org-plain-link-re))
24292 (re-angle-link (concat "\\([^[]\\)" org-angle-link-re))
24293 (re-archive (concat ":" org-archive-tag ":"))
24294 (re-quote (concat "^\\*+[ \t]+" org-quote-string "\\>"))
24295 (re-commented (concat "^\\*+[ \t]+" org-comment-string "\\>"))
24296 (htmlp (plist-get parameters :for-html))
24297 (asciip (plist-get parameters :for-ascii))
24298 (latexp (plist-get parameters :for-LaTeX))
24299 (commentsp (plist-get parameters :comments))
24300 (archived-trees (plist-get parameters :archived-trees))
24301 (inhibit-read-only t)
24302 (drawers org-drawers)
24303 (exp-drawers (plist-get parameters :drawers))
24304 (outline-regexp "\\*+ ")
24305 a b xx
24306 rtn p)
24307 (with-current-buffer (get-buffer-create " org-mode-tmp")
24308 (erase-buffer)
24309 (insert string)
24310 ;; Remove license-to-kill stuff
24311 (while (setq p (text-property-any (point-min) (point-max)
24312 :org-license-to-kill t))
24313 (delete-region p (next-single-property-change p :org-license-to-kill)))
24315 (let ((org-inhibit-startup t)) (org-mode))
24316 (untabify (point-min) (point-max))
24318 ;; Get rid of drawers
24319 (unless (eq t exp-drawers)
24320 (goto-char (point-min))
24321 (let ((re (concat "^[ \t]*:\\("
24322 (mapconcat
24323 'identity
24324 (org-delete-all exp-drawers
24325 (copy-sequence drawers))
24326 "\\|")
24327 "\\):[ \t]*\n\\([^@]*?\n\\)?[ \t]*:END:[ \t]*\n")))
24328 (while (re-search-forward re nil t)
24329 (replace-match ""))))
24331 ;; Get the correct stuff before the first headline
24332 (when (plist-get parameters :skip-before-1st-heading)
24333 (goto-char (point-min))
24334 (when (re-search-forward "^\\*+[ \t]" nil t)
24335 (delete-region (point-min) (match-beginning 0))
24336 (goto-char (point-min))
24337 (insert "\n")))
24338 (when (plist-get parameters :add-text)
24339 (goto-char (point-min))
24340 (insert (plist-get parameters :add-text) "\n"))
24342 ;; Get rid of archived trees
24343 (when (not (eq archived-trees t))
24344 (goto-char (point-min))
24345 (while (re-search-forward re-archive nil t)
24346 (if (not (org-on-heading-p t))
24347 (org-end-of-subtree t)
24348 (beginning-of-line 1)
24349 (setq a (if archived-trees
24350 (1+ (point-at-eol)) (point))
24351 b (org-end-of-subtree t))
24352 (if (> b a) (delete-region a b)))))
24354 ;; Find targets in comments and move them out of comments,
24355 ;; but mark them as targets that should be invisible
24356 (goto-char (point-min))
24357 (while (re-search-forward "^#.*?\\(<<<?[^>\r\n]+>>>?\\).*" nil t)
24358 (replace-match "\\1(INVISIBLE)"))
24360 ;; Protect backend specific stuff, throw away the others.
24361 (let ((formatters
24362 `((,htmlp "HTML" "BEGIN_HTML" "END_HTML")
24363 (,asciip "ASCII" "BEGIN_ASCII" "END_ASCII")
24364 (,latexp "LaTeX" "BEGIN_LaTeX" "END_LaTeX")))
24365 fmt)
24366 (goto-char (point-min))
24367 (while (re-search-forward "^#\\+BEGIN_EXAMPLE[ \t]*\n" nil t)
24368 (goto-char (match-end 0))
24369 (while (not (looking-at "#\\+END_EXAMPLE"))
24370 (insert ": ")
24371 (beginning-of-line 2)))
24372 (goto-char (point-min))
24373 (while (re-search-forward "^[ \t]*:.*\\(\n[ \t]*:.*\\)*" nil t)
24374 (add-text-properties (match-beginning 0) (match-end 0)
24375 '(org-protected t)))
24376 (while formatters
24377 (setq fmt (pop formatters))
24378 (when (car fmt)
24379 (goto-char (point-min))
24380 (while (re-search-forward (concat "^#\\+" (cadr fmt)
24381 ":[ \t]*\\(.*\\)") nil t)
24382 (replace-match "\\1" t)
24383 (add-text-properties
24384 (point-at-bol) (min (1+ (point-at-eol)) (point-max))
24385 '(org-protected t))))
24386 (goto-char (point-min))
24387 (while (re-search-forward
24388 (concat "^#\\+"
24389 (caddr fmt) "\\>.*\\(\\(\n.*\\)*?\n\\)#\\+"
24390 (cadddr fmt) "\\>.*\n?") nil t)
24391 (if (car fmt)
24392 (add-text-properties (match-beginning 1) (1+ (match-end 1))
24393 '(org-protected t))
24394 (delete-region (match-beginning 0) (match-end 0))))))
24396 ;; Protect quoted subtrees
24397 (goto-char (point-min))
24398 (while (re-search-forward re-quote nil t)
24399 (goto-char (match-beginning 0))
24400 (end-of-line 1)
24401 (add-text-properties (point) (org-end-of-subtree t)
24402 '(org-protected t)))
24404 ;; Protect verbatim elements
24405 (goto-char (point-min))
24406 (while (re-search-forward org-verbatim-re nil t)
24407 (add-text-properties (match-beginning 4) (match-end 4)
24408 '(org-protected t))
24409 (goto-char (1+ (match-end 4))))
24411 ;; Remove subtrees that are commented
24412 (goto-char (point-min))
24413 (while (re-search-forward re-commented nil t)
24414 (goto-char (match-beginning 0))
24415 (delete-region (point) (org-end-of-subtree t)))
24417 ;; Remove special table lines
24418 (when org-export-table-remove-special-lines
24419 (goto-char (point-min))
24420 (while (re-search-forward "^[ \t]*|" nil t)
24421 (beginning-of-line 1)
24422 (if (or (looking-at "[ \t]*| *[!_^] *|")
24423 (and (looking-at ".*?| *<[0-9]+> *|")
24424 (not (looking-at ".*?| *[^ <|]"))))
24425 (delete-region (max (point-min) (1- (point-at-bol)))
24426 (point-at-eol))
24427 (end-of-line 1))))
24429 ;; Specific LaTeX stuff
24430 (when latexp
24431 (require 'org-export-latex nil)
24432 (org-export-latex-cleaned-string))
24434 (when asciip
24435 (org-export-ascii-clean-string))
24437 ;; Specific HTML stuff
24438 (when htmlp
24439 ;; Convert LaTeX fragments to images
24440 (when (plist-get parameters :LaTeX-fragments)
24441 (org-format-latex
24442 (concat "ltxpng/" (file-name-sans-extension
24443 (file-name-nondirectory
24444 org-current-export-file)))
24445 org-current-export-dir nil "Creating LaTeX image %s"))
24446 (message "Exporting..."))
24448 ;; Remove or replace comments
24449 (goto-char (point-min))
24450 (while (re-search-forward "^#\\(.*\n?\\)" nil t)
24451 (if commentsp
24452 (progn (add-text-properties
24453 (match-beginning 0) (match-end 0) '(org-protected t))
24454 (replace-match (format commentsp (match-string 1)) t t))
24455 (replace-match "")))
24457 ;; Find matches for radio targets and turn them into internal links
24458 (goto-char (point-min))
24459 (when re-radio
24460 (while (re-search-forward re-radio nil t)
24461 (org-if-unprotected
24462 (replace-match "\\1[[\\2]]"))))
24464 ;; Find all links that contain a newline and put them into a single line
24465 (goto-char (point-min))
24466 (while (re-search-forward "\\(\\(\\[\\|\\]\\)\\[[^]]*?\\)[ \t]*\n[ \t]*\\([^]]*\\]\\(\\[\\|\\]\\)\\)" nil t)
24467 (org-if-unprotected
24468 (replace-match "\\1 \\3")
24469 (goto-char (match-beginning 0))))
24472 ;; Normalize links: Convert angle and plain links into bracket links
24473 ;; Expand link abbreviations
24474 (goto-char (point-min))
24475 (while (re-search-forward re-plain-link nil t)
24476 (goto-char (1- (match-end 0)))
24477 (org-if-unprotected
24478 (let* ((s (concat (match-string 1) "[[" (match-string 2)
24479 ":" (match-string 3) "]]")))
24480 ;; added 'org-link face to links
24481 (put-text-property 0 (length s) 'face 'org-link s)
24482 (replace-match s t t))))
24483 (goto-char (point-min))
24484 (while (re-search-forward re-angle-link nil t)
24485 (goto-char (1- (match-end 0)))
24486 (org-if-unprotected
24487 (let* ((s (concat (match-string 1) "[[" (match-string 2)
24488 ":" (match-string 3) "]]")))
24489 (put-text-property 0 (length s) 'face 'org-link s)
24490 (replace-match s t t))))
24491 (goto-char (point-min))
24492 (while (re-search-forward org-bracket-link-regexp nil t)
24493 (org-if-unprotected
24494 (let* ((s (concat "[[" (setq xx (save-match-data
24495 (org-link-expand-abbrev (match-string 1))))
24497 (if (match-end 3)
24498 (match-string 2)
24499 (concat "[" xx "]"))
24500 "]")))
24501 (put-text-property 0 (length s) 'face 'org-link s)
24502 (replace-match s t t))))
24504 ;; Find multiline emphasis and put them into single line
24505 (when (plist-get parameters :emph-multiline)
24506 (goto-char (point-min))
24507 (while (re-search-forward org-emph-re nil t)
24508 (if (not (= (char-after (match-beginning 3))
24509 (char-after (match-beginning 4))))
24510 (org-if-unprotected
24511 (subst-char-in-region (match-beginning 0) (match-end 0)
24512 ?\n ?\ t)
24513 (goto-char (1- (match-end 0))))
24514 (goto-char (1+ (match-beginning 0))))))
24516 (setq rtn (buffer-string)))
24517 (kill-buffer " org-mode-tmp")
24518 rtn))
24520 (defun org-export-grab-title-from-buffer ()
24521 "Get a title for the current document, from looking at the buffer."
24522 (let ((inhibit-read-only t))
24523 (save-excursion
24524 (goto-char (point-min))
24525 (let ((end (save-excursion (outline-next-heading) (point))))
24526 (when (re-search-forward "^[ \t]*[^|# \t\r\n].*\n" end t)
24527 ;; Mark the line so that it will not be exported as normal text.
24528 (org-unmodified
24529 (add-text-properties (match-beginning 0) (match-end 0)
24530 (list :org-license-to-kill t)))
24531 ;; Return the title string
24532 (org-trim (match-string 0)))))))
24534 (defun org-export-get-title-from-subtree ()
24535 "Return subtree title and exclude it from export."
24536 (let (title (m (mark)))
24537 (save-excursion
24538 (goto-char (region-beginning))
24539 (when (and (org-at-heading-p)
24540 (>= (org-end-of-subtree t t) (region-end)))
24541 ;; This is a subtree, we take the title from the first heading
24542 (goto-char (region-beginning))
24543 (looking-at org-todo-line-regexp)
24544 (setq title (match-string 3))
24545 (org-unmodified
24546 (add-text-properties (point) (1+ (point-at-eol))
24547 (list :org-license-to-kill t)))))
24548 title))
24550 (defun org-solidify-link-text (s &optional alist)
24551 "Take link text and make a safe target out of it."
24552 (save-match-data
24553 (let* ((rtn
24554 (mapconcat
24555 'identity
24556 (org-split-string s "[ \t\r\n]+") "--"))
24557 (a (assoc rtn alist)))
24558 (or (cdr a) rtn))))
24560 (defun org-get-min-level (lines)
24561 "Get the minimum level in LINES."
24562 (let ((re "^\\(\\*+\\) ") l min)
24563 (catch 'exit
24564 (while (setq l (pop lines))
24565 (if (string-match re l)
24566 (throw 'exit (org-tr-level (length (match-string 1 l))))))
24567 1)))
24569 ;; Variable holding the vector with section numbers
24570 (defvar org-section-numbers (make-vector org-level-max 0))
24572 (defun org-init-section-numbers ()
24573 "Initialize the vector for the section numbers."
24574 (let* ((level -1)
24575 (numbers (nreverse (org-split-string "" "\\.")))
24576 (depth (1- (length org-section-numbers)))
24577 (i depth) number-string)
24578 (while (>= i 0)
24579 (if (> i level)
24580 (aset org-section-numbers i 0)
24581 (setq number-string (or (car numbers) "0"))
24582 (if (string-match "\\`[A-Z]\\'" number-string)
24583 (aset org-section-numbers i
24584 (- (string-to-char number-string) ?A -1))
24585 (aset org-section-numbers i (string-to-number number-string)))
24586 (pop numbers))
24587 (setq i (1- i)))))
24589 (defun org-section-number (&optional level)
24590 "Return a string with the current section number.
24591 When LEVEL is non-nil, increase section numbers on that level."
24592 (let* ((depth (1- (length org-section-numbers))) idx n (string ""))
24593 (when level
24594 (when (> level -1)
24595 (aset org-section-numbers
24596 level (1+ (aref org-section-numbers level))))
24597 (setq idx (1+ level))
24598 (while (<= idx depth)
24599 (if (not (= idx 1))
24600 (aset org-section-numbers idx 0))
24601 (setq idx (1+ idx))))
24602 (setq idx 0)
24603 (while (<= idx depth)
24604 (setq n (aref org-section-numbers idx))
24605 (setq string (concat string (if (not (string= string "")) "." "")
24606 (int-to-string n)))
24607 (setq idx (1+ idx)))
24608 (save-match-data
24609 (if (string-match "\\`\\([@0]\\.\\)+" string)
24610 (setq string (replace-match "" t nil string)))
24611 (if (string-match "\\(\\.0\\)+\\'" string)
24612 (setq string (replace-match "" t nil string))))
24613 string))
24615 ;;; ASCII export
24617 (defvar org-last-level nil) ; dynamically scoped variable
24618 (defvar org-min-level nil) ; dynamically scoped variable
24619 (defvar org-levels-open nil) ; dynamically scoped parameter
24620 (defvar org-ascii-current-indentation nil) ; For communication
24622 (defun org-export-as-ascii (arg)
24623 "Export the outline as a pretty ASCII file.
24624 If there is an active region, export only the region.
24625 The prefix ARG specifies how many levels of the outline should become
24626 underlined headlines. The default is 3."
24627 (interactive "P")
24628 (setq-default org-todo-line-regexp org-todo-line-regexp)
24629 (let* ((opt-plist (org-combine-plists (org-default-export-plist)
24630 (org-infile-export-plist)))
24631 (region-p (org-region-active-p))
24632 (subtree-p
24633 (when region-p
24634 (save-excursion
24635 (goto-char (region-beginning))
24636 (and (org-at-heading-p)
24637 (>= (org-end-of-subtree t t) (region-end))))))
24638 (custom-times org-display-custom-times)
24639 (org-ascii-current-indentation '(0 . 0))
24640 (level 0) line txt
24641 (umax nil)
24642 (umax-toc nil)
24643 (case-fold-search nil)
24644 (filename (concat (file-name-as-directory
24645 (org-export-directory :ascii opt-plist))
24646 (file-name-sans-extension
24647 (or (and subtree-p
24648 (org-entry-get (region-beginning)
24649 "EXPORT_FILE_NAME" t))
24650 (file-name-nondirectory buffer-file-name)))
24651 ".txt"))
24652 (filename (if (equal (file-truename filename)
24653 (file-truename buffer-file-name))
24654 (concat filename ".txt")
24655 filename))
24656 (buffer (find-file-noselect filename))
24657 (org-levels-open (make-vector org-level-max nil))
24658 (odd org-odd-levels-only)
24659 (date (plist-get opt-plist :date))
24660 (author (plist-get opt-plist :author))
24661 (title (or (and subtree-p (org-export-get-title-from-subtree))
24662 (plist-get opt-plist :title)
24663 (and (not
24664 (plist-get opt-plist :skip-before-1st-heading))
24665 (org-export-grab-title-from-buffer))
24666 (file-name-sans-extension
24667 (file-name-nondirectory buffer-file-name))))
24668 (email (plist-get opt-plist :email))
24669 (language (plist-get opt-plist :language))
24670 (quote-re0 (concat "^[ \t]*" org-quote-string "\\>"))
24671 ; (quote-re (concat "^\\(\\*+\\)\\([ \t]*" org-quote-string "\\>\\)"))
24672 (todo nil)
24673 (lang-words nil)
24674 (region
24675 (buffer-substring
24676 (if (org-region-active-p) (region-beginning) (point-min))
24677 (if (org-region-active-p) (region-end) (point-max))))
24678 (lines (org-split-string
24679 (org-cleaned-string-for-export
24680 region
24681 :for-ascii t
24682 :skip-before-1st-heading
24683 (plist-get opt-plist :skip-before-1st-heading)
24684 :drawers (plist-get opt-plist :drawers)
24685 :verbatim-multiline t
24686 :archived-trees
24687 (plist-get opt-plist :archived-trees)
24688 :add-text (plist-get opt-plist :text))
24689 "\n"))
24690 thetoc have-headings first-heading-pos
24691 table-open table-buffer)
24693 (let ((inhibit-read-only t))
24694 (org-unmodified
24695 (remove-text-properties (point-min) (point-max)
24696 '(:org-license-to-kill t))))
24698 (setq org-min-level (org-get-min-level lines))
24699 (setq org-last-level org-min-level)
24700 (org-init-section-numbers)
24702 (find-file-noselect filename)
24704 (setq lang-words (or (assoc language org-export-language-setup)
24705 (assoc "en" org-export-language-setup)))
24706 (switch-to-buffer-other-window buffer)
24707 (erase-buffer)
24708 (fundamental-mode)
24709 ;; create local variables for all options, to make sure all called
24710 ;; functions get the correct information
24711 (mapc (lambda (x)
24712 (set (make-local-variable (cdr x))
24713 (plist-get opt-plist (car x))))
24714 org-export-plist-vars)
24715 (org-set-local 'org-odd-levels-only odd)
24716 (setq umax (if arg (prefix-numeric-value arg)
24717 org-export-headline-levels))
24718 (setq umax-toc (if (integerp org-export-with-toc)
24719 (min org-export-with-toc umax)
24720 umax))
24722 ;; File header
24723 (if title (org-insert-centered title ?=))
24724 (insert "\n")
24725 (if (and (or author email)
24726 org-export-author-info)
24727 (insert (concat (nth 1 lang-words) ": " (or author "")
24728 (if email (concat " <" email ">") "")
24729 "\n")))
24731 (cond
24732 ((and date (string-match "%" date))
24733 (setq date (format-time-string date (current-time))))
24734 (date)
24735 (t (setq date (format-time-string "%Y/%m/%d %X" (current-time)))))
24737 (if (and date org-export-time-stamp-file)
24738 (insert (concat (nth 2 lang-words) ": " date"\n")))
24740 (insert "\n\n")
24742 (if org-export-with-toc
24743 (progn
24744 (push (concat (nth 3 lang-words) "\n") thetoc)
24745 (push (concat (make-string (length (nth 3 lang-words)) ?=) "\n") thetoc)
24746 (mapc '(lambda (line)
24747 (if (string-match org-todo-line-regexp
24748 line)
24749 ;; This is a headline
24750 (progn
24751 (setq have-headings t)
24752 (setq level (- (match-end 1) (match-beginning 1))
24753 level (org-tr-level level)
24754 txt (match-string 3 line)
24755 todo
24756 (or (and org-export-mark-todo-in-toc
24757 (match-beginning 2)
24758 (not (member (match-string 2 line)
24759 org-done-keywords)))
24760 ; TODO, not DONE
24761 (and org-export-mark-todo-in-toc
24762 (= level umax-toc)
24763 (org-search-todo-below
24764 line lines level))))
24765 (setq txt (org-html-expand-for-ascii txt))
24767 (while (string-match org-bracket-link-regexp txt)
24768 (setq txt
24769 (replace-match
24770 (match-string (if (match-end 2) 3 1) txt)
24771 t t txt)))
24773 (if (and (memq org-export-with-tags '(not-in-toc nil))
24774 (string-match
24775 (org-re "[ \t]+:[[:alnum:]_@:]+:[ \t]*$")
24776 txt))
24777 (setq txt (replace-match "" t t txt)))
24778 (if (string-match quote-re0 txt)
24779 (setq txt (replace-match "" t t txt)))
24781 (if org-export-with-section-numbers
24782 (setq txt (concat (org-section-number level)
24783 " " txt)))
24784 (if (<= level umax-toc)
24785 (progn
24786 (push
24787 (concat
24788 (make-string
24789 (* (max 0 (- level org-min-level)) 4) ?\ )
24790 (format (if todo "%s (*)\n" "%s\n") txt))
24791 thetoc)
24792 (setq org-last-level level))
24793 ))))
24794 lines)
24795 (setq thetoc (if have-headings (nreverse thetoc) nil))))
24797 (org-init-section-numbers)
24798 (while (setq line (pop lines))
24799 ;; Remove the quoted HTML tags.
24800 (setq line (org-html-expand-for-ascii line))
24801 ;; Remove targets
24802 (while (string-match "<<<?[^<>]*>>>?[ \t]*\n?" line)
24803 (setq line (replace-match "" t t line)))
24804 ;; Replace internal links
24805 (while (string-match org-bracket-link-regexp line)
24806 (setq line (replace-match
24807 (if (match-end 3) "[\\3]" "[\\1]")
24808 t nil line)))
24809 (when custom-times
24810 (setq line (org-translate-time line)))
24811 (cond
24812 ((string-match "^\\(\\*+\\)[ \t]+\\(.*\\)" line)
24813 ;; a Headline
24814 (setq first-heading-pos (or first-heading-pos (point)))
24815 (setq level (org-tr-level (- (match-end 1) (match-beginning 1)))
24816 txt (match-string 2 line))
24817 (org-ascii-level-start level txt umax lines))
24819 ((and org-export-with-tables
24820 (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)" line))
24821 (if (not table-open)
24822 ;; New table starts
24823 (setq table-open t table-buffer nil))
24824 ;; Accumulate lines
24825 (setq table-buffer (cons line table-buffer))
24826 (when (or (not lines)
24827 (not (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)"
24828 (car lines))))
24829 (setq table-open nil
24830 table-buffer (nreverse table-buffer))
24831 (insert (mapconcat
24832 (lambda (x)
24833 (org-fix-indentation x org-ascii-current-indentation))
24834 (org-format-table-ascii table-buffer)
24835 "\n") "\n")))
24837 (setq line (org-fix-indentation line org-ascii-current-indentation))
24838 (if (and org-export-with-fixed-width
24839 (string-match "^\\([ \t]*\\)\\(:\\)" line))
24840 (setq line (replace-match "\\1" nil nil line)))
24841 (insert line "\n"))))
24843 (normal-mode)
24845 ;; insert the table of contents
24846 (when thetoc
24847 (goto-char (point-min))
24848 (if (re-search-forward "^[ \t]*\\[TABLE-OF-CONTENTS\\][ \t]*$" nil t)
24849 (progn
24850 (goto-char (match-beginning 0))
24851 (replace-match ""))
24852 (goto-char first-heading-pos))
24853 (mapc 'insert thetoc)
24854 (or (looking-at "[ \t]*\n[ \t]*\n")
24855 (insert "\n\n")))
24857 ;; Convert whitespace place holders
24858 (goto-char (point-min))
24859 (let (beg end)
24860 (while (setq beg (next-single-property-change (point) 'org-whitespace))
24861 (setq end (next-single-property-change beg 'org-whitespace))
24862 (goto-char beg)
24863 (delete-region beg end)
24864 (insert (make-string (- end beg) ?\ ))))
24866 (save-buffer)
24867 ;; remove display and invisible chars
24868 (let (beg end)
24869 (goto-char (point-min))
24870 (while (setq beg (next-single-property-change (point) 'display))
24871 (setq end (next-single-property-change beg 'display))
24872 (delete-region beg end)
24873 (goto-char beg)
24874 (insert "=>"))
24875 (goto-char (point-min))
24876 (while (setq beg (next-single-property-change (point) 'org-cwidth))
24877 (setq end (next-single-property-change beg 'org-cwidth))
24878 (delete-region beg end)
24879 (goto-char beg)))
24880 (goto-char (point-min))))
24882 (defun org-export-ascii-clean-string ()
24883 "Do extra work for ASCII export"
24884 (goto-char (point-min))
24885 (while (re-search-forward org-verbatim-re nil t)
24886 (goto-char (match-end 2))
24887 (backward-delete-char 1) (insert "'")
24888 (goto-char (match-beginning 2))
24889 (delete-char 1) (insert "`")
24890 (goto-char (match-end 2))))
24892 (defun org-search-todo-below (line lines level)
24893 "Search the subtree below LINE for any TODO entries."
24894 (let ((rest (cdr (memq line lines)))
24895 (re org-todo-line-regexp)
24896 line lv todo)
24897 (catch 'exit
24898 (while (setq line (pop rest))
24899 (if (string-match re line)
24900 (progn
24901 (setq lv (- (match-end 1) (match-beginning 1))
24902 todo (and (match-beginning 2)
24903 (not (member (match-string 2 line)
24904 org-done-keywords))))
24905 ; TODO, not DONE
24906 (if (<= lv level) (throw 'exit nil))
24907 (if todo (throw 'exit t))))))))
24909 (defun org-html-expand-for-ascii (line)
24910 "Handle quoted HTML for ASCII export."
24911 (if org-export-html-expand
24912 (while (string-match "@<[^<>\n]*>" line)
24913 ;; We just remove the tags for now.
24914 (setq line (replace-match "" nil nil line))))
24915 line)
24917 (defun org-insert-centered (s &optional underline)
24918 "Insert the string S centered and underline it with character UNDERLINE."
24919 (let ((ind (max (/ (- 80 (string-width s)) 2) 0)))
24920 (insert (make-string ind ?\ ) s "\n")
24921 (if underline
24922 (insert (make-string ind ?\ )
24923 (make-string (string-width s) underline)
24924 "\n"))))
24926 (defun org-ascii-level-start (level title umax &optional lines)
24927 "Insert a new level in ASCII export."
24928 (let (char (n (- level umax 1)) (ind 0))
24929 (if (> level umax)
24930 (progn
24931 (insert (make-string (* 2 n) ?\ )
24932 (char-to-string (nth (% n (length org-export-ascii-bullets))
24933 org-export-ascii-bullets))
24934 " " title "\n")
24935 ;; find the indentation of the next non-empty line
24936 (catch 'stop
24937 (while lines
24938 (if (string-match "^\\* " (car lines)) (throw 'stop nil))
24939 (if (string-match "^\\([ \t]*\\)\\S-" (car lines))
24940 (throw 'stop (setq ind (org-get-indentation (car lines)))))
24941 (pop lines)))
24942 (setq org-ascii-current-indentation (cons (* 2 (1+ n)) ind)))
24943 (if (or (not (equal (char-before) ?\n))
24944 (not (equal (char-before (1- (point))) ?\n)))
24945 (insert "\n"))
24946 (setq char (nth (- umax level) (reverse org-export-ascii-underline)))
24947 (unless org-export-with-tags
24948 (if (string-match (org-re "[ \t]+\\(:[[:alnum:]_@:]+:\\)[ \t]*$") title)
24949 (setq title (replace-match "" t t title))))
24950 (if org-export-with-section-numbers
24951 (setq title (concat (org-section-number level) " " title)))
24952 (insert title "\n" (make-string (string-width title) char) "\n")
24953 (setq org-ascii-current-indentation '(0 . 0)))))
24955 (defun org-export-visible (type arg)
24956 "Create a copy of the visible part of the current buffer, and export it.
24957 The copy is created in a temporary buffer and removed after use.
24958 TYPE is the final key (as a string) that also select the export command in
24959 the `C-c C-e' export dispatcher.
24960 As a special case, if the you type SPC at the prompt, the temporary
24961 org-mode file will not be removed but presented to you so that you can
24962 continue to use it. The prefix arg ARG is passed through to the exporting
24963 command."
24964 (interactive
24965 (list (progn
24966 (message "Export visible: [a]SCII [h]tml [b]rowse HTML [H/R]uffer with HTML [x]OXO [ ]keep buffer")
24967 (read-char-exclusive))
24968 current-prefix-arg))
24969 (if (not (member type '(?a ?\C-a ?b ?\C-b ?h ?x ?\ )))
24970 (error "Invalid export key"))
24971 (let* ((binding (cdr (assoc type
24972 '((?a . org-export-as-ascii)
24973 (?\C-a . org-export-as-ascii)
24974 (?b . org-export-as-html-and-open)
24975 (?\C-b . org-export-as-html-and-open)
24976 (?h . org-export-as-html)
24977 (?H . org-export-as-html-to-buffer)
24978 (?R . org-export-region-as-html)
24979 (?x . org-export-as-xoxo)))))
24980 (keepp (equal type ?\ ))
24981 (file buffer-file-name)
24982 (buffer (get-buffer-create "*Org Export Visible*"))
24983 s e)
24984 ;; Need to hack the drawers here.
24985 (save-excursion
24986 (goto-char (point-min))
24987 (while (re-search-forward org-drawer-regexp nil t)
24988 (goto-char (match-beginning 1))
24989 (or (org-invisible-p) (org-flag-drawer nil))))
24990 (with-current-buffer buffer (erase-buffer))
24991 (save-excursion
24992 (setq s (goto-char (point-min)))
24993 (while (not (= (point) (point-max)))
24994 (goto-char (org-find-invisible))
24995 (append-to-buffer buffer s (point))
24996 (setq s (goto-char (org-find-visible))))
24997 (org-cycle-hide-drawers 'all)
24998 (goto-char (point-min))
24999 (unless keepp
25000 ;; Copy all comment lines to the end, to make sure #+ settings are
25001 ;; still available for the second export step. Kind of a hack, but
25002 ;; does do the trick.
25003 (if (looking-at "#[^\r\n]*")
25004 (append-to-buffer buffer (match-beginning 0) (1+ (match-end 0))))
25005 (while (re-search-forward "[\n\r]#[^\n\r]*" nil t)
25006 (append-to-buffer buffer (1+ (match-beginning 0))
25007 (min (point-max) (1+ (match-end 0))))))
25008 (set-buffer buffer)
25009 (let ((buffer-file-name file)
25010 (org-inhibit-startup t))
25011 (org-mode)
25012 (show-all)
25013 (unless keepp (funcall binding arg))))
25014 (if (not keepp)
25015 (kill-buffer buffer)
25016 (switch-to-buffer-other-window buffer)
25017 (goto-char (point-min)))))
25019 (defun org-find-visible ()
25020 (let ((s (point)))
25021 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
25022 (get-char-property s 'invisible)))
25024 (defun org-find-invisible ()
25025 (let ((s (point)))
25026 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
25027 (not (get-char-property s 'invisible))))
25030 ;;; HTML export
25032 (defun org-get-current-options ()
25033 "Return a string with current options as keyword options.
25034 Does include HTML export options as well as TODO and CATEGORY stuff."
25035 (format
25036 "#+TITLE: %s
25037 #+AUTHOR: %s
25038 #+EMAIL: %s
25039 #+LANGUAGE: %s
25040 #+TEXT: Some descriptive text to be emitted. Several lines OK.
25041 #+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
25042 #+CATEGORY: %s
25043 #+SEQ_TODO: %s
25044 #+TYP_TODO: %s
25045 #+PRIORITIES: %c %c %c
25046 #+DRAWERS: %s
25047 #+STARTUP: %s %s %s %s %s
25048 #+TAGS: %s
25049 #+ARCHIVE: %s
25050 #+LINK: %s
25052 (buffer-name) (user-full-name) user-mail-address org-export-default-language
25053 org-export-headline-levels
25054 org-export-with-section-numbers
25055 org-export-with-toc
25056 org-export-preserve-breaks
25057 org-export-html-expand
25058 org-export-with-fixed-width
25059 org-export-with-tables
25060 org-export-with-sub-superscripts
25061 org-export-with-special-strings
25062 org-export-with-footnotes
25063 org-export-with-emphasize
25064 org-export-with-TeX-macros
25065 org-export-with-LaTeX-fragments
25066 org-export-skip-text-before-1st-heading
25067 org-export-with-drawers
25068 org-export-with-tags
25069 (file-name-nondirectory buffer-file-name)
25070 "TODO FEEDBACK VERIFY DONE"
25071 "Me Jason Marie DONE"
25072 org-highest-priority org-lowest-priority org-default-priority
25073 (mapconcat 'identity org-drawers " ")
25074 (cdr (assoc org-startup-folded
25075 '((nil . "showall") (t . "overview") (content . "content"))))
25076 (if org-odd-levels-only "odd" "oddeven")
25077 (if org-hide-leading-stars "hidestars" "showstars")
25078 (if org-startup-align-all-tables "align" "noalign")
25079 (cond ((eq org-log-done t) "logdone")
25080 ((equal org-log-done 'note) "lognotedone")
25081 ((not org-log-done) "nologdone"))
25082 (or (mapconcat (lambda (x)
25083 (cond
25084 ((equal '(:startgroup) x) "{")
25085 ((equal '(:endgroup) x) "}")
25086 ((cdr x) (format "%s(%c)" (car x) (cdr x)))
25087 (t (car x))))
25088 (or org-tag-alist (org-get-buffer-tags)) " ") "")
25089 org-archive-location
25090 "org file:~/org/%s.org"
25093 (defun org-insert-export-options-template ()
25094 "Insert into the buffer a template with information for exporting."
25095 (interactive)
25096 (if (not (bolp)) (newline))
25097 (let ((s (org-get-current-options)))
25098 (and (string-match "#\\+CATEGORY" s)
25099 (setq s (substring s 0 (match-beginning 0))))
25100 (insert s)))
25102 (defun org-toggle-fixed-width-section (arg)
25103 "Toggle the fixed-width export.
25104 If there is no active region, the QUOTE keyword at the current headline is
25105 inserted or removed. When present, it causes the text between this headline
25106 and the next to be exported as fixed-width text, and unmodified.
25107 If there is an active region, this command adds or removes a colon as the
25108 first character of this line. If the first character of a line is a colon,
25109 this line is also exported in fixed-width font."
25110 (interactive "P")
25111 (let* ((cc 0)
25112 (regionp (org-region-active-p))
25113 (beg (if regionp (region-beginning) (point)))
25114 (end (if regionp (region-end)))
25115 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
25116 (case-fold-search nil)
25117 (re "[ \t]*\\(:\\)")
25118 off)
25119 (if regionp
25120 (save-excursion
25121 (goto-char beg)
25122 (setq cc (current-column))
25123 (beginning-of-line 1)
25124 (setq off (looking-at re))
25125 (while (> nlines 0)
25126 (setq nlines (1- nlines))
25127 (beginning-of-line 1)
25128 (cond
25129 (arg
25130 (move-to-column cc t)
25131 (insert ":\n")
25132 (forward-line -1))
25133 ((and off (looking-at re))
25134 (replace-match "" t t nil 1))
25135 ((not off) (move-to-column cc t) (insert ":")))
25136 (forward-line 1)))
25137 (save-excursion
25138 (org-back-to-heading)
25139 (if (looking-at (concat outline-regexp
25140 "\\( *\\<" org-quote-string "\\>[ \t]*\\)"))
25141 (replace-match "" t t nil 1)
25142 (if (looking-at outline-regexp)
25143 (progn
25144 (goto-char (match-end 0))
25145 (insert org-quote-string " "))))))))
25147 (defun org-export-as-html-and-open (arg)
25148 "Export the outline as HTML and immediately open it with a browser.
25149 If there is an active region, export only the region.
25150 The prefix ARG specifies how many levels of the outline should become
25151 headlines. The default is 3. Lower levels will become bulleted lists."
25152 (interactive "P")
25153 (org-export-as-html arg 'hidden)
25154 (org-open-file buffer-file-name))
25156 (defun org-export-as-html-batch ()
25157 "Call `org-export-as-html', may be used in batch processing as
25158 emacs --batch
25159 --load=$HOME/lib/emacs/org.el
25160 --eval \"(setq org-export-headline-levels 2)\"
25161 --visit=MyFile --funcall org-export-as-html-batch"
25162 (org-export-as-html org-export-headline-levels 'hidden))
25164 (defun org-export-as-html-to-buffer (arg)
25165 "Call `org-exort-as-html` with output to a temporary buffer.
25166 No file is created. The prefix ARG is passed through to `org-export-as-html'."
25167 (interactive "P")
25168 (org-export-as-html arg nil nil "*Org HTML Export*")
25169 (switch-to-buffer-other-window "*Org HTML Export*"))
25171 (defun org-replace-region-by-html (beg end)
25172 "Assume the current region has org-mode syntax, and convert it to HTML.
25173 This can be used in any buffer. For example, you could write an
25174 itemized list in org-mode syntax in an HTML buffer and then use this
25175 command to convert it."
25176 (interactive "r")
25177 (let (reg html buf pop-up-frames)
25178 (save-window-excursion
25179 (if (org-mode-p)
25180 (setq html (org-export-region-as-html
25181 beg end t 'string))
25182 (setq reg (buffer-substring beg end)
25183 buf (get-buffer-create "*Org tmp*"))
25184 (with-current-buffer buf
25185 (erase-buffer)
25186 (insert reg)
25187 (org-mode)
25188 (setq html (org-export-region-as-html
25189 (point-min) (point-max) t 'string)))
25190 (kill-buffer buf)))
25191 (delete-region beg end)
25192 (insert html)))
25194 (defun org-export-region-as-html (beg end &optional body-only buffer)
25195 "Convert region from BEG to END in org-mode buffer to HTML.
25196 If prefix arg BODY-ONLY is set, omit file header, footer, and table of
25197 contents, and only produce the region of converted text, useful for
25198 cut-and-paste operations.
25199 If BUFFER is a buffer or a string, use/create that buffer as a target
25200 of the converted HTML. If BUFFER is the symbol `string', return the
25201 produced HTML as a string and leave not buffer behind. For example,
25202 a Lisp program could call this function in the following way:
25204 (setq html (org-export-region-as-html beg end t 'string))
25206 When called interactively, the output buffer is selected, and shown
25207 in a window. A non-interactive call will only retunr the buffer."
25208 (interactive "r\nP")
25209 (when (interactive-p)
25210 (setq buffer "*Org HTML Export*"))
25211 (let ((transient-mark-mode t) (zmacs-regions t)
25212 rtn)
25213 (goto-char end)
25214 (set-mark (point)) ;; to activate the region
25215 (goto-char beg)
25216 (setq rtn (org-export-as-html
25217 nil nil nil
25218 buffer body-only))
25219 (if (fboundp 'deactivate-mark) (deactivate-mark))
25220 (if (and (interactive-p) (bufferp rtn))
25221 (switch-to-buffer-other-window rtn)
25222 rtn)))
25224 (defvar html-table-tag nil) ; dynamically scoped into this.
25225 (defun org-export-as-html (arg &optional hidden ext-plist
25226 to-buffer body-only)
25227 "Export the outline as a pretty HTML file.
25228 If there is an active region, export only the region. The prefix
25229 ARG specifies how many levels of the outline should become
25230 headlines. The default is 3. Lower levels will become bulleted
25231 lists. When HIDDEN is non-nil, don't display the HTML buffer.
25232 EXT-PLIST is a property list with external parameters overriding
25233 org-mode's default settings, but still inferior to file-local
25234 settings. When TO-BUFFER is non-nil, create a buffer with that
25235 name and export to that buffer. If TO-BUFFER is the symbol `string',
25236 don't leave any buffer behind but just return the resulting HTML as
25237 a string. When BODY-ONLY is set, don't produce the file header and footer,
25238 simply return the content of <body>...</body>, without even
25239 the body tags themselves."
25240 (interactive "P")
25242 ;; Make sure we have a file name when we need it.
25243 (when (and (not (or to-buffer body-only))
25244 (not buffer-file-name))
25245 (if (buffer-base-buffer)
25246 (org-set-local 'buffer-file-name
25247 (with-current-buffer (buffer-base-buffer)
25248 buffer-file-name))
25249 (error "Need a file name to be able to export.")))
25251 (message "Exporting...")
25252 (setq-default org-todo-line-regexp org-todo-line-regexp)
25253 (setq-default org-deadline-line-regexp org-deadline-line-regexp)
25254 (setq-default org-done-keywords org-done-keywords)
25255 (setq-default org-maybe-keyword-time-regexp org-maybe-keyword-time-regexp)
25256 (let* ((opt-plist (org-combine-plists (org-default-export-plist)
25257 ext-plist
25258 (org-infile-export-plist)))
25260 (style (plist-get opt-plist :style))
25261 (html-extension (plist-get opt-plist :html-extension))
25262 (link-validate (plist-get opt-plist :link-validation-function))
25263 valid thetoc have-headings first-heading-pos
25264 (odd org-odd-levels-only)
25265 (region-p (org-region-active-p))
25266 (subtree-p
25267 (when region-p
25268 (save-excursion
25269 (goto-char (region-beginning))
25270 (and (org-at-heading-p)
25271 (>= (org-end-of-subtree t t) (region-end))))))
25272 ;; The following two are dynamically scoped into other
25273 ;; routines below.
25274 (org-current-export-dir (org-export-directory :html opt-plist))
25275 (org-current-export-file buffer-file-name)
25276 (level 0) (line "") (origline "") txt todo
25277 (umax nil)
25278 (umax-toc nil)
25279 (filename (if to-buffer nil
25280 (expand-file-name
25281 (concat
25282 (file-name-sans-extension
25283 (or (and subtree-p
25284 (org-entry-get (region-beginning)
25285 "EXPORT_FILE_NAME" t))
25286 (file-name-nondirectory buffer-file-name)))
25287 "." html-extension)
25288 (file-name-as-directory
25289 (org-export-directory :html opt-plist)))))
25290 (current-dir (if buffer-file-name
25291 (file-name-directory buffer-file-name)
25292 default-directory))
25293 (buffer (if to-buffer
25294 (cond
25295 ((eq to-buffer 'string) (get-buffer-create "*Org HTML Export*"))
25296 (t (get-buffer-create to-buffer)))
25297 (find-file-noselect filename)))
25298 (org-levels-open (make-vector org-level-max nil))
25299 (date (plist-get opt-plist :date))
25300 (author (plist-get opt-plist :author))
25301 (title (or (and subtree-p (org-export-get-title-from-subtree))
25302 (plist-get opt-plist :title)
25303 (and (not
25304 (plist-get opt-plist :skip-before-1st-heading))
25305 (org-export-grab-title-from-buffer))
25306 (and buffer-file-name
25307 (file-name-sans-extension
25308 (file-name-nondirectory buffer-file-name)))
25309 "UNTITLED"))
25310 (html-table-tag (plist-get opt-plist :html-table-tag))
25311 (quote-re0 (concat "^[ \t]*" org-quote-string "\\>"))
25312 (quote-re (concat "^\\(\\*+\\)\\([ \t]+" org-quote-string "\\>\\)"))
25313 (inquote nil)
25314 (infixed nil)
25315 (in-local-list nil)
25316 (local-list-num nil)
25317 (local-list-indent nil)
25318 (llt org-plain-list-ordered-item-terminator)
25319 (email (plist-get opt-plist :email))
25320 (language (plist-get opt-plist :language))
25321 (lang-words nil)
25322 (target-alist nil) tg
25323 (head-count 0) cnt
25324 (start 0)
25325 (coding-system (and (boundp 'buffer-file-coding-system)
25326 buffer-file-coding-system))
25327 (coding-system-for-write (or org-export-html-coding-system
25328 coding-system))
25329 (save-buffer-coding-system (or org-export-html-coding-system
25330 coding-system))
25331 (charset (and coding-system-for-write
25332 (fboundp 'coding-system-get)
25333 (coding-system-get coding-system-for-write
25334 'mime-charset)))
25335 (region
25336 (buffer-substring
25337 (if region-p (region-beginning) (point-min))
25338 (if region-p (region-end) (point-max))))
25339 (lines
25340 (org-split-string
25341 (org-cleaned-string-for-export
25342 region
25343 :emph-multiline t
25344 :for-html t
25345 :skip-before-1st-heading
25346 (plist-get opt-plist :skip-before-1st-heading)
25347 :drawers (plist-get opt-plist :drawers)
25348 :archived-trees
25349 (plist-get opt-plist :archived-trees)
25350 :add-text
25351 (plist-get opt-plist :text)
25352 :LaTeX-fragments
25353 (plist-get opt-plist :LaTeX-fragments))
25354 "[\r\n]"))
25355 table-open type
25356 table-buffer table-orig-buffer
25357 ind start-is-num starter didclose
25358 rpl path desc descp desc1 desc2 link
25361 (let ((inhibit-read-only t))
25362 (org-unmodified
25363 (remove-text-properties (point-min) (point-max)
25364 '(:org-license-to-kill t))))
25366 (message "Exporting...")
25368 (setq org-min-level (org-get-min-level lines))
25369 (setq org-last-level org-min-level)
25370 (org-init-section-numbers)
25372 (cond
25373 ((and date (string-match "%" date))
25374 (setq date (format-time-string date (current-time))))
25375 (date)
25376 (t (setq date (format-time-string "%Y/%m/%d %X" (current-time)))))
25378 ;; Get the language-dependent settings
25379 (setq lang-words (or (assoc language org-export-language-setup)
25380 (assoc "en" org-export-language-setup)))
25382 ;; Switch to the output buffer
25383 (set-buffer buffer)
25384 (let ((inhibit-read-only t)) (erase-buffer))
25385 (fundamental-mode)
25387 (and (fboundp 'set-buffer-file-coding-system)
25388 (set-buffer-file-coding-system coding-system-for-write))
25390 (let ((case-fold-search nil)
25391 (org-odd-levels-only odd))
25392 ;; create local variables for all options, to make sure all called
25393 ;; functions get the correct information
25394 (mapc (lambda (x)
25395 (set (make-local-variable (cdr x))
25396 (plist-get opt-plist (car x))))
25397 org-export-plist-vars)
25398 (setq umax (if arg (prefix-numeric-value arg)
25399 org-export-headline-levels))
25400 (setq umax-toc (if (integerp org-export-with-toc)
25401 (min org-export-with-toc umax)
25402 umax))
25403 (unless body-only
25404 ;; File header
25405 (insert (format
25406 "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"
25407 \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">
25408 <html xmlns=\"http://www.w3.org/1999/xhtml\"
25409 lang=\"%s\" xml:lang=\"%s\">
25410 <head>
25411 <title>%s</title>
25412 <meta http-equiv=\"Content-Type\" content=\"text/html;charset=%s\"/>
25413 <meta name=\"generator\" content=\"Org-mode\"/>
25414 <meta name=\"generated\" content=\"%s\"/>
25415 <meta name=\"author\" content=\"%s\"/>
25417 </head><body>
25419 language language (org-html-expand title)
25420 (or charset "iso-8859-1") date author style))
25422 (insert (or (plist-get opt-plist :preamble) ""))
25424 (when (plist-get opt-plist :auto-preamble)
25425 (if title (insert (format org-export-html-title-format
25426 (org-html-expand title))))))
25428 (if (and org-export-with-toc (not body-only))
25429 (progn
25430 (push (format "<h%d>%s</h%d>\n"
25431 org-export-html-toplevel-hlevel
25432 (nth 3 lang-words)
25433 org-export-html-toplevel-hlevel)
25434 thetoc)
25435 (push "<ul>\n<li>" thetoc)
25436 (setq lines
25437 (mapcar '(lambda (line)
25438 (if (string-match org-todo-line-regexp line)
25439 ;; This is a headline
25440 (progn
25441 (setq have-headings t)
25442 (setq level (- (match-end 1) (match-beginning 1))
25443 level (org-tr-level level)
25444 txt (save-match-data
25445 (org-html-expand
25446 (org-export-cleanup-toc-line
25447 (match-string 3 line))))
25448 todo
25449 (or (and org-export-mark-todo-in-toc
25450 (match-beginning 2)
25451 (not (member (match-string 2 line)
25452 org-done-keywords)))
25453 ; TODO, not DONE
25454 (and org-export-mark-todo-in-toc
25455 (= level umax-toc)
25456 (org-search-todo-below
25457 line lines level))))
25458 (if (string-match
25459 (org-re "[ \t]+:\\([[:alnum:]_@:]+\\):[ \t]*$") txt)
25460 (setq txt (replace-match "&nbsp;&nbsp;&nbsp;<span class=\"tag\"> \\1</span>" t nil txt)))
25461 (if (string-match quote-re0 txt)
25462 (setq txt (replace-match "" t t txt)))
25463 (if org-export-with-section-numbers
25464 (setq txt (concat (org-section-number level)
25465 " " txt)))
25466 (if (<= level (max umax umax-toc))
25467 (setq head-count (+ head-count 1)))
25468 (if (<= level umax-toc)
25469 (progn
25470 (if (> level org-last-level)
25471 (progn
25472 (setq cnt (- level org-last-level))
25473 (while (>= (setq cnt (1- cnt)) 0)
25474 (push "\n<ul>\n<li>" thetoc))
25475 (push "\n" thetoc)))
25476 (if (< level org-last-level)
25477 (progn
25478 (setq cnt (- org-last-level level))
25479 (while (>= (setq cnt (1- cnt)) 0)
25480 (push "</li>\n</ul>" thetoc))
25481 (push "\n" thetoc)))
25482 ;; Check for targets
25483 (while (string-match org-target-regexp line)
25484 (setq tg (match-string 1 line)
25485 line (replace-match
25486 (concat "@<span class=\"target\">" tg "@</span> ")
25487 t t line))
25488 (push (cons (org-solidify-link-text tg)
25489 (format "sec-%d" head-count))
25490 target-alist))
25491 (while (string-match "&lt;\\(&lt;\\)+\\|&gt;\\(&gt;\\)+" txt)
25492 (setq txt (replace-match "" t t txt)))
25493 (push
25494 (format
25495 (if todo
25496 "</li>\n<li><a href=\"#sec-%d\"><span class=\"todo\">%s</span></a>"
25497 "</li>\n<li><a href=\"#sec-%d\">%s</a>")
25498 head-count txt) thetoc)
25500 (setq org-last-level level))
25502 line)
25503 lines))
25504 (while (> org-last-level (1- org-min-level))
25505 (setq org-last-level (1- org-last-level))
25506 (push "</li>\n</ul>\n" thetoc))
25507 (setq thetoc (if have-headings (nreverse thetoc) nil))))
25509 (setq head-count 0)
25510 (org-init-section-numbers)
25512 (while (setq line (pop lines) origline line)
25513 (catch 'nextline
25515 ;; end of quote section?
25516 (when (and inquote (string-match "^\\*+ " line))
25517 (insert "</pre>\n")
25518 (setq inquote nil))
25519 ;; inside a quote section?
25520 (when inquote
25521 (insert (org-html-protect line) "\n")
25522 (throw 'nextline nil))
25524 ;; verbatim lines
25525 (when (and org-export-with-fixed-width
25526 (string-match "^[ \t]*:\\(.*\\)" line))
25527 (when (not infixed)
25528 (setq infixed t)
25529 (insert "<pre>\n"))
25530 (insert (org-html-protect (match-string 1 line)) "\n")
25531 (when (and lines
25532 (not (string-match "^[ \t]*\\(:.*\\)"
25533 (car lines))))
25534 (setq infixed nil)
25535 (insert "</pre>\n"))
25536 (throw 'nextline nil))
25538 ;; Protected HTML
25539 (when (get-text-property 0 'org-protected line)
25540 (let (par)
25541 (when (re-search-backward
25542 "\\(<p>\\)\\([ \t\r\n]*\\)\\=" (- (point) 100) t)
25543 (setq par (match-string 1))
25544 (replace-match "\\2\n"))
25545 (insert line "\n")
25546 (while (and lines
25547 (or (= (length (car lines)) 0)
25548 (get-text-property 0 'org-protected (car lines))))
25549 (insert (pop lines) "\n"))
25550 (and par (insert "<p>\n")))
25551 (throw 'nextline nil))
25553 ;; Horizontal line
25554 (when (string-match "^[ \t]*-\\{5,\\}[ \t]*$" line)
25555 (insert "\n<hr/>\n")
25556 (throw 'nextline nil))
25558 ;; make targets to anchors
25559 (while (string-match "<<<?\\([^<>]*\\)>>>?\\((INVISIBLE)\\)?[ \t]*\n?" line)
25560 (cond
25561 ((match-end 2)
25562 (setq line (replace-match
25563 (concat "@<a name=\""
25564 (org-solidify-link-text (match-string 1 line))
25565 "\">\\nbsp@</a>")
25566 t t line)))
25567 ((and org-export-with-toc (equal (string-to-char line) ?*))
25568 (setq line (replace-match
25569 (concat "@<span class=\"target\">" (match-string 1 line) "@</span> ")
25570 ; (concat "@<i>" (match-string 1 line) "@</i> ")
25571 t t line)))
25573 (setq line (replace-match
25574 (concat "@<a name=\""
25575 (org-solidify-link-text (match-string 1 line))
25576 "\" class=\"target\">" (match-string 1 line) "@</a> ")
25577 t t line)))))
25579 (setq line (org-html-handle-time-stamps line))
25581 ;; replace "&" by "&amp;", "<" and ">" by "&lt;" and "&gt;"
25582 ;; handle @<..> HTML tags (replace "@&gt;..&lt;" by "<..>")
25583 ;; Also handle sub_superscripts and checkboxes
25584 (or (string-match org-table-hline-regexp line)
25585 (setq line (org-html-expand line)))
25587 ;; Format the links
25588 (setq start 0)
25589 (while (string-match org-bracket-link-analytic-regexp line start)
25590 (setq start (match-beginning 0))
25591 (setq type (if (match-end 2) (match-string 2 line) "internal"))
25592 (setq path (match-string 3 line))
25593 (setq desc1 (if (match-end 5) (match-string 5 line))
25594 desc2 (if (match-end 2) (concat type ":" path) path)
25595 descp (and desc1 (not (equal desc1 desc2)))
25596 desc (or desc1 desc2))
25597 ;; Make an image out of the description if that is so wanted
25598 (when (and descp (org-file-image-p desc))
25599 (save-match-data
25600 (if (string-match "^file:" desc)
25601 (setq desc (substring desc (match-end 0)))))
25602 (setq desc (concat "<img src=\"" desc "\"/>")))
25603 ;; FIXME: do we need to unescape here somewhere?
25604 (cond
25605 ((equal type "internal")
25606 (setq rpl
25607 (concat
25608 "<a href=\"#"
25609 (org-solidify-link-text
25610 (save-match-data (org-link-unescape path)) target-alist)
25611 "\">" desc "</a>")))
25612 ((member type '("http" "https"))
25613 ;; standard URL, just check if we need to inline an image
25614 (if (and (or (eq t org-export-html-inline-images)
25615 (and org-export-html-inline-images (not descp)))
25616 (org-file-image-p path))
25617 (setq rpl (concat "<img src=\"" type ":" path "\"/>"))
25618 (setq link (concat type ":" path))
25619 (setq rpl (concat "<a href=\"" link "\">" desc "</a>"))))
25620 ((member type '("ftp" "mailto" "news"))
25621 ;; standard URL
25622 (setq link (concat type ":" path))
25623 (setq rpl (concat "<a href=\"" link "\">" desc "</a>")))
25624 ((string= type "file")
25625 ;; FILE link
25626 (let* ((filename path)
25627 (abs-p (file-name-absolute-p filename))
25628 thefile file-is-image-p search)
25629 (save-match-data
25630 (if (string-match "::\\(.*\\)" filename)
25631 (setq search (match-string 1 filename)
25632 filename (replace-match "" t nil filename)))
25633 (setq valid
25634 (if (functionp link-validate)
25635 (funcall link-validate filename current-dir)
25637 (setq file-is-image-p (org-file-image-p filename))
25638 (setq thefile (if abs-p (expand-file-name filename) filename))
25639 (when (and org-export-html-link-org-files-as-html
25640 (string-match "\\.org$" thefile))
25641 (setq thefile (concat (substring thefile 0
25642 (match-beginning 0))
25643 "." html-extension))
25644 (if (and search
25645 ;; make sure this is can be used as target search
25646 (not (string-match "^[0-9]*$" search))
25647 (not (string-match "^\\*" search))
25648 (not (string-match "^/.*/$" search)))
25649 (setq thefile (concat thefile "#"
25650 (org-solidify-link-text
25651 (org-link-unescape search)))))
25652 (when (string-match "^file:" desc)
25653 (setq desc (replace-match "" t t desc))
25654 (if (string-match "\\.org$" desc)
25655 (setq desc (replace-match "" t t desc))))))
25656 (setq rpl (if (and file-is-image-p
25657 (or (eq t org-export-html-inline-images)
25658 (and org-export-html-inline-images
25659 (not descp))))
25660 (concat "<img src=\"" thefile "\"/>")
25661 (concat "<a href=\"" thefile "\">" desc "</a>")))
25662 (if (not valid) (setq rpl desc))))
25663 ((member type '("bbdb" "vm" "wl" "mhe" "rmail" "gnus" "shell" "info" "elisp"))
25664 (setq rpl (concat "<i>&lt;" type ":"
25665 (save-match-data (org-link-unescape path))
25666 "&gt;</i>"))))
25667 (setq line (replace-match rpl t t line)
25668 start (+ start (length rpl))))
25670 ;; TODO items
25671 (if (and (string-match org-todo-line-regexp line)
25672 (match-beginning 2))
25674 (setq line
25675 (concat (substring line 0 (match-beginning 2))
25676 "<span class=\""
25677 (if (member (match-string 2 line)
25678 org-done-keywords)
25679 "done" "todo")
25680 "\">" (match-string 2 line)
25681 "</span>" (substring line (match-end 2)))))
25683 ;; Does this contain a reference to a footnote?
25684 (when org-export-with-footnotes
25685 (setq start 0)
25686 (while (string-match "\\([^* \t].*?\\)\\[\\([0-9]+\\)\\]" line start)
25687 (if (get-text-property (match-beginning 2) 'org-protected line)
25688 (setq start (match-end 2))
25689 (let ((n (match-string 2 line)))
25690 (setq line
25691 (replace-match
25692 (format
25693 "%s<sup><a class=\"footref\" name=\"fnr.%s\" href=\"#fn.%s\">%s</a></sup>"
25694 (match-string 1 line) n n n)
25695 t t line))))))
25697 (cond
25698 ((string-match "^\\(\\*+\\)[ \t]+\\(.*\\)" line)
25699 ;; This is a headline
25700 (setq level (org-tr-level (- (match-end 1) (match-beginning 1)))
25701 txt (match-string 2 line))
25702 (if (string-match quote-re0 txt)
25703 (setq txt (replace-match "" t t txt)))
25704 (if (<= level (max umax umax-toc))
25705 (setq head-count (+ head-count 1)))
25706 (when in-local-list
25707 ;; Close any local lists before inserting a new header line
25708 (while local-list-num
25709 (org-close-li)
25710 (insert (if (car local-list-num) "</ol>\n" "</ul>"))
25711 (pop local-list-num))
25712 (setq local-list-indent nil
25713 in-local-list nil))
25714 (setq first-heading-pos (or first-heading-pos (point)))
25715 (org-html-level-start level txt umax
25716 (and org-export-with-toc (<= level umax))
25717 head-count)
25718 ;; QUOTES
25719 (when (string-match quote-re line)
25720 (insert "<pre>")
25721 (setq inquote t)))
25723 ((and org-export-with-tables
25724 (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)" line))
25725 (if (not table-open)
25726 ;; New table starts
25727 (setq table-open t table-buffer nil table-orig-buffer nil))
25728 ;; Accumulate lines
25729 (setq table-buffer (cons line table-buffer)
25730 table-orig-buffer (cons origline table-orig-buffer))
25731 (when (or (not lines)
25732 (not (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)"
25733 (car lines))))
25734 (setq table-open nil
25735 table-buffer (nreverse table-buffer)
25736 table-orig-buffer (nreverse table-orig-buffer))
25737 (org-close-par-maybe)
25738 (insert (org-format-table-html table-buffer table-orig-buffer))))
25740 ;; Normal lines
25741 (when (string-match
25742 (cond
25743 ((eq llt t) "^\\([ \t]*\\)\\(\\([-+*] \\)\\|\\([0-9]+[.)]\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
25744 ((= llt ?.) "^\\([ \t]*\\)\\(\\([-+*] \\)\\|\\([0-9]+\\.\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
25745 ((= llt ?\)) "^\\([ \t]*\\)\\(\\([-+*] \\)\\|\\([0-9]+)\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
25746 (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))
25747 line)
25748 (setq ind (org-get-string-indentation line)
25749 start-is-num (match-beginning 4)
25750 starter (if (match-beginning 2)
25751 (substring (match-string 2 line) 0 -1))
25752 line (substring line (match-beginning 5)))
25753 (unless (string-match "[^ \t]" line)
25754 ;; empty line. Pretend indentation is large.
25755 (setq ind (if org-empty-line-terminates-plain-lists
25757 (1+ (or (car local-list-indent) 1)))))
25758 (setq didclose nil)
25759 (while (and in-local-list
25760 (or (and (= ind (car local-list-indent))
25761 (not starter))
25762 (< ind (car local-list-indent))))
25763 (setq didclose t)
25764 (org-close-li)
25765 (insert (if (car local-list-num) "</ol>\n" "</ul>"))
25766 (pop local-list-num) (pop local-list-indent)
25767 (setq in-local-list local-list-indent))
25768 (cond
25769 ((and starter
25770 (or (not in-local-list)
25771 (> ind (car local-list-indent))))
25772 ;; Start new (level of) list
25773 (org-close-par-maybe)
25774 (insert (if start-is-num "<ol>\n<li>\n" "<ul>\n<li>\n"))
25775 (push start-is-num local-list-num)
25776 (push ind local-list-indent)
25777 (setq in-local-list t))
25778 (starter
25779 ;; continue current list
25780 (org-close-li)
25781 (insert "<li>\n"))
25782 (didclose
25783 ;; we did close a list, normal text follows: need <p>
25784 (org-open-par)))
25785 (if (string-match "^[ \t]*\\[\\([X ]\\)\\]" line)
25786 (setq line
25787 (replace-match
25788 (if (equal (match-string 1 line) "X")
25789 "<b>[X]</b>"
25790 "<b>[<span style=\"visibility:hidden;\">X</span>]</b>")
25791 t t line))))
25793 ;; Empty lines start a new paragraph. If hand-formatted lists
25794 ;; are not fully interpreted, lines starting with "-", "+", "*"
25795 ;; also start a new paragraph.
25796 (if (string-match "^ [-+*]-\\|^[ \t]*$" line) (org-open-par))
25798 ;; Is this the start of a footnote?
25799 (when org-export-with-footnotes
25800 (when (string-match "^[ \t]*\\[\\([0-9]+\\)\\]" line)
25801 (org-close-par-maybe)
25802 (let ((n (match-string 1 line)))
25803 (setq line (replace-match
25804 (format "<p class=\"footnote\"><sup><a class=\"footnum\" name=\"fn.%s\" href=\"#fnr.%s\">%s</a></sup>" n n n) t t line)))))
25806 ;; Check if the line break needs to be conserved
25807 (cond
25808 ((string-match "\\\\\\\\[ \t]*$" line)
25809 (setq line (replace-match "<br/>" t t line)))
25810 (org-export-preserve-breaks
25811 (setq line (concat line "<br/>"))))
25813 (insert line "\n")))))
25815 ;; Properly close all local lists and other lists
25816 (when inquote (insert "</pre>\n"))
25817 (when in-local-list
25818 ;; Close any local lists before inserting a new header line
25819 (while local-list-num
25820 (org-close-li)
25821 (insert (if (car local-list-num) "</ol>\n" "</ul>\n"))
25822 (pop local-list-num))
25823 (setq local-list-indent nil
25824 in-local-list nil))
25825 (org-html-level-start 1 nil umax
25826 (and org-export-with-toc (<= level umax))
25827 head-count)
25829 (unless body-only
25830 (when (plist-get opt-plist :auto-postamble)
25831 (insert "<div id=\"postamble\">")
25832 (when (and org-export-author-info author)
25833 (insert "<p class=\"author\"> "
25834 (nth 1 lang-words) ": " author "\n")
25835 (when email
25836 (if (listp (split-string email ",+ *"))
25837 (mapc (lambda(e)
25838 (insert "<a href=\"mailto:" e "\">&lt;"
25839 e "&gt;</a>\n"))
25840 (split-string email ",+ *"))
25841 (insert "<a href=\"mailto:" email "\">&lt;"
25842 email "&gt;</a>\n")))
25843 (insert "</p>\n"))
25844 (when (and date org-export-time-stamp-file)
25845 (insert "<p class=\"date\"> "
25846 (nth 2 lang-words) ": "
25847 date "</p>\n"))
25848 (insert "</div>"))
25850 (if org-export-html-with-timestamp
25851 (insert org-export-html-html-helper-timestamp))
25852 (insert (or (plist-get opt-plist :postamble) ""))
25853 (insert "</body>\n</html>\n"))
25855 (normal-mode)
25856 (if (eq major-mode default-major-mode) (html-mode))
25858 ;; insert the table of contents
25859 (goto-char (point-min))
25860 (when thetoc
25861 (if (or (re-search-forward
25862 "<p>\\s-*\\[TABLE-OF-CONTENTS\\]\\s-*</p>" nil t)
25863 (re-search-forward
25864 "\\[TABLE-OF-CONTENTS\\]" nil t))
25865 (progn
25866 (goto-char (match-beginning 0))
25867 (replace-match ""))
25868 (goto-char first-heading-pos)
25869 (when (looking-at "\\s-*</p>")
25870 (goto-char (match-end 0))
25871 (insert "\n")))
25872 (insert "<div id=\"table-of-contents\">\n")
25873 (mapc 'insert thetoc)
25874 (insert "</div>\n"))
25875 ;; remove empty paragraphs and lists
25876 (goto-char (point-min))
25877 (while (re-search-forward "<p>[ \r\n\t]*</p>" nil t)
25878 (replace-match ""))
25879 (goto-char (point-min))
25880 (while (re-search-forward "<li>[ \r\n\t]*</li>\n?" nil t)
25881 (replace-match ""))
25882 (goto-char (point-min))
25883 (while (re-search-forward "</ul>\\s-*<ul>\n?" nil t)
25884 (replace-match ""))
25885 ;; Convert whitespace place holders
25886 (goto-char (point-min))
25887 (let (beg end n)
25888 (while (setq beg (next-single-property-change (point) 'org-whitespace))
25889 (setq n (get-text-property beg 'org-whitespace)
25890 end (next-single-property-change beg 'org-whitespace))
25891 (goto-char beg)
25892 (delete-region beg end)
25893 (insert (format "<span style=\"visibility:hidden;\">%s</span>"
25894 (make-string n ?x)))))
25896 (or to-buffer (save-buffer))
25897 (goto-char (point-min))
25898 (message "Exporting... done")
25899 (if (eq to-buffer 'string)
25900 (prog1 (buffer-substring (point-min) (point-max))
25901 (kill-buffer (current-buffer)))
25902 (current-buffer)))))
25904 (defvar org-table-colgroup-info nil)
25905 (defun org-format-table-ascii (lines)
25906 "Format a table for ascii export."
25907 (if (stringp lines)
25908 (setq lines (org-split-string lines "\n")))
25909 (if (not (string-match "^[ \t]*|" (car lines)))
25910 ;; Table made by table.el - test for spanning
25911 lines
25913 ;; A normal org table
25914 ;; Get rid of hlines at beginning and end
25915 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
25916 (setq lines (nreverse lines))
25917 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
25918 (setq lines (nreverse lines))
25919 (when org-export-table-remove-special-lines
25920 ;; Check if the table has a marking column. If yes remove the
25921 ;; column and the special lines
25922 (setq lines (org-table-clean-before-export lines)))
25923 ;; Get rid of the vertical lines except for grouping
25924 (let ((vl (org-colgroup-info-to-vline-list org-table-colgroup-info))
25925 rtn line vl1 start)
25926 (while (setq line (pop lines))
25927 (if (string-match org-table-hline-regexp line)
25928 (and (string-match "|\\(.*\\)|" line)
25929 (setq line (replace-match " \\1" t nil line)))
25930 (setq start 0 vl1 vl)
25931 (while (string-match "|" line start)
25932 (setq start (match-end 0))
25933 (or (pop vl1) (setq line (replace-match " " t t line)))))
25934 (push line rtn))
25935 (nreverse rtn))))
25937 (defun org-colgroup-info-to-vline-list (info)
25938 (let (vl new last)
25939 (while info
25940 (setq last new new (pop info))
25941 (if (or (memq last '(:end :startend))
25942 (memq new '(:start :startend)))
25943 (push t vl)
25944 (push nil vl)))
25945 (setq vl (nreverse vl))
25946 (and vl (setcar vl nil))
25947 vl))
25949 (defun org-format-table-html (lines olines)
25950 "Find out which HTML converter to use and return the HTML code."
25951 (if (stringp lines)
25952 (setq lines (org-split-string lines "\n")))
25953 (if (string-match "^[ \t]*|" (car lines))
25954 ;; A normal org table
25955 (org-format-org-table-html lines)
25956 ;; Table made by table.el - test for spanning
25957 (let* ((hlines (delq nil (mapcar
25958 (lambda (x)
25959 (if (string-match "^[ \t]*\\+-" x) x
25960 nil))
25961 lines)))
25962 (first (car hlines))
25963 (ll (and (string-match "\\S-+" first)
25964 (match-string 0 first)))
25965 (re (concat "^[ \t]*" (regexp-quote ll)))
25966 (spanning (delq nil (mapcar (lambda (x) (not (string-match re x)))
25967 hlines))))
25968 (if (and (not spanning)
25969 (not org-export-prefer-native-exporter-for-tables))
25970 ;; We can use my own converter with HTML conversions
25971 (org-format-table-table-html lines)
25972 ;; Need to use the code generator in table.el, with the original text.
25973 (org-format-table-table-html-using-table-generate-source olines)))))
25975 (defun org-format-org-table-html (lines &optional splice)
25976 "Format a table into HTML."
25977 ;; Get rid of hlines at beginning and end
25978 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
25979 (setq lines (nreverse lines))
25980 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
25981 (setq lines (nreverse lines))
25982 (when org-export-table-remove-special-lines
25983 ;; Check if the table has a marking column. If yes remove the
25984 ;; column and the special lines
25985 (setq lines (org-table-clean-before-export lines)))
25987 (let ((head (and org-export-highlight-first-table-line
25988 (delq nil (mapcar
25989 (lambda (x) (string-match "^[ \t]*|-" x))
25990 (cdr lines)))))
25991 (nlines 0) fnum i
25992 tbopen line fields html gr colgropen)
25993 (if splice (setq head nil))
25994 (unless splice (push (if head "<thead>" "<tbody>") html))
25995 (setq tbopen t)
25996 (while (setq line (pop lines))
25997 (catch 'next-line
25998 (if (string-match "^[ \t]*|-" line)
25999 (progn
26000 (unless splice
26001 (push (if head "</thead>" "</tbody>") html)
26002 (if lines (push "<tbody>" html) (setq tbopen nil)))
26003 (setq head nil) ;; head ends here, first time around
26004 ;; ignore this line
26005 (throw 'next-line t)))
26006 ;; Break the line into fields
26007 (setq fields (org-split-string line "[ \t]*|[ \t]*"))
26008 (unless fnum (setq fnum (make-vector (length fields) 0)))
26009 (setq nlines (1+ nlines) i -1)
26010 (push (concat "<tr>"
26011 (mapconcat
26012 (lambda (x)
26013 (setq i (1+ i))
26014 (if (and (< i nlines)
26015 (string-match org-table-number-regexp x))
26016 (incf (aref fnum i)))
26017 (if head
26018 (concat (car org-export-table-header-tags) x
26019 (cdr org-export-table-header-tags))
26020 (concat (car org-export-table-data-tags) x
26021 (cdr org-export-table-data-tags))))
26022 fields "")
26023 "</tr>")
26024 html)))
26025 (unless splice (if tbopen (push "</tbody>" html)))
26026 (unless splice (push "</table>\n" html))
26027 (setq html (nreverse html))
26028 (unless splice
26029 ;; Put in col tags with the alignment (unfortuntely often ignored...)
26030 (push (mapconcat
26031 (lambda (x)
26032 (setq gr (pop org-table-colgroup-info))
26033 (format "%s<col align=\"%s\"></col>%s"
26034 (if (memq gr '(:start :startend))
26035 (prog1
26036 (if colgropen "</colgroup>\n<colgroup>" "<colgroup>")
26037 (setq colgropen t))
26039 (if (> (/ (float x) nlines) org-table-number-fraction)
26040 "right" "left")
26041 (if (memq gr '(:end :startend))
26042 (progn (setq colgropen nil) "</colgroup>")
26043 "")))
26044 fnum "")
26045 html)
26046 (if colgropen (setq html (cons (car html) (cons "</colgroup>" (cdr html)))))
26047 (push html-table-tag html))
26048 (concat (mapconcat 'identity html "\n") "\n")))
26050 (defun org-table-clean-before-export (lines)
26051 "Check if the table has a marking column.
26052 If yes remove the column and the special lines."
26053 (setq org-table-colgroup-info nil)
26054 (if (memq nil
26055 (mapcar
26056 (lambda (x) (or (string-match "^[ \t]*|-" x)
26057 (string-match "^[ \t]*| *\\([#!$*_^ /]\\) *|" x)))
26058 lines))
26059 (progn
26060 (setq org-table-clean-did-remove-column nil)
26061 (delq nil
26062 (mapcar
26063 (lambda (x)
26064 (cond
26065 ((string-match "^[ \t]*| */ *|" x)
26066 (setq org-table-colgroup-info
26067 (mapcar (lambda (x)
26068 (cond ((member x '("<" "&lt;")) :start)
26069 ((member x '(">" "&gt;")) :end)
26070 ((member x '("<>" "&lt;&gt;")) :startend)
26071 (t nil)))
26072 (org-split-string x "[ \t]*|[ \t]*")))
26073 nil)
26074 (t x)))
26075 lines)))
26076 (setq org-table-clean-did-remove-column t)
26077 (delq nil
26078 (mapcar
26079 (lambda (x)
26080 (cond
26081 ((string-match "^[ \t]*| */ *|" x)
26082 (setq org-table-colgroup-info
26083 (mapcar (lambda (x)
26084 (cond ((member x '("<" "&lt;")) :start)
26085 ((member x '(">" "&gt;")) :end)
26086 ((member x '("<>" "&lt;&gt;")) :startend)
26087 (t nil)))
26088 (cdr (org-split-string x "[ \t]*|[ \t]*"))))
26089 nil)
26090 ((string-match "^[ \t]*| *[!_^/] *|" x)
26091 nil) ; ignore this line
26092 ((or (string-match "^\\([ \t]*\\)|-+\\+" x)
26093 (string-match "^\\([ \t]*\\)|[^|]*|" x))
26094 ;; remove the first column
26095 (replace-match "\\1|" t nil x))))
26096 lines))))
26098 (defun org-format-table-table-html (lines)
26099 "Format a table generated by table.el into HTML.
26100 This conversion does *not* use `table-generate-source' from table.el.
26101 This has the advantage that Org-mode's HTML conversions can be used.
26102 But it has the disadvantage, that no cell- or row-spanning is allowed."
26103 (let (line field-buffer
26104 (head org-export-highlight-first-table-line)
26105 fields html empty)
26106 (setq html (concat html-table-tag "\n"))
26107 (while (setq line (pop lines))
26108 (setq empty "&nbsp;")
26109 (catch 'next-line
26110 (if (string-match "^[ \t]*\\+-" line)
26111 (progn
26112 (if field-buffer
26113 (progn
26114 (setq
26115 html
26116 (concat
26117 html
26118 "<tr>"
26119 (mapconcat
26120 (lambda (x)
26121 (if (equal x "") (setq x empty))
26122 (if head
26123 (concat (car org-export-table-header-tags) x
26124 (cdr org-export-table-header-tags))
26125 (concat (car org-export-table-data-tags) x
26126 (cdr org-export-table-data-tags))))
26127 field-buffer "\n")
26128 "</tr>\n"))
26129 (setq head nil)
26130 (setq field-buffer nil)))
26131 ;; Ignore this line
26132 (throw 'next-line t)))
26133 ;; Break the line into fields and store the fields
26134 (setq fields (org-split-string line "[ \t]*|[ \t]*"))
26135 (if field-buffer
26136 (setq field-buffer (mapcar
26137 (lambda (x)
26138 (concat x "<br/>" (pop fields)))
26139 field-buffer))
26140 (setq field-buffer fields))))
26141 (setq html (concat html "</table>\n"))
26142 html))
26144 (defun org-format-table-table-html-using-table-generate-source (lines)
26145 "Format a table into html, using `table-generate-source' from table.el.
26146 This has the advantage that cell- or row-spanning is allowed.
26147 But it has the disadvantage, that Org-mode's HTML conversions cannot be used."
26148 (require 'table)
26149 (with-current-buffer (get-buffer-create " org-tmp1 ")
26150 (erase-buffer)
26151 (insert (mapconcat 'identity lines "\n"))
26152 (goto-char (point-min))
26153 (if (not (re-search-forward "|[^+]" nil t))
26154 (error "Error processing table"))
26155 (table-recognize-table)
26156 (with-current-buffer (get-buffer-create " org-tmp2 ") (erase-buffer))
26157 (table-generate-source 'html " org-tmp2 ")
26158 (set-buffer " org-tmp2 ")
26159 (buffer-substring (point-min) (point-max))))
26161 (defun org-html-handle-time-stamps (s)
26162 "Format time stamps in string S, or remove them."
26163 (catch 'exit
26164 (let (r b)
26165 (while (string-match org-maybe-keyword-time-regexp s)
26166 (if (and (match-end 1) (equal (match-string 1 s) org-clock-string))
26167 ;; never export CLOCK
26168 (throw 'exit ""))
26169 (or b (setq b (substring s 0 (match-beginning 0))))
26170 (if (not org-export-with-timestamps)
26171 (setq r (concat r (substring s 0 (match-beginning 0)))
26172 s (substring s (match-end 0)))
26173 (setq r (concat
26174 r (substring s 0 (match-beginning 0))
26175 (if (match-end 1)
26176 (format "@<span class=\"timestamp-kwd\">%s @</span>"
26177 (match-string 1 s)))
26178 (format " @<span class=\"timestamp\">%s@</span>"
26179 (substring
26180 (org-translate-time (match-string 3 s)) 1 -1)))
26181 s (substring s (match-end 0)))))
26182 ;; Line break if line started and ended with time stamp stuff
26183 (if (not r)
26185 (setq r (concat r s))
26186 (unless (string-match "\\S-" (concat b s))
26187 (setq r (concat r "@<br/>")))
26188 r))))
26190 (defun org-html-protect (s)
26191 ;; convert & to &amp;, < to &lt; and > to &gt;
26192 (let ((start 0))
26193 (while (string-match "&" s start)
26194 (setq s (replace-match "&amp;" t t s)
26195 start (1+ (match-beginning 0))))
26196 (while (string-match "<" s)
26197 (setq s (replace-match "&lt;" t t s)))
26198 (while (string-match ">" s)
26199 (setq s (replace-match "&gt;" t t s))))
26202 (defun org-export-cleanup-toc-line (s)
26203 "Remove tags and time staps from lines going into the toc."
26204 (when (memq org-export-with-tags '(not-in-toc nil))
26205 (if (string-match (org-re " +:[[:alnum:]_@:]+: *$") s)
26206 (setq s (replace-match "" t t s))))
26207 (when org-export-remove-timestamps-from-toc
26208 (while (string-match org-maybe-keyword-time-regexp s)
26209 (setq s (replace-match "" t t s))))
26210 (while (string-match org-bracket-link-regexp s)
26211 (setq s (replace-match (match-string (if (match-end 3) 3 1) s)
26212 t t s)))
26215 (defun org-html-expand (string)
26216 "Prepare STRING for HTML export. Applies all active conversions.
26217 If there are links in the string, don't modify these."
26218 (let* ((re (concat org-bracket-link-regexp "\\|"
26219 (org-re "[ \t]+\\(:[[:alnum:]_@:]+:\\)[ \t]*$")))
26220 m s l res)
26221 (while (setq m (string-match re string))
26222 (setq s (substring string 0 m)
26223 l (match-string 0 string)
26224 string (substring string (match-end 0)))
26225 (push (org-html-do-expand s) res)
26226 (push l res))
26227 (push (org-html-do-expand string) res)
26228 (apply 'concat (nreverse res))))
26230 (defun org-html-do-expand (s)
26231 "Apply all active conversions to translate special ASCII to HTML."
26232 (setq s (org-html-protect s))
26233 (if org-export-html-expand
26234 (let ((start 0))
26235 (while (string-match "@&lt;\\([^&]*\\)&gt;" s)
26236 (setq s (replace-match "<\\1>" t nil s)))))
26237 (if org-export-with-emphasize
26238 (setq s (org-export-html-convert-emphasize s)))
26239 (if org-export-with-special-strings
26240 (setq s (org-export-html-convert-special-strings s)))
26241 (if org-export-with-sub-superscripts
26242 (setq s (org-export-html-convert-sub-super s)))
26243 (if org-export-with-TeX-macros
26244 (let ((start 0) wd ass)
26245 (while (setq start (string-match "\\\\\\([a-zA-Z]+\\)" s start))
26246 (if (get-text-property (match-beginning 0) 'org-protected s)
26247 (setq start (match-end 0))
26248 (setq wd (match-string 1 s))
26249 (if (setq ass (assoc wd org-html-entities))
26250 (setq s (replace-match (or (cdr ass)
26251 (concat "&" (car ass) ";"))
26252 t t s))
26253 (setq start (+ start (length wd))))))))
26256 (defun org-create-multibrace-regexp (left right n)
26257 "Create a regular expression which will match a balanced sexp.
26258 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
26259 as single character strings.
26260 The regexp returned will match the entire expression including the
26261 delimiters. It will also define a single group which contains the
26262 match except for the outermost delimiters. The maximum depth of
26263 stacked delimiters is N. Escaping delimiters is not possible."
26264 (let* ((nothing (concat "[^" "\\" left "\\" right "]*?"))
26265 (or "\\|")
26266 (re nothing)
26267 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
26268 (while (> n 1)
26269 (setq n (1- n)
26270 re (concat re or next)
26271 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
26272 (concat left "\\(" re "\\)" right)))
26274 (defvar org-match-substring-regexp
26275 (concat
26276 "\\([^\\]\\)\\([_^]\\)\\("
26277 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
26278 "\\|"
26279 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
26280 "\\|"
26281 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
26282 "The regular expression matching a sub- or superscript.")
26284 (defvar org-match-substring-with-braces-regexp
26285 (concat
26286 "\\([^\\]\\)\\([_^]\\)\\("
26287 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
26288 "\\)")
26289 "The regular expression matching a sub- or superscript, forcing braces.")
26291 (defconst org-export-html-special-string-regexps
26292 '(("\\\\-" . "&shy;")
26293 ("---\\([^-]\\)" . "&mdash;\\1")
26294 ("--\\([^-]\\)" . "&ndash;\\1")
26295 ("\\.\\.\\." . "&hellip;"))
26296 "Regular expressions for special string conversion.")
26298 (defun org-export-html-convert-special-strings (string)
26299 "Convert special characters in STRING to HTML."
26300 (let ((all org-export-html-special-string-regexps)
26301 e a re rpl start)
26302 (while (setq a (pop all))
26303 (setq re (car a) rpl (cdr a) start 0)
26304 (while (string-match re string start)
26305 (if (get-text-property (match-beginning 0) 'org-protected string)
26306 (setq start (match-end 0))
26307 (setq string (replace-match rpl t nil string)))))
26308 string))
26310 (defun org-export-html-convert-sub-super (string)
26311 "Convert sub- and superscripts in STRING to HTML."
26312 (let (key c (s 0) (requireb (eq org-export-with-sub-superscripts '{})))
26313 (while (string-match org-match-substring-regexp string s)
26314 (cond
26315 ((and requireb (match-end 8)) (setq s (match-end 2)))
26316 ((get-text-property (match-beginning 2) 'org-protected string)
26317 (setq s (match-end 2)))
26319 (setq s (match-end 1)
26320 key (if (string= (match-string 2 string) "_") "sub" "sup")
26321 c (or (match-string 8 string)
26322 (match-string 6 string)
26323 (match-string 5 string))
26324 string (replace-match
26325 (concat (match-string 1 string)
26326 "<" key ">" c "</" key ">")
26327 t t string)))))
26328 (while (string-match "\\\\\\([_^]\\)" string)
26329 (setq string (replace-match (match-string 1 string) t t string)))
26330 string))
26332 (defun org-export-html-convert-emphasize (string)
26333 "Apply emphasis."
26334 (let ((s 0) rpl)
26335 (while (string-match org-emph-re string s)
26336 (if (not (equal
26337 (substring string (match-beginning 3) (1+ (match-beginning 3)))
26338 (substring string (match-beginning 4) (1+ (match-beginning 4)))))
26339 (setq s (match-beginning 0)
26341 (concat
26342 (match-string 1 string)
26343 (nth 2 (assoc (match-string 3 string) org-emphasis-alist))
26344 (match-string 4 string)
26345 (nth 3 (assoc (match-string 3 string)
26346 org-emphasis-alist))
26347 (match-string 5 string))
26348 string (replace-match rpl t t string)
26349 s (+ s (- (length rpl) 2)))
26350 (setq s (1+ s))))
26351 string))
26353 (defvar org-par-open nil)
26354 (defun org-open-par ()
26355 "Insert <p>, but first close previous paragraph if any."
26356 (org-close-par-maybe)
26357 (insert "\n<p>")
26358 (setq org-par-open t))
26359 (defun org-close-par-maybe ()
26360 "Close paragraph if there is one open."
26361 (when org-par-open
26362 (insert "</p>")
26363 (setq org-par-open nil)))
26364 (defun org-close-li ()
26365 "Close <li> if necessary."
26366 (org-close-par-maybe)
26367 (insert "</li>\n"))
26369 (defvar body-only) ; dynamically scoped into this.
26370 (defun org-html-level-start (level title umax with-toc head-count)
26371 "Insert a new level in HTML export.
26372 When TITLE is nil, just close all open levels."
26373 (org-close-par-maybe)
26374 (let ((l org-level-max))
26375 (while (>= l level)
26376 (if (aref org-levels-open (1- l))
26377 (progn
26378 (org-html-level-close l umax)
26379 (aset org-levels-open (1- l) nil)))
26380 (setq l (1- l)))
26381 (when title
26382 ;; If title is nil, this means this function is called to close
26383 ;; all levels, so the rest is done only if title is given
26384 (when (string-match (org-re "\\(:[[:alnum:]_@:]+:\\)[ \t]*$") title)
26385 (setq title (replace-match
26386 (if org-export-with-tags
26387 (save-match-data
26388 (concat
26389 "&nbsp;&nbsp;&nbsp;<span class=\"tag\">"
26390 (mapconcat 'identity (org-split-string
26391 (match-string 1 title) ":")
26392 "&nbsp;")
26393 "</span>"))
26395 t t title)))
26396 (if (> level umax)
26397 (progn
26398 (if (aref org-levels-open (1- level))
26399 (progn
26400 (org-close-li)
26401 (insert "<li>" title "<br/>\n"))
26402 (aset org-levels-open (1- level) t)
26403 (org-close-par-maybe)
26404 (insert "<ul>\n<li>" title "<br/>\n")))
26405 (aset org-levels-open (1- level) t)
26406 (if (and org-export-with-section-numbers (not body-only))
26407 (setq title (concat (org-section-number level) " " title)))
26408 (setq level (+ level org-export-html-toplevel-hlevel -1))
26409 (if with-toc
26410 (insert (format "\n<div class=\"outline-%d\">\n<h%d id=\"sec-%d\">%s</h%d>\n"
26411 level level head-count title level))
26412 (insert (format "\n<div class=\"outline-%d\">\n<h%d>%s</h%d>\n" level level title level)))
26413 (org-open-par)))))
26415 (defun org-html-level-close (level max-outline-level)
26416 "Terminate one level in HTML export."
26417 (if (<= level max-outline-level)
26418 (insert "</div>\n")
26419 (org-close-li)
26420 (insert "</ul>\n")))
26422 ;;; iCalendar export
26424 ;;;###autoload
26425 (defun org-export-icalendar-this-file ()
26426 "Export current file as an iCalendar file.
26427 The iCalendar file will be located in the same directory as the Org-mode
26428 file, but with extension `.ics'."
26429 (interactive)
26430 (org-export-icalendar nil buffer-file-name))
26432 ;;;###autoload
26433 (defun org-export-icalendar-all-agenda-files ()
26434 "Export all files in `org-agenda-files' to iCalendar .ics files.
26435 Each iCalendar file will be located in the same directory as the Org-mode
26436 file, but with extension `.ics'."
26437 (interactive)
26438 (apply 'org-export-icalendar nil (org-agenda-files t)))
26440 ;;;###autoload
26441 (defun org-export-icalendar-combine-agenda-files ()
26442 "Export all files in `org-agenda-files' to a single combined iCalendar file.
26443 The file is stored under the name `org-combined-agenda-icalendar-file'."
26444 (interactive)
26445 (apply 'org-export-icalendar t (org-agenda-files t)))
26447 (defun org-export-icalendar (combine &rest files)
26448 "Create iCalendar files for all elements of FILES.
26449 If COMBINE is non-nil, combine all calendar entries into a single large
26450 file and store it under the name `org-combined-agenda-icalendar-file'."
26451 (save-excursion
26452 (org-prepare-agenda-buffers files)
26453 (let* ((dir (org-export-directory
26454 :ical (list :publishing-directory
26455 org-export-publishing-directory)))
26456 file ical-file ical-buffer category started org-agenda-new-buffers)
26458 (and (get-buffer "*ical-tmp*") (kill-buffer "*ical-tmp*"))
26459 (when combine
26460 (setq ical-file
26461 (if (file-name-absolute-p org-combined-agenda-icalendar-file)
26462 org-combined-agenda-icalendar-file
26463 (expand-file-name org-combined-agenda-icalendar-file dir))
26464 ical-buffer (org-get-agenda-file-buffer ical-file))
26465 (set-buffer ical-buffer) (erase-buffer))
26466 (while (setq file (pop files))
26467 (catch 'nextfile
26468 (org-check-agenda-file file)
26469 (set-buffer (org-get-agenda-file-buffer file))
26470 (unless combine
26471 (setq ical-file (concat (file-name-as-directory dir)
26472 (file-name-sans-extension
26473 (file-name-nondirectory buffer-file-name))
26474 ".ics"))
26475 (setq ical-buffer (org-get-agenda-file-buffer ical-file))
26476 (with-current-buffer ical-buffer (erase-buffer)))
26477 (setq category (or org-category
26478 (file-name-sans-extension
26479 (file-name-nondirectory buffer-file-name))))
26480 (if (symbolp category) (setq category (symbol-name category)))
26481 (let ((standard-output ical-buffer))
26482 (if combine
26483 (and (not started) (setq started t)
26484 (org-start-icalendar-file org-icalendar-combined-name))
26485 (org-start-icalendar-file category))
26486 (org-print-icalendar-entries combine)
26487 (when (or (and combine (not files)) (not combine))
26488 (org-finish-icalendar-file)
26489 (set-buffer ical-buffer)
26490 (save-buffer)
26491 (run-hooks 'org-after-save-iCalendar-file-hook)))))
26492 (org-release-buffers org-agenda-new-buffers))))
26494 (defvar org-after-save-iCalendar-file-hook nil
26495 "Hook run after an iCalendar file has been saved.
26496 The iCalendar buffer is still current when this hook is run.
26497 A good way to use this is to tell a desktop calenndar application to re-read
26498 the iCalendar file.")
26500 (defun org-print-icalendar-entries (&optional combine)
26501 "Print iCalendar entries for the current Org-mode file to `standard-output'.
26502 When COMBINE is non nil, add the category to each line."
26503 (let ((re1 (concat org-ts-regexp "\\|<%%([^>\n]+>"))
26504 (re2 (concat "--?-?\\(" org-ts-regexp "\\)"))
26505 (dts (org-ical-ts-to-string
26506 (format-time-string (cdr org-time-stamp-formats) (current-time))
26507 "DTSTART"))
26508 hd ts ts2 state status (inc t) pos b sexp rrule
26509 scheduledp deadlinep tmp pri category entry location summary desc
26510 (sexp-buffer (get-buffer-create "*ical-tmp*")))
26511 (org-refresh-category-properties)
26512 (save-excursion
26513 (goto-char (point-min))
26514 (while (re-search-forward re1 nil t)
26515 (catch :skip
26516 (org-agenda-skip)
26517 (setq pos (match-beginning 0)
26518 ts (match-string 0)
26519 inc t
26520 hd (org-get-heading)
26521 summary (org-icalendar-cleanup-string
26522 (org-entry-get nil "SUMMARY"))
26523 desc (org-icalendar-cleanup-string
26524 (or (org-entry-get nil "DESCRIPTION")
26525 (and org-icalendar-include-body (org-get-entry)))
26526 t org-icalendar-include-body)
26527 location (org-icalendar-cleanup-string
26528 (org-entry-get nil "LOCATION"))
26529 category (org-get-category))
26530 (if (looking-at re2)
26531 (progn
26532 (goto-char (match-end 0))
26533 (setq ts2 (match-string 1) inc nil))
26534 (setq tmp (buffer-substring (max (point-min)
26535 (- pos org-ds-keyword-length))
26536 pos)
26537 ts2 (if (string-match "[0-9]\\{1,2\\}:[0-9][0-9]-\\([0-9]\\{1,2\\}:[0-9][0-9]\\)" ts)
26538 (progn
26539 (setq inc nil)
26540 (replace-match "\\1" t nil ts))
26542 deadlinep (string-match org-deadline-regexp tmp)
26543 scheduledp (string-match org-scheduled-regexp tmp)
26544 ;; donep (org-entry-is-done-p)
26546 (if (or (string-match org-tr-regexp hd)
26547 (string-match org-ts-regexp hd))
26548 (setq hd (replace-match "" t t hd)))
26549 (if (string-match "\\+\\([0-9]+\\)\\([dwmy]\\)>" ts)
26550 (setq rrule
26551 (concat "\nRRULE:FREQ="
26552 (cdr (assoc
26553 (match-string 2 ts)
26554 '(("d" . "DAILY")("w" . "WEEKLY")
26555 ("m" . "MONTHLY")("y" . "YEARLY"))))
26556 ";INTERVAL=" (match-string 1 ts)))
26557 (setq rrule ""))
26558 (setq summary (or summary hd))
26559 (if (string-match org-bracket-link-regexp summary)
26560 (setq summary
26561 (replace-match (if (match-end 3)
26562 (match-string 3 summary)
26563 (match-string 1 summary))
26564 t t summary)))
26565 (if deadlinep (setq summary (concat "DL: " summary)))
26566 (if scheduledp (setq summary (concat "S: " summary)))
26567 (if (string-match "\\`<%%" ts)
26568 (with-current-buffer sexp-buffer
26569 (insert (substring ts 1 -1) " " summary "\n"))
26570 (princ (format "BEGIN:VEVENT
26572 %s%s
26573 SUMMARY:%s%s%s
26574 CATEGORIES:%s
26575 END:VEVENT\n"
26576 (org-ical-ts-to-string ts "DTSTART")
26577 (org-ical-ts-to-string ts2 "DTEND" inc)
26578 rrule summary
26579 (if (and desc (string-match "\\S-" desc))
26580 (concat "\nDESCRIPTION: " desc) "")
26581 (if (and location (string-match "\\S-" location))
26582 (concat "\nLOCATION: " location) "")
26583 category)))))
26585 (when (and org-icalendar-include-sexps
26586 (condition-case nil (require 'icalendar) (error nil))
26587 (fboundp 'icalendar-export-region))
26588 ;; Get all the literal sexps
26589 (goto-char (point-min))
26590 (while (re-search-forward "^&?%%(" nil t)
26591 (catch :skip
26592 (org-agenda-skip)
26593 (setq b (match-beginning 0))
26594 (goto-char (1- (match-end 0)))
26595 (forward-sexp 1)
26596 (end-of-line 1)
26597 (setq sexp (buffer-substring b (point)))
26598 (with-current-buffer sexp-buffer
26599 (insert sexp "\n"))
26600 (princ (org-diary-to-ical-string sexp-buffer)))))
26602 (when org-icalendar-include-todo
26603 (goto-char (point-min))
26604 (while (re-search-forward org-todo-line-regexp nil t)
26605 (catch :skip
26606 (org-agenda-skip)
26607 (setq state (match-string 2))
26608 (setq status (if (member state org-done-keywords)
26609 "COMPLETED" "NEEDS-ACTION"))
26610 (when (and state
26611 (or (not (member state org-done-keywords))
26612 (eq org-icalendar-include-todo 'all))
26613 (not (member org-archive-tag (org-get-tags-at)))
26615 (setq hd (match-string 3)
26616 summary (org-icalendar-cleanup-string
26617 (org-entry-get nil "SUMMARY"))
26618 desc (org-icalendar-cleanup-string
26619 (or (org-entry-get nil "DESCRIPTION")
26620 (and org-icalendar-include-body (org-get-entry)))
26621 t org-icalendar-include-body)
26622 location (org-icalendar-cleanup-string
26623 (org-entry-get nil "LOCATION")))
26624 (if (string-match org-bracket-link-regexp hd)
26625 (setq hd (replace-match (if (match-end 3) (match-string 3 hd)
26626 (match-string 1 hd))
26627 t t hd)))
26628 (if (string-match org-priority-regexp hd)
26629 (setq pri (string-to-char (match-string 2 hd))
26630 hd (concat (substring hd 0 (match-beginning 1))
26631 (substring hd (match-end 1))))
26632 (setq pri org-default-priority))
26633 (setq pri (floor (1+ (* 8. (/ (float (- org-lowest-priority pri))
26634 (- org-lowest-priority org-highest-priority))))))
26636 (princ (format "BEGIN:VTODO
26638 SUMMARY:%s%s%s
26639 CATEGORIES:%s
26640 SEQUENCE:1
26641 PRIORITY:%d
26642 STATUS:%s
26643 END:VTODO\n"
26645 (or summary hd)
26646 (if (and location (string-match "\\S-" location))
26647 (concat "\nLOCATION: " location) "")
26648 (if (and desc (string-match "\\S-" desc))
26649 (concat "\nDESCRIPTION: " desc) "")
26650 category pri status)))))))))
26652 (defun org-icalendar-cleanup-string (s &optional is-body maxlength)
26653 "Take out stuff and quote what needs to be quoted.
26654 When IS-BODY is non-nil, assume that this is the body of an item, clean up
26655 whitespace, newlines, drawers, and timestamps, and cut it down to MAXLENGTH
26656 characters."
26657 (if (not s)
26659 (when is-body
26660 (let ((re (concat "\\(" org-drawer-regexp "\\)[^\000]*?:END:.*\n?"))
26661 (re2 (concat "^[ \t]*" org-keyword-time-regexp ".*\n?")))
26662 (while (string-match re s) (setq s (replace-match "" t t s)))
26663 (while (string-match re2 s) (setq s (replace-match "" t t s)))))
26664 (let ((start 0))
26665 (while (string-match "\\([,;\\]\\)" s start)
26666 (setq start (+ (match-beginning 0) 2)
26667 s (replace-match "\\\\\\1" nil nil s))))
26668 (when is-body
26669 (while (string-match "[ \t]*\n[ \t]*" s)
26670 (setq s (replace-match "\\n" t t s))))
26671 (setq s (org-trim s))
26672 (if is-body
26673 (if maxlength
26674 (if (and (numberp maxlength)
26675 (> (length s) maxlength))
26676 (setq s (substring s 0 maxlength)))))
26679 (defun org-get-entry ()
26680 "Clean-up description string."
26681 (save-excursion
26682 (org-back-to-heading t)
26683 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
26685 (defun org-start-icalendar-file (name)
26686 "Start an iCalendar file by inserting the header."
26687 (let ((user user-full-name)
26688 (name (or name "unknown"))
26689 (timezone (cadr (current-time-zone))))
26690 (princ
26691 (format "BEGIN:VCALENDAR
26692 VERSION:2.0
26693 X-WR-CALNAME:%s
26694 PRODID:-//%s//Emacs with Org-mode//EN
26695 X-WR-TIMEZONE:%s
26696 CALSCALE:GREGORIAN\n" name user timezone))))
26698 (defun org-finish-icalendar-file ()
26699 "Finish an iCalendar file by inserting the END statement."
26700 (princ "END:VCALENDAR\n"))
26702 (defun org-ical-ts-to-string (s keyword &optional inc)
26703 "Take a time string S and convert it to iCalendar format.
26704 KEYWORD is added in front, to make a complete line like DTSTART....
26705 When INC is non-nil, increase the hour by two (if time string contains
26706 a time), or the day by one (if it does not contain a time)."
26707 (let ((t1 (org-parse-time-string s 'nodefault))
26708 t2 fmt have-time time)
26709 (if (and (car t1) (nth 1 t1) (nth 2 t1))
26710 (setq t2 t1 have-time t)
26711 (setq t2 (org-parse-time-string s)))
26712 (let ((s (car t2)) (mi (nth 1 t2)) (h (nth 2 t2))
26713 (d (nth 3 t2)) (m (nth 4 t2)) (y (nth 5 t2)))
26714 (when inc
26715 (if have-time
26716 (if org-agenda-default-appointment-duration
26717 (setq mi (+ org-agenda-default-appointment-duration mi))
26718 (setq h (+ 2 h)))
26719 (setq d (1+ d))))
26720 (setq time (encode-time s mi h d m y)))
26721 (setq fmt (if have-time ":%Y%m%dT%H%M%S" ";VALUE=DATE:%Y%m%d"))
26722 (concat keyword (format-time-string fmt time))))
26724 ;;; XOXO export
26726 (defun org-export-as-xoxo-insert-into (buffer &rest output)
26727 (with-current-buffer buffer
26728 (apply 'insert output)))
26729 (put 'org-export-as-xoxo-insert-into 'lisp-indent-function 1)
26731 (defun org-export-as-xoxo (&optional buffer)
26732 "Export the org buffer as XOXO.
26733 The XOXO buffer is named *xoxo-<source buffer name>*"
26734 (interactive (list (current-buffer)))
26735 ;; A quickie abstraction
26737 ;; Output everything as XOXO
26738 (with-current-buffer (get-buffer buffer)
26739 (let* ((pos (point))
26740 (opt-plist (org-combine-plists (org-default-export-plist)
26741 (org-infile-export-plist)))
26742 (filename (concat (file-name-as-directory
26743 (org-export-directory :xoxo opt-plist))
26744 (file-name-sans-extension
26745 (file-name-nondirectory buffer-file-name))
26746 ".html"))
26747 (out (find-file-noselect filename))
26748 (last-level 1)
26749 (hanging-li nil))
26750 (goto-char (point-min)) ;; CD: beginning-of-buffer is not allowed.
26751 ;; Check the output buffer is empty.
26752 (with-current-buffer out (erase-buffer))
26753 ;; Kick off the output
26754 (org-export-as-xoxo-insert-into out "<ol class='xoxo'>\n")
26755 (while (re-search-forward "^\\(\\*+\\)[ \t]+\\(.+\\)" (point-max) 't)
26756 (let* ((hd (match-string-no-properties 1))
26757 (level (length hd))
26758 (text (concat
26759 (match-string-no-properties 2)
26760 (save-excursion
26761 (goto-char (match-end 0))
26762 (let ((str ""))
26763 (catch 'loop
26764 (while 't
26765 (forward-line)
26766 (if (looking-at "^[ \t]\\(.*\\)")
26767 (setq str (concat str (match-string-no-properties 1)))
26768 (throw 'loop str)))))))))
26770 ;; Handle level rendering
26771 (cond
26772 ((> level last-level)
26773 (org-export-as-xoxo-insert-into out "\n<ol>\n"))
26775 ((< level last-level)
26776 (dotimes (- (- last-level level) 1)
26777 (if hanging-li
26778 (org-export-as-xoxo-insert-into out "</li>\n"))
26779 (org-export-as-xoxo-insert-into out "</ol>\n"))
26780 (when hanging-li
26781 (org-export-as-xoxo-insert-into out "</li>\n")
26782 (setq hanging-li nil)))
26784 ((equal level last-level)
26785 (if hanging-li
26786 (org-export-as-xoxo-insert-into out "</li>\n")))
26789 (setq last-level level)
26791 ;; And output the new li
26792 (setq hanging-li 't)
26793 (if (equal ?+ (elt text 0))
26794 (org-export-as-xoxo-insert-into out "<li class='" (substring text 1) "'>")
26795 (org-export-as-xoxo-insert-into out "<li>" text))))
26797 ;; Finally finish off the ol
26798 (dotimes (- last-level 1)
26799 (if hanging-li
26800 (org-export-as-xoxo-insert-into out "</li>\n"))
26801 (org-export-as-xoxo-insert-into out "</ol>\n"))
26803 (goto-char pos)
26804 ;; Finish the buffer off and clean it up.
26805 (switch-to-buffer-other-window out)
26806 (indent-region (point-min) (point-max) nil)
26807 (save-buffer)
26808 (goto-char (point-min))
26812 ;;;; Key bindings
26814 ;; Make `C-c C-x' a prefix key
26815 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
26817 ;; TAB key with modifiers
26818 (org-defkey org-mode-map "\C-i" 'org-cycle)
26819 (org-defkey org-mode-map [(tab)] 'org-cycle)
26820 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
26821 (org-defkey org-mode-map [(meta tab)] 'org-complete)
26822 (org-defkey org-mode-map "\M-\t" 'org-complete)
26823 (org-defkey org-mode-map "\M-\C-i" 'org-complete)
26824 ;; The following line is necessary under Suse GNU/Linux
26825 (unless (featurep 'xemacs)
26826 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
26827 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
26828 (define-key org-mode-map [backtab] 'org-shifttab)
26830 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
26831 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
26832 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
26834 ;; Cursor keys with modifiers
26835 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
26836 (org-defkey org-mode-map [(meta right)] 'org-metaright)
26837 (org-defkey org-mode-map [(meta up)] 'org-metaup)
26838 (org-defkey org-mode-map [(meta down)] 'org-metadown)
26840 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
26841 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
26842 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
26843 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
26845 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
26846 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
26847 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
26848 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
26850 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
26851 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
26853 ;;; Extra keys for tty access.
26854 ;; We only set them when really needed because otherwise the
26855 ;; menus don't show the simple keys
26857 (when (or (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
26858 (not window-system))
26859 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
26860 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
26861 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
26862 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
26863 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
26864 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
26865 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
26866 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
26867 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
26868 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
26869 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
26870 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
26871 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
26872 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
26873 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
26874 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
26875 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
26876 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
26877 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
26878 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
26879 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
26880 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft))
26882 ;; All the other keys
26884 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
26885 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
26886 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree)
26887 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
26888 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
26889 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-toggle-archive-tag)
26890 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
26891 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
26892 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
26893 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
26894 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
26895 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
26896 (org-defkey org-mode-map "\C-c\C-v" 'org-show-todo-tree)
26897 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
26898 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
26899 (org-defkey org-mode-map "\C-c\\" 'org-tags-sparse-tree) ; Minor-mode res.
26900 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
26901 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
26902 (org-defkey org-mode-map [(control return)] 'org-insert-heading-after-current)
26903 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
26904 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
26905 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
26906 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
26907 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
26908 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
26909 (org-defkey org-mode-map "\C-c\C-z" 'org-time-stamp) ; Alternative binding
26910 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
26911 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
26912 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
26913 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
26914 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
26915 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
26916 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
26917 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
26918 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
26919 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
26920 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
26921 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
26922 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
26923 (org-defkey org-mode-map "\C-c^" 'org-sort)
26924 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
26925 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
26926 (org-defkey org-mode-map "\C-c#" 'org-update-checkbox-count)
26927 (org-defkey org-mode-map "\C-m" 'org-return)
26928 (org-defkey org-mode-map "\C-j" 'org-return-indent)
26929 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
26930 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
26931 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
26932 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
26933 (org-defkey org-mode-map "\C-c'" 'org-table-edit-formulas)
26934 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
26935 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
26936 (org-defkey org-mode-map "\C-c*" 'org-table-recalculate)
26937 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
26938 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
26939 (org-defkey org-mode-map "\C-c\C-q" 'org-table-wrap-region)
26940 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
26941 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
26942 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
26943 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
26944 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
26946 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-cut-special)
26947 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
26948 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
26949 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
26951 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
26952 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
26953 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
26954 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
26955 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
26956 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
26957 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
26958 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
26959 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
26960 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
26961 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
26962 (org-defkey org-mode-map "\C-c\C-xr" 'org-insert-columns-dblock)
26964 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
26966 (when (featurep 'xemacs)
26967 (org-defkey org-mode-map 'button3 'popup-mode-menu))
26969 (defsubst org-table-p () (org-at-table-p))
26971 (defun org-self-insert-command (N)
26972 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
26973 If the cursor is in a table looking at whitespace, the whitespace is
26974 overwritten, and the table is not marked as requiring realignment."
26975 (interactive "p")
26976 (if (and (org-table-p)
26977 (progn
26978 ;; check if we blank the field, and if that triggers align
26979 (and org-table-auto-blank-field
26980 (member last-command
26981 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
26982 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
26983 ;; got extra space, this field does not determine column width
26984 (let (org-table-may-need-update) (org-table-blank-field))
26985 ;; no extra space, this field may determine column width
26986 (org-table-blank-field)))
26988 (eq N 1)
26989 (looking-at "[^|\n]* |"))
26990 (let (org-table-may-need-update)
26991 (goto-char (1- (match-end 0)))
26992 (delete-backward-char 1)
26993 (goto-char (match-beginning 0))
26994 (self-insert-command N))
26995 (setq org-table-may-need-update t)
26996 (self-insert-command N)
26997 (org-fix-tags-on-the-fly)))
26999 (defun org-fix-tags-on-the-fly ()
27000 (when (and (equal (char-after (point-at-bol)) ?*)
27001 (org-on-heading-p))
27002 (org-align-tags-here org-tags-column)))
27004 (defun org-delete-backward-char (N)
27005 "Like `delete-backward-char', insert whitespace at field end in tables.
27006 When deleting backwards, in tables this function will insert whitespace in
27007 front of the next \"|\" separator, to keep the table aligned. The table will
27008 still be marked for re-alignment if the field did fill the entire column,
27009 because, in this case the deletion might narrow the column."
27010 (interactive "p")
27011 (if (and (org-table-p)
27012 (eq N 1)
27013 (string-match "|" (buffer-substring (point-at-bol) (point)))
27014 (looking-at ".*?|"))
27015 (let ((pos (point))
27016 (noalign (looking-at "[^|\n\r]* |"))
27017 (c org-table-may-need-update))
27018 (backward-delete-char N)
27019 (skip-chars-forward "^|")
27020 (insert " ")
27021 (goto-char (1- pos))
27022 ;; noalign: if there were two spaces at the end, this field
27023 ;; does not determine the width of the column.
27024 (if noalign (setq org-table-may-need-update c)))
27025 (backward-delete-char N)
27026 (org-fix-tags-on-the-fly)))
27028 (defun org-delete-char (N)
27029 "Like `delete-char', but insert whitespace at field end in tables.
27030 When deleting characters, in tables this function will insert whitespace in
27031 front of the next \"|\" separator, to keep the table aligned. The table will
27032 still be marked for re-alignment if the field did fill the entire column,
27033 because, in this case the deletion might narrow the column."
27034 (interactive "p")
27035 (if (and (org-table-p)
27036 (not (bolp))
27037 (not (= (char-after) ?|))
27038 (eq N 1))
27039 (if (looking-at ".*?|")
27040 (let ((pos (point))
27041 (noalign (looking-at "[^|\n\r]* |"))
27042 (c org-table-may-need-update))
27043 (replace-match (concat
27044 (substring (match-string 0) 1 -1)
27045 " |"))
27046 (goto-char pos)
27047 ;; noalign: if there were two spaces at the end, this field
27048 ;; does not determine the width of the column.
27049 (if noalign (setq org-table-may-need-update c)))
27050 (delete-char N))
27051 (delete-char N)
27052 (org-fix-tags-on-the-fly)))
27054 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
27055 (put 'org-self-insert-command 'delete-selection t)
27056 (put 'orgtbl-self-insert-command 'delete-selection t)
27057 (put 'org-delete-char 'delete-selection 'supersede)
27058 (put 'org-delete-backward-char 'delete-selection 'supersede)
27060 ;; Make `flyspell-mode' delay after some commands
27061 (put 'org-self-insert-command 'flyspell-delayed t)
27062 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
27063 (put 'org-delete-char 'flyspell-delayed t)
27064 (put 'org-delete-backward-char 'flyspell-delayed t)
27066 ;; Make pabbrev-mode expand after org-mode commands
27067 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
27068 (put 'orgybl-self-insert-command 'pabbrev-expand-after-command t)
27070 ;; How to do this: Measure non-white length of current string
27071 ;; If equal to column width, we should realign.
27073 (defun org-remap (map &rest commands)
27074 "In MAP, remap the functions given in COMMANDS.
27075 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
27076 (let (new old)
27077 (while commands
27078 (setq old (pop commands) new (pop commands))
27079 (if (fboundp 'command-remapping)
27080 (org-defkey map (vector 'remap old) new)
27081 (substitute-key-definition old new map global-map)))))
27083 (when (eq org-enable-table-editor 'optimized)
27084 ;; If the user wants maximum table support, we need to hijack
27085 ;; some standard editing functions
27086 (org-remap org-mode-map
27087 'self-insert-command 'org-self-insert-command
27088 'delete-char 'org-delete-char
27089 'delete-backward-char 'org-delete-backward-char)
27090 (org-defkey org-mode-map "|" 'org-force-self-insert))
27092 (defun org-shiftcursor-error ()
27093 "Throw an error because Shift-Cursor command was applied in wrong context."
27094 (error "This command is active in special context like tables, headlines or timestamps"))
27096 (defun org-shifttab (&optional arg)
27097 "Global visibility cycling or move to previous table field.
27098 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
27099 on context.
27100 See the individual commands for more information."
27101 (interactive "P")
27102 (cond
27103 ((org-at-table-p) (call-interactively 'org-table-previous-field))
27104 (arg (message "Content view to level: ")
27105 (org-content (prefix-numeric-value arg))
27106 (setq org-cycle-global-status 'overview))
27107 (t (call-interactively 'org-global-cycle))))
27109 (defun org-shiftmetaleft ()
27110 "Promote subtree or delete table column.
27111 Calls `org-promote-subtree', `org-outdent-item',
27112 or `org-table-delete-column', depending on context.
27113 See the individual commands for more information."
27114 (interactive)
27115 (cond
27116 ((org-at-table-p) (call-interactively 'org-table-delete-column))
27117 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
27118 ((org-at-item-p) (call-interactively 'org-outdent-item))
27119 (t (org-shiftcursor-error))))
27121 (defun org-shiftmetaright ()
27122 "Demote subtree or insert table column.
27123 Calls `org-demote-subtree', `org-indent-item',
27124 or `org-table-insert-column', depending on context.
27125 See the individual commands for more information."
27126 (interactive)
27127 (cond
27128 ((org-at-table-p) (call-interactively 'org-table-insert-column))
27129 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
27130 ((org-at-item-p) (call-interactively 'org-indent-item))
27131 (t (org-shiftcursor-error))))
27133 (defun org-shiftmetaup (&optional arg)
27134 "Move subtree up or kill table row.
27135 Calls `org-move-subtree-up' or `org-table-kill-row' or
27136 `org-move-item-up' depending on context. See the individual commands
27137 for more information."
27138 (interactive "P")
27139 (cond
27140 ((org-at-table-p) (call-interactively 'org-table-kill-row))
27141 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
27142 ((org-at-item-p) (call-interactively 'org-move-item-up))
27143 (t (org-shiftcursor-error))))
27144 (defun org-shiftmetadown (&optional arg)
27145 "Move subtree down or insert table row.
27146 Calls `org-move-subtree-down' or `org-table-insert-row' or
27147 `org-move-item-down', depending on context. See the individual
27148 commands for more information."
27149 (interactive "P")
27150 (cond
27151 ((org-at-table-p) (call-interactively 'org-table-insert-row))
27152 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
27153 ((org-at-item-p) (call-interactively 'org-move-item-down))
27154 (t (org-shiftcursor-error))))
27156 (defun org-metaleft (&optional arg)
27157 "Promote heading or move table column to left.
27158 Calls `org-do-promote' or `org-table-move-column', depending on context.
27159 With no specific context, calls the Emacs default `backward-word'.
27160 See the individual commands for more information."
27161 (interactive "P")
27162 (cond
27163 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
27164 ((or (org-on-heading-p) (org-region-active-p))
27165 (call-interactively 'org-do-promote))
27166 ((org-at-item-p) (call-interactively 'org-outdent-item))
27167 (t (call-interactively 'backward-word))))
27169 (defun org-metaright (&optional arg)
27170 "Demote subtree or move table column to right.
27171 Calls `org-do-demote' or `org-table-move-column', depending on context.
27172 With no specific context, calls the Emacs default `forward-word'.
27173 See the individual commands for more information."
27174 (interactive "P")
27175 (cond
27176 ((org-at-table-p) (call-interactively 'org-table-move-column))
27177 ((or (org-on-heading-p) (org-region-active-p))
27178 (call-interactively 'org-do-demote))
27179 ((org-at-item-p) (call-interactively 'org-indent-item))
27180 (t (call-interactively 'forward-word))))
27182 (defun org-metaup (&optional arg)
27183 "Move subtree up or move table row up.
27184 Calls `org-move-subtree-up' or `org-table-move-row' or
27185 `org-move-item-up', depending on context. See the individual commands
27186 for more information."
27187 (interactive "P")
27188 (cond
27189 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
27190 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
27191 ((org-at-item-p) (call-interactively 'org-move-item-up))
27192 (t (transpose-lines 1) (beginning-of-line -1))))
27194 (defun org-metadown (&optional arg)
27195 "Move subtree down or move table row down.
27196 Calls `org-move-subtree-down' or `org-table-move-row' or
27197 `org-move-item-down', depending on context. See the individual
27198 commands for more information."
27199 (interactive "P")
27200 (cond
27201 ((org-at-table-p) (call-interactively 'org-table-move-row))
27202 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
27203 ((org-at-item-p) (call-interactively 'org-move-item-down))
27204 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
27206 (defun org-shiftup (&optional arg)
27207 "Increase item in timestamp or increase priority of current headline.
27208 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
27209 depending on context. See the individual commands for more information."
27210 (interactive "P")
27211 (cond
27212 ((org-at-timestamp-p t)
27213 (call-interactively (if org-edit-timestamp-down-means-later
27214 'org-timestamp-down 'org-timestamp-up)))
27215 ((org-on-heading-p) (call-interactively 'org-priority-up))
27216 ((org-at-item-p) (call-interactively 'org-previous-item))
27217 (t (call-interactively 'org-beginning-of-item) (beginning-of-line 1))))
27219 (defun org-shiftdown (&optional arg)
27220 "Decrease item in timestamp or decrease priority of current headline.
27221 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
27222 depending on context. See the individual commands for more information."
27223 (interactive "P")
27224 (cond
27225 ((org-at-timestamp-p t)
27226 (call-interactively (if org-edit-timestamp-down-means-later
27227 'org-timestamp-up 'org-timestamp-down)))
27228 ((org-on-heading-p) (call-interactively 'org-priority-down))
27229 (t (call-interactively 'org-next-item))))
27231 (defun org-shiftright ()
27232 "Next TODO keyword or timestamp one day later, depending on context."
27233 (interactive)
27234 (cond
27235 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
27236 ((org-on-heading-p) (org-call-with-arg 'org-todo 'right))
27237 ((org-at-item-p) (org-call-with-arg 'org-cycle-list-bullet nil))
27238 ((org-at-property-p) (call-interactively 'org-property-next-allowed-value))
27239 (t (org-shiftcursor-error))))
27241 (defun org-shiftleft ()
27242 "Previous TODO keyword or timestamp one day earlier, depending on context."
27243 (interactive)
27244 (cond
27245 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
27246 ((org-on-heading-p) (org-call-with-arg 'org-todo 'left))
27247 ((org-at-item-p) (org-call-with-arg 'org-cycle-list-bullet 'previous))
27248 ((org-at-property-p)
27249 (call-interactively 'org-property-previous-allowed-value))
27250 (t (org-shiftcursor-error))))
27252 (defun org-shiftcontrolright ()
27253 "Switch to next TODO set."
27254 (interactive)
27255 (cond
27256 ((org-on-heading-p) (org-call-with-arg 'org-todo 'nextset))
27257 (t (org-shiftcursor-error))))
27259 (defun org-shiftcontrolleft ()
27260 "Switch to previous TODO set."
27261 (interactive)
27262 (cond
27263 ((org-on-heading-p) (org-call-with-arg 'org-todo 'previousset))
27264 (t (org-shiftcursor-error))))
27266 (defun org-ctrl-c-ret ()
27267 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
27268 (interactive)
27269 (cond
27270 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
27271 (t (call-interactively 'org-insert-heading))))
27273 (defun org-copy-special ()
27274 "Copy region in table or copy current subtree.
27275 Calls `org-table-copy' or `org-copy-subtree', depending on context.
27276 See the individual commands for more information."
27277 (interactive)
27278 (call-interactively
27279 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
27281 (defun org-cut-special ()
27282 "Cut region in table or cut current subtree.
27283 Calls `org-table-copy' or `org-cut-subtree', depending on context.
27284 See the individual commands for more information."
27285 (interactive)
27286 (call-interactively
27287 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
27289 (defun org-paste-special (arg)
27290 "Paste rectangular region into table, or past subtree relative to level.
27291 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
27292 See the individual commands for more information."
27293 (interactive "P")
27294 (if (org-at-table-p)
27295 (org-table-paste-rectangle)
27296 (org-paste-subtree arg)))
27298 (defun org-ctrl-c-ctrl-c (&optional arg)
27299 "Set tags in headline, or update according to changed information at point.
27301 This command does many different things, depending on context:
27303 - If the cursor is in a headline, prompt for tags and insert them
27304 into the current line, aligned to `org-tags-column'. When called
27305 with prefix arg, realign all tags in the current buffer.
27307 - If the cursor is in one of the special #+KEYWORD lines, this
27308 triggers scanning the buffer for these lines and updating the
27309 information.
27311 - If the cursor is inside a table, realign the table. This command
27312 works even if the automatic table editor has been turned off.
27314 - If the cursor is on a #+TBLFM line, re-apply the formulas to
27315 the entire table.
27317 - If the cursor is a the beginning of a dynamic block, update it.
27319 - If the cursor is inside a table created by the table.el package,
27320 activate that table.
27322 - If the current buffer is a remember buffer, close note and file it.
27323 with a prefix argument, file it without further interaction to the default
27324 location.
27326 - If the cursor is on a <<<target>>>, update radio targets and corresponding
27327 links in this buffer.
27329 - If the cursor is on a numbered item in a plain list, renumber the
27330 ordered list.
27332 - If the cursor is on a checkbox, toggle it."
27333 (interactive "P")
27334 (let ((org-enable-table-editor t))
27335 (cond
27336 ((or org-clock-overlays
27337 org-occur-highlights
27338 org-latex-fragment-image-overlays)
27339 (org-remove-clock-overlays)
27340 (org-remove-occur-highlights)
27341 (org-remove-latex-fragment-image-overlays)
27342 (message "Temporary highlights/overlays removed from current buffer"))
27343 ((and (local-variable-p 'org-finish-function (current-buffer))
27344 (fboundp org-finish-function))
27345 (funcall org-finish-function))
27346 ((org-at-property-p)
27347 (call-interactively 'org-property-action))
27348 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
27349 ((org-on-heading-p) (call-interactively 'org-set-tags))
27350 ((org-at-table.el-p)
27351 (require 'table)
27352 (beginning-of-line 1)
27353 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
27354 (call-interactively 'table-recognize-table))
27355 ((org-at-table-p)
27356 (org-table-maybe-eval-formula)
27357 (if arg
27358 (call-interactively 'org-table-recalculate)
27359 (org-table-maybe-recalculate-line))
27360 (call-interactively 'org-table-align))
27361 ((org-at-item-checkbox-p)
27362 (call-interactively 'org-toggle-checkbox))
27363 ((org-at-item-p)
27364 (call-interactively 'org-maybe-renumber-ordered-list))
27365 ((save-excursion (beginning-of-line 1) (looking-at "#\\+BEGIN:"))
27366 ;; Dynamic block
27367 (beginning-of-line 1)
27368 (org-update-dblock))
27369 ((save-excursion (beginning-of-line 1) (looking-at "#\\+\\([A-Z]+\\)"))
27370 (cond
27371 ((equal (match-string 1) "TBLFM")
27372 ;; Recalculate the table before this line
27373 (save-excursion
27374 (beginning-of-line 1)
27375 (skip-chars-backward " \r\n\t")
27376 (if (org-at-table-p)
27377 (org-call-with-arg 'org-table-recalculate t))))
27379 (call-interactively 'org-mode-restart))))
27380 (t (error "C-c C-c can do nothing useful at this location.")))))
27382 (defun org-mode-restart ()
27383 "Restart Org-mode, to scan again for special lines.
27384 Also updates the keyword regular expressions."
27385 (interactive)
27386 (let ((org-inhibit-startup t)) (org-mode))
27387 (message "Org-mode restarted to refresh keyword and special line setup"))
27389 (defun org-kill-note-or-show-branches ()
27390 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
27391 (interactive)
27392 (if (not org-finish-function)
27393 (call-interactively 'show-branches)
27394 (let ((org-note-abort t))
27395 (funcall org-finish-function))))
27397 (defun org-return (&optional indent)
27398 "Goto next table row or insert a newline.
27399 Calls `org-table-next-row' or `newline', depending on context.
27400 See the individual commands for more information."
27401 (interactive)
27402 (cond
27403 ((bobp) (if indent (newline-and-indent) (newline)))
27404 ((and (org-at-heading-p)
27405 (looking-at
27406 (org-re "\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$")))
27407 (org-show-entry)
27408 (end-of-line 1)
27409 (newline))
27410 ((org-at-table-p)
27411 (org-table-justify-field-maybe)
27412 (call-interactively 'org-table-next-row))
27413 (t (if indent (newline-and-indent) (newline)))))
27415 (defun org-return-indent ()
27416 (interactive)
27417 "Goto next table row or insert a newline and indent.
27418 Calls `org-table-next-row' or `newline-and-indent', depending on
27419 context. See the individual commands for more information."
27420 (org-return t))
27422 (defun org-ctrl-c-minus ()
27423 "Insert separator line in table or modify bullet type in list.
27424 Calls `org-table-insert-hline' or `org-cycle-list-bullet',
27425 depending on context."
27426 (interactive)
27427 (cond
27428 ((org-at-table-p)
27429 (call-interactively 'org-table-insert-hline))
27430 ((org-on-heading-p)
27431 ;; Convert to item
27432 (save-excursion
27433 (beginning-of-line 1)
27434 (if (looking-at "\\*+ ")
27435 (replace-match (concat (make-string (- (match-end 0) (point)) ?\ ) "- ")))))
27436 ((org-in-item-p)
27437 (call-interactively 'org-cycle-list-bullet))
27438 (t (error "`C-c -' does have no function here."))))
27440 (defun org-meta-return (&optional arg)
27441 "Insert a new heading or wrap a region in a table.
27442 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
27443 See the individual commands for more information."
27444 (interactive "P")
27445 (cond
27446 ((org-at-table-p)
27447 (call-interactively 'org-table-wrap-region))
27448 (t (call-interactively 'org-insert-heading))))
27450 ;;; Menu entries
27452 ;; Define the Org-mode menus
27453 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
27454 '("Tbl"
27455 ["Align" org-ctrl-c-ctrl-c (org-at-table-p)]
27456 ["Next Field" org-cycle (org-at-table-p)]
27457 ["Previous Field" org-shifttab (org-at-table-p)]
27458 ["Next Row" org-return (org-at-table-p)]
27459 "--"
27460 ["Blank Field" org-table-blank-field (org-at-table-p)]
27461 ["Edit Field" org-table-edit-field (org-at-table-p)]
27462 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
27463 "--"
27464 ("Column"
27465 ["Move Column Left" org-metaleft (org-at-table-p)]
27466 ["Move Column Right" org-metaright (org-at-table-p)]
27467 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
27468 ["Insert Column" org-shiftmetaright (org-at-table-p)])
27469 ("Row"
27470 ["Move Row Up" org-metaup (org-at-table-p)]
27471 ["Move Row Down" org-metadown (org-at-table-p)]
27472 ["Delete Row" org-shiftmetaup (org-at-table-p)]
27473 ["Insert Row" org-shiftmetadown (org-at-table-p)]
27474 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
27475 "--"
27476 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
27477 ("Rectangle"
27478 ["Copy Rectangle" org-copy-special (org-at-table-p)]
27479 ["Cut Rectangle" org-cut-special (org-at-table-p)]
27480 ["Paste Rectangle" org-paste-special (org-at-table-p)]
27481 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
27482 "--"
27483 ("Calculate"
27484 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
27485 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
27486 ["Edit Formulas" org-table-edit-formulas (org-at-table-p)]
27487 "--"
27488 ["Recalculate line" org-table-recalculate (org-at-table-p)]
27489 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
27490 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
27491 "--"
27492 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
27493 "--"
27494 ["Sum Column/Rectangle" org-table-sum
27495 (or (org-at-table-p) (org-region-active-p))]
27496 ["Which Column?" org-table-current-column (org-at-table-p)])
27497 ["Debug Formulas"
27498 org-table-toggle-formula-debugger
27499 :style toggle :selected org-table-formula-debug]
27500 ["Show Col/Row Numbers"
27501 org-table-toggle-coordinate-overlays
27502 :style toggle :selected org-table-overlay-coordinates]
27503 "--"
27504 ["Create" org-table-create (and (not (org-at-table-p))
27505 org-enable-table-editor)]
27506 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
27507 ["Import from File" org-table-import (not (org-at-table-p))]
27508 ["Export to File" org-table-export (org-at-table-p)]
27509 "--"
27510 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
27512 (easy-menu-define org-org-menu org-mode-map "Org menu"
27513 '("Org"
27514 ("Show/Hide"
27515 ["Cycle Visibility" org-cycle (or (bobp) (outline-on-heading-p))]
27516 ["Cycle Global Visibility" org-shifttab (not (org-at-table-p))]
27517 ["Sparse Tree" org-occur t]
27518 ["Reveal Context" org-reveal t]
27519 ["Show All" show-all t]
27520 "--"
27521 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
27522 "--"
27523 ["New Heading" org-insert-heading t]
27524 ("Navigate Headings"
27525 ["Up" outline-up-heading t]
27526 ["Next" outline-next-visible-heading t]
27527 ["Previous" outline-previous-visible-heading t]
27528 ["Next Same Level" outline-forward-same-level t]
27529 ["Previous Same Level" outline-backward-same-level t]
27530 "--"
27531 ["Jump" org-goto t])
27532 ("Edit Structure"
27533 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
27534 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
27535 "--"
27536 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
27537 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
27538 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
27539 "--"
27540 ["Promote Heading" org-metaleft (not (org-at-table-p))]
27541 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
27542 ["Demote Heading" org-metaright (not (org-at-table-p))]
27543 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
27544 "--"
27545 ["Sort Region/Children" org-sort (not (org-at-table-p))]
27546 "--"
27547 ["Convert to odd levels" org-convert-to-odd-levels t]
27548 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
27549 ("Editing"
27550 ["Emphasis..." org-emphasize t])
27551 ("Archive"
27552 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
27553 ; ["Check and Tag Children" (org-toggle-archive-tag (4))
27554 ; :active t :keys "C-u C-c C-x C-a"]
27555 ["Sparse trees open ARCHIVE trees"
27556 (setq org-sparse-tree-open-archived-trees
27557 (not org-sparse-tree-open-archived-trees))
27558 :style toggle :selected org-sparse-tree-open-archived-trees]
27559 ["Cycling opens ARCHIVE trees"
27560 (setq org-cycle-open-archived-trees (not org-cycle-open-archived-trees))
27561 :style toggle :selected org-cycle-open-archived-trees]
27562 ["Agenda includes ARCHIVE trees"
27563 (setq org-agenda-skip-archived-trees (not org-agenda-skip-archived-trees))
27564 :style toggle :selected (not org-agenda-skip-archived-trees)]
27565 "--"
27566 ["Move Subtree to Archive" org-advertized-archive-subtree t]
27567 ; ["Check and Move Children" (org-archive-subtree '(4))
27568 ; :active t :keys "C-u C-c C-x C-s"]
27570 "--"
27571 ("TODO Lists"
27572 ["TODO/DONE/-" org-todo t]
27573 ("Select keyword"
27574 ["Next keyword" org-shiftright (org-on-heading-p)]
27575 ["Previous keyword" org-shiftleft (org-on-heading-p)]
27576 ["Complete Keyword" org-complete (assq :todo-keyword (org-context))]
27577 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))]
27578 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))])
27579 ["Show TODO Tree" org-show-todo-tree t]
27580 ["Global TODO list" org-todo-list t]
27581 "--"
27582 ["Set Priority" org-priority t]
27583 ["Priority Up" org-shiftup t]
27584 ["Priority Down" org-shiftdown t])
27585 ("TAGS and Properties"
27586 ["Set Tags" 'org-ctrl-c-ctrl-c (org-at-heading-p)]
27587 ["Change tag in region" 'org-change-tag-in-region (org-region-active-p)]
27588 "--"
27589 ["Set property" 'org-set-property t]
27590 ["Column view of properties" org-columns t]
27591 ["Insert Column View DBlock" org-insert-columns-dblock t])
27592 ("Dates and Scheduling"
27593 ["Timestamp" org-time-stamp t]
27594 ["Timestamp (inactive)" org-time-stamp-inactive t]
27595 ("Change Date"
27596 ["1 Day Later" org-shiftright t]
27597 ["1 Day Earlier" org-shiftleft t]
27598 ["1 ... Later" org-shiftup t]
27599 ["1 ... Earlier" org-shiftdown t])
27600 ["Compute Time Range" org-evaluate-time-range t]
27601 ["Schedule Item" org-schedule t]
27602 ["Deadline" org-deadline t]
27603 "--"
27604 ["Custom time format" org-toggle-time-stamp-overlays
27605 :style radio :selected org-display-custom-times]
27606 "--"
27607 ["Goto Calendar" org-goto-calendar t]
27608 ["Date from Calendar" org-date-from-calendar t])
27609 ("Logging work"
27610 ["Clock in" org-clock-in t]
27611 ["Clock out" org-clock-out t]
27612 ["Clock cancel" org-clock-cancel t]
27613 ["Goto running clock" org-clock-goto t]
27614 ["Display times" org-clock-display t]
27615 ["Create clock table" org-clock-report t]
27616 "--"
27617 ["Record DONE time"
27618 (progn (setq org-log-done (not org-log-done))
27619 (message "Switching to %s will %s record a timestamp"
27620 (car org-done-keywords)
27621 (if org-log-done "automatically" "not")))
27622 :style toggle :selected org-log-done])
27623 "--"
27624 ["Agenda Command..." org-agenda t]
27625 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
27626 ("File List for Agenda")
27627 ("Special views current file"
27628 ["TODO Tree" org-show-todo-tree t]
27629 ["Check Deadlines" org-check-deadlines t]
27630 ["Timeline" org-timeline t]
27631 ["Tags Tree" org-tags-sparse-tree t])
27632 "--"
27633 ("Hyperlinks"
27634 ["Store Link (Global)" org-store-link t]
27635 ["Insert Link" org-insert-link t]
27636 ["Follow Link" org-open-at-point t]
27637 "--"
27638 ["Next link" org-next-link t]
27639 ["Previous link" org-previous-link t]
27640 "--"
27641 ["Descriptive Links"
27642 (progn (org-add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
27643 :style radio :selected (member '(org-link) buffer-invisibility-spec)]
27644 ["Literal Links"
27645 (progn
27646 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
27647 :style radio :selected (not (member '(org-link) buffer-invisibility-spec))])
27648 "--"
27649 ["Export/Publish..." org-export t]
27650 ("LaTeX"
27651 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
27652 :selected org-cdlatex-mode]
27653 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
27654 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
27655 ["Modify math symbol" org-cdlatex-math-modify
27656 (org-inside-LaTeX-fragment-p)]
27657 ["Export LaTeX fragments as images"
27658 (setq org-export-with-LaTeX-fragments (not org-export-with-LaTeX-fragments))
27659 :style toggle :selected org-export-with-LaTeX-fragments])
27660 "--"
27661 ("Documentation"
27662 ["Show Version" org-version t]
27663 ["Info Documentation" org-info t])
27664 ("Customize"
27665 ["Browse Org Group" org-customize t]
27666 "--"
27667 ["Expand This Menu" org-create-customize-menu
27668 (fboundp 'customize-menu-create)])
27669 "--"
27670 ["Refresh setup" org-mode-restart t]
27673 (defun org-info (&optional node)
27674 "Read documentation for Org-mode in the info system.
27675 With optional NODE, go directly to that node."
27676 (interactive)
27677 (require 'info)
27678 (Info-goto-node (format "(org)%s" (or node ""))))
27680 (defun org-install-agenda-files-menu ()
27681 (let ((bl (buffer-list)))
27682 (save-excursion
27683 (while bl
27684 (set-buffer (pop bl))
27685 (if (org-mode-p) (setq bl nil)))
27686 (when (org-mode-p)
27687 (easy-menu-change
27688 '("Org") "File List for Agenda"
27689 (append
27690 (list
27691 ["Edit File List" (org-edit-agenda-file-list) t]
27692 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
27693 ["Remove Current File from List" org-remove-file t]
27694 ["Cycle through agenda files" org-cycle-agenda-files t]
27695 ["Occur in all agenda files" org-occur-in-agenda-files t]
27696 "--")
27697 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
27699 ;;;; Documentation
27701 (defun org-customize ()
27702 "Call the customize function with org as argument."
27703 (interactive)
27704 (customize-browse 'org))
27706 (defun org-create-customize-menu ()
27707 "Create a full customization menu for Org-mode, insert it into the menu."
27708 (interactive)
27709 (if (fboundp 'customize-menu-create)
27710 (progn
27711 (easy-menu-change
27712 '("Org") "Customize"
27713 `(["Browse Org group" org-customize t]
27714 "--"
27715 ,(customize-menu-create 'org)
27716 ["Set" Custom-set t]
27717 ["Save" Custom-save t]
27718 ["Reset to Current" Custom-reset-current t]
27719 ["Reset to Saved" Custom-reset-saved t]
27720 ["Reset to Standard Settings" Custom-reset-standard t]))
27721 (message "\"Org\"-menu now contains full customization menu"))
27722 (error "Cannot expand menu (outdated version of cus-edit.el)")))
27724 ;;;; Miscellaneous stuff
27727 ;;; Generally useful functions
27729 (defun org-context ()
27730 "Return a list of contexts of the current cursor position.
27731 If several contexts apply, all are returned.
27732 Each context entry is a list with a symbol naming the context, and
27733 two positions indicating start and end of the context. Possible
27734 contexts are:
27736 :headline anywhere in a headline
27737 :headline-stars on the leading stars in a headline
27738 :todo-keyword on a TODO keyword (including DONE) in a headline
27739 :tags on the TAGS in a headline
27740 :priority on the priority cookie in a headline
27741 :item on the first line of a plain list item
27742 :item-bullet on the bullet/number of a plain list item
27743 :checkbox on the checkbox in a plain list item
27744 :table in an org-mode table
27745 :table-special on a special filed in a table
27746 :table-table in a table.el table
27747 :link on a hyperlink
27748 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
27749 :target on a <<target>>
27750 :radio-target on a <<<radio-target>>>
27751 :latex-fragment on a LaTeX fragment
27752 :latex-preview on a LaTeX fragment with overlayed preview image
27754 This function expects the position to be visible because it uses font-lock
27755 faces as a help to recognize the following contexts: :table-special, :link,
27756 and :keyword."
27757 (let* ((f (get-text-property (point) 'face))
27758 (faces (if (listp f) f (list f)))
27759 (p (point)) clist o)
27760 ;; First the large context
27761 (cond
27762 ((org-on-heading-p t)
27763 (push (list :headline (point-at-bol) (point-at-eol)) clist)
27764 (when (progn
27765 (beginning-of-line 1)
27766 (looking-at org-todo-line-tags-regexp))
27767 (push (org-point-in-group p 1 :headline-stars) clist)
27768 (push (org-point-in-group p 2 :todo-keyword) clist)
27769 (push (org-point-in-group p 4 :tags) clist))
27770 (goto-char p)
27771 (skip-chars-backward "^[\n\r \t") (or (eobp) (backward-char 1))
27772 (if (looking-at "\\[#[A-Z0-9]\\]")
27773 (push (org-point-in-group p 0 :priority) clist)))
27775 ((org-at-item-p)
27776 (push (org-point-in-group p 2 :item-bullet) clist)
27777 (push (list :item (point-at-bol)
27778 (save-excursion (org-end-of-item) (point)))
27779 clist)
27780 (and (org-at-item-checkbox-p)
27781 (push (org-point-in-group p 0 :checkbox) clist)))
27783 ((org-at-table-p)
27784 (push (list :table (org-table-begin) (org-table-end)) clist)
27785 (if (memq 'org-formula faces)
27786 (push (list :table-special
27787 (previous-single-property-change p 'face)
27788 (next-single-property-change p 'face)) clist)))
27789 ((org-at-table-p 'any)
27790 (push (list :table-table) clist)))
27791 (goto-char p)
27793 ;; Now the small context
27794 (cond
27795 ((org-at-timestamp-p)
27796 (push (org-point-in-group p 0 :timestamp) clist))
27797 ((memq 'org-link faces)
27798 (push (list :link
27799 (previous-single-property-change p 'face)
27800 (next-single-property-change p 'face)) clist))
27801 ((memq 'org-special-keyword faces)
27802 (push (list :keyword
27803 (previous-single-property-change p 'face)
27804 (next-single-property-change p 'face)) clist))
27805 ((org-on-target-p)
27806 (push (org-point-in-group p 0 :target) clist)
27807 (goto-char (1- (match-beginning 0)))
27808 (if (looking-at org-radio-target-regexp)
27809 (push (org-point-in-group p 0 :radio-target) clist))
27810 (goto-char p))
27811 ((setq o (car (delq nil
27812 (mapcar
27813 (lambda (x)
27814 (if (memq x org-latex-fragment-image-overlays) x))
27815 (org-overlays-at (point))))))
27816 (push (list :latex-fragment
27817 (org-overlay-start o) (org-overlay-end o)) clist)
27818 (push (list :latex-preview
27819 (org-overlay-start o) (org-overlay-end o)) clist))
27820 ((org-inside-LaTeX-fragment-p)
27821 ;; FIXME: positions wrong.
27822 (push (list :latex-fragment (point) (point)) clist)))
27824 (setq clist (nreverse (delq nil clist)))
27825 clist))
27827 ;; FIXME: Compare with at-regexp-p Do we need both?
27828 (defun org-in-regexp (re &optional nlines visually)
27829 "Check if point is inside a match of regexp.
27830 Normally only the current line is checked, but you can include NLINES extra
27831 lines both before and after point into the search.
27832 If VISUALLY is set, require that the cursor is not after the match but
27833 really on, so that the block visually is on the match."
27834 (catch 'exit
27835 (let ((pos (point))
27836 (eol (point-at-eol (+ 1 (or nlines 0))))
27837 (inc (if visually 1 0)))
27838 (save-excursion
27839 (beginning-of-line (- 1 (or nlines 0)))
27840 (while (re-search-forward re eol t)
27841 (if (and (<= (match-beginning 0) pos)
27842 (>= (+ inc (match-end 0)) pos))
27843 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
27845 (defun org-at-regexp-p (regexp)
27846 "Is point inside a match of REGEXP in the current line?"
27847 (catch 'exit
27848 (save-excursion
27849 (let ((pos (point)) (end (point-at-eol)))
27850 (beginning-of-line 1)
27851 (while (re-search-forward regexp end t)
27852 (if (and (<= (match-beginning 0) pos)
27853 (>= (match-end 0) pos))
27854 (throw 'exit t)))
27855 nil))))
27857 (defun org-occur-in-agenda-files (regexp &optional nlines)
27858 "Call `multi-occur' with buffers for all agenda files."
27859 (interactive "sOrg-files matching: \np")
27860 (let* ((files (org-agenda-files))
27861 (tnames (mapcar 'file-truename files))
27862 (extra org-agenda-text-search-extra-files)
27864 (while (setq f (pop extra))
27865 (unless (member (file-truename f) tnames)
27866 (add-to-list 'files f 'append)
27867 (add-to-list 'tnames (file-truename f) 'append)))
27868 (multi-occur
27869 (mapcar (lambda (x) (or (get-file-buffer x) (find-file-noselect x))) files)
27870 regexp)))
27872 (if (boundp 'occur-mode-find-occurrence-hook)
27873 ;; Emacs 23
27874 (add-hook 'occur-mode-find-occurrence-hook
27875 (lambda ()
27876 (when (org-mode-p)
27877 (org-reveal))))
27878 ;; Emacs 22
27879 (defadvice occur-mode-goto-occurrence
27880 (after org-occur-reveal activate)
27881 (and (org-mode-p) (org-reveal)))
27882 (defadvice occur-mode-goto-occurrence-other-window
27883 (after org-occur-reveal activate)
27884 (and (org-mode-p) (org-reveal)))
27885 (defadvice occur-mode-display-occurrence
27886 (after org-occur-reveal activate)
27887 (when (org-mode-p)
27888 (let ((pos (occur-mode-find-occurrence)))
27889 (with-current-buffer (marker-buffer pos)
27890 (save-excursion
27891 (goto-char pos)
27892 (org-reveal)))))))
27894 (defun org-uniquify (list)
27895 "Remove duplicate elements from LIST."
27896 (let (res)
27897 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
27898 res))
27900 (defun org-delete-all (elts list)
27901 "Remove all elements in ELTS from LIST."
27902 (while elts
27903 (setq list (delete (pop elts) list)))
27904 list)
27906 (defun org-back-over-empty-lines ()
27907 "Move backwards over witespace, to the beginning of the first empty line.
27908 Returns the number o empty lines passed."
27909 (let ((pos (point)))
27910 (skip-chars-backward " \t\n\r")
27911 (beginning-of-line 2)
27912 (goto-char (min (point) pos))
27913 (count-lines (point) pos)))
27915 (defun org-skip-whitespace ()
27916 (skip-chars-forward " \t\n\r"))
27918 (defun org-point-in-group (point group &optional context)
27919 "Check if POINT is in match-group GROUP.
27920 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
27921 match. If the match group does ot exist or point is not inside it,
27922 return nil."
27923 (and (match-beginning group)
27924 (>= point (match-beginning group))
27925 (<= point (match-end group))
27926 (if context
27927 (list context (match-beginning group) (match-end group))
27928 t)))
27930 (defun org-switch-to-buffer-other-window (&rest args)
27931 "Switch to buffer in a second window on the current frame.
27932 In particular, do not allow pop-up frames."
27933 (let (pop-up-frames special-display-buffer-names special-display-regexps
27934 special-display-function)
27935 (apply 'switch-to-buffer-other-window args)))
27937 (defun org-combine-plists (&rest plists)
27938 "Create a single property list from all plists in PLISTS.
27939 The process starts by copying the first list, and then setting properties
27940 from the other lists. Settings in the last list are the most significant
27941 ones and overrule settings in the other lists."
27942 (let ((rtn (copy-sequence (pop plists)))
27943 p v ls)
27944 (while plists
27945 (setq ls (pop plists))
27946 (while ls
27947 (setq p (pop ls) v (pop ls))
27948 (setq rtn (plist-put rtn p v))))
27949 rtn))
27951 (defun org-move-line-down (arg)
27952 "Move the current line down. With prefix argument, move it past ARG lines."
27953 (interactive "p")
27954 (let ((col (current-column))
27955 beg end pos)
27956 (beginning-of-line 1) (setq beg (point))
27957 (beginning-of-line 2) (setq end (point))
27958 (beginning-of-line (+ 1 arg))
27959 (setq pos (move-marker (make-marker) (point)))
27960 (insert (delete-and-extract-region beg end))
27961 (goto-char pos)
27962 (move-to-column col)))
27964 (defun org-move-line-up (arg)
27965 "Move the current line up. With prefix argument, move it past ARG lines."
27966 (interactive "p")
27967 (let ((col (current-column))
27968 beg end pos)
27969 (beginning-of-line 1) (setq beg (point))
27970 (beginning-of-line 2) (setq end (point))
27971 (beginning-of-line (- arg))
27972 (setq pos (move-marker (make-marker) (point)))
27973 (insert (delete-and-extract-region beg end))
27974 (goto-char pos)
27975 (move-to-column col)))
27977 (defun org-replace-escapes (string table)
27978 "Replace %-escapes in STRING with values in TABLE.
27979 TABLE is an association list with keys like \"%a\" and string values.
27980 The sequences in STRING may contain normal field width and padding information,
27981 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
27982 so values can contain further %-escapes if they are define later in TABLE."
27983 (let ((case-fold-search nil)
27984 e re rpl)
27985 (while (setq e (pop table))
27986 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
27987 (while (string-match re string)
27988 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
27989 (cdr e)))
27990 (setq string (replace-match rpl t t string))))
27991 string))
27994 (defun org-sublist (list start end)
27995 "Return a section of LIST, from START to END.
27996 Counting starts at 1."
27997 (let (rtn (c start))
27998 (setq list (nthcdr (1- start) list))
27999 (while (and list (<= c end))
28000 (push (pop list) rtn)
28001 (setq c (1+ c)))
28002 (nreverse rtn)))
28004 (defun org-find-base-buffer-visiting (file)
28005 "Like `find-buffer-visiting' but alway return the base buffer and
28006 not an indirect buffer"
28007 (let ((buf (find-buffer-visiting file)))
28008 (if buf
28009 (or (buffer-base-buffer buf) buf)
28010 nil)))
28012 (defun org-image-file-name-regexp ()
28013 "Return regexp matching the file names of images."
28014 (if (fboundp 'image-file-name-regexp)
28015 (image-file-name-regexp)
28016 (let ((image-file-name-extensions
28017 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
28018 "xbm" "xpm" "pbm" "pgm" "ppm")))
28019 (concat "\\."
28020 (regexp-opt (nconc (mapcar 'upcase
28021 image-file-name-extensions)
28022 image-file-name-extensions)
28024 "\\'"))))
28026 (defun org-file-image-p (file)
28027 "Return non-nil if FILE is an image."
28028 (save-match-data
28029 (string-match (org-image-file-name-regexp) file)))
28031 ;;; Paragraph filling stuff.
28032 ;; We want this to be just right, so use the full arsenal.
28034 (defun org-indent-line-function ()
28035 "Indent line like previous, but further if previous was headline or item."
28036 (interactive)
28037 (let* ((pos (point))
28038 (itemp (org-at-item-p))
28039 column bpos bcol tpos tcol bullet btype bullet-type)
28040 ;; Find the previous relevant line
28041 (beginning-of-line 1)
28042 (cond
28043 ((looking-at "#") (setq column 0))
28044 ((looking-at "\\*+ ") (setq column 0))
28046 (beginning-of-line 0)
28047 (while (and (not (bobp)) (looking-at "[ \t]*[\n:#|]"))
28048 (beginning-of-line 0))
28049 (cond
28050 ((looking-at "\\*+[ \t]+")
28051 (goto-char (match-end 0))
28052 (setq column (current-column)))
28053 ((org-in-item-p)
28054 (org-beginning-of-item)
28055 ; (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
28056 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*\\(\\[[- X]\\][ \t]*\\)?")
28057 (setq bpos (match-beginning 1) tpos (match-end 0)
28058 bcol (progn (goto-char bpos) (current-column))
28059 tcol (progn (goto-char tpos) (current-column))
28060 bullet (match-string 1)
28061 bullet-type (if (string-match "[0-9]" bullet) "n" bullet))
28062 (if (not itemp)
28063 (setq column tcol)
28064 (goto-char pos)
28065 (beginning-of-line 1)
28066 (if (looking-at "\\S-")
28067 (progn
28068 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
28069 (setq bullet (match-string 1)
28070 btype (if (string-match "[0-9]" bullet) "n" bullet))
28071 (setq column (if (equal btype bullet-type) bcol tcol)))
28072 (setq column (org-get-indentation)))))
28073 (t (setq column (org-get-indentation))))))
28074 (goto-char pos)
28075 (if (<= (current-column) (current-indentation))
28076 (indent-line-to column)
28077 (save-excursion (indent-line-to column)))
28078 (setq column (current-column))
28079 (beginning-of-line 1)
28080 (if (looking-at
28081 "\\([ \t]+\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
28082 (replace-match (concat "\\1" (format org-property-format
28083 (match-string 2) (match-string 3)))
28084 t nil))
28085 (move-to-column column)))
28087 (defun org-set-autofill-regexps ()
28088 (interactive)
28089 ;; In the paragraph separator we include headlines, because filling
28090 ;; text in a line directly attached to a headline would otherwise
28091 ;; fill the headline as well.
28092 (org-set-local 'comment-start-skip "^#+[ \t]*")
28093 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|]")
28094 ;; The paragraph starter includes hand-formatted lists.
28095 (org-set-local 'paragraph-start
28096 "\f\\|[ ]*$\\|\\*+ \\|\f\\|[ \t]*\\([-+*][ \t]+\\|[0-9]+[.)][ \t]+\\)\\|[ \t]*[:|]")
28097 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
28098 ;; But only if the user has not turned off tables or fixed-width regions
28099 (org-set-local
28100 'auto-fill-inhibit-regexp
28101 (concat "\\*+ \\|#\\+"
28102 "\\|[ \t]*" org-keyword-time-regexp
28103 (if (or org-enable-table-editor org-enable-fixed-width-editor)
28104 (concat
28105 "\\|[ \t]*["
28106 (if org-enable-table-editor "|" "")
28107 (if org-enable-fixed-width-editor ":" "")
28108 "]"))))
28109 ;; We use our own fill-paragraph function, to make sure that tables
28110 ;; and fixed-width regions are not wrapped. That function will pass
28111 ;; through to `fill-paragraph' when appropriate.
28112 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
28113 ; Adaptive filling: To get full control, first make sure that
28114 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
28115 (org-set-local 'adaptive-fill-regexp "\000")
28116 (org-set-local 'adaptive-fill-function
28117 'org-adaptive-fill-function)
28118 (org-set-local
28119 'align-mode-rules-list
28120 '((org-in-buffer-settings
28121 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
28122 (modes . '(org-mode))))))
28124 (defun org-fill-paragraph (&optional justify)
28125 "Re-align a table, pass through to fill-paragraph if no table."
28126 (let ((table-p (org-at-table-p))
28127 (table.el-p (org-at-table.el-p)))
28128 (cond ((and (equal (char-after (point-at-bol)) ?*)
28129 (save-excursion (goto-char (point-at-bol))
28130 (looking-at outline-regexp)))
28131 t) ; skip headlines
28132 (table.el-p t) ; skip table.el tables
28133 (table-p (org-table-align) t) ; align org-mode tables
28134 (t nil)))) ; call paragraph-fill
28136 ;; For reference, this is the default value of adaptive-fill-regexp
28137 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
28139 (defun org-adaptive-fill-function ()
28140 "Return a fill prefix for org-mode files.
28141 In particular, this makes sure hanging paragraphs for hand-formatted lists
28142 work correctly."
28143 (cond ((looking-at "#[ \t]+")
28144 (match-string 0))
28145 ((looking-at "[ \t]*\\([-*+] \\|[0-9]+[.)] \\)?")
28146 (save-excursion
28147 (goto-char (match-end 0))
28148 (make-string (current-column) ?\ )))
28149 (t nil)))
28151 ;;;; Functions extending outline functionality
28154 (defun org-beginning-of-line (&optional arg)
28155 "Go to the beginning of the current line. If that is invisible, continue
28156 to a visible line beginning. This makes the function of C-a more intuitive.
28157 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
28158 first attempt, and only move to after the tags when the cursor is already
28159 beyond the end of the headline."
28160 (interactive "P")
28161 (let ((pos (point)))
28162 (beginning-of-line 1)
28163 (if (bobp)
28165 (backward-char 1)
28166 (if (org-invisible-p)
28167 (while (and (not (bobp)) (org-invisible-p))
28168 (backward-char 1)
28169 (beginning-of-line 1))
28170 (forward-char 1)))
28171 (when org-special-ctrl-a/e
28172 (cond
28173 ((and (looking-at org-todo-line-regexp)
28174 (= (char-after (match-end 1)) ?\ ))
28175 (goto-char
28176 (if (eq org-special-ctrl-a/e t)
28177 (cond ((> pos (match-beginning 3)) (match-beginning 3))
28178 ((= pos (point)) (match-beginning 3))
28179 (t (point)))
28180 (cond ((> pos (point)) (point))
28181 ((not (eq last-command this-command)) (point))
28182 (t (match-beginning 3))))))
28183 ((org-at-item-p)
28184 (goto-char
28185 (if (eq org-special-ctrl-a/e t)
28186 (cond ((> pos (match-end 4)) (match-end 4))
28187 ((= pos (point)) (match-end 4))
28188 (t (point)))
28189 (cond ((> pos (point)) (point))
28190 ((not (eq last-command this-command)) (point))
28191 (t (match-end 4))))))))))
28193 (defun org-end-of-line (&optional arg)
28194 "Go to the end of the line.
28195 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
28196 first attempt, and only move to after the tags when the cursor is already
28197 beyond the end of the headline."
28198 (interactive "P")
28199 (if (or (not org-special-ctrl-a/e)
28200 (not (org-on-heading-p)))
28201 (end-of-line arg)
28202 (let ((pos (point)))
28203 (beginning-of-line 1)
28204 (if (looking-at (org-re ".*?\\([ \t]*\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
28205 (if (eq org-special-ctrl-a/e t)
28206 (if (or (< pos (match-beginning 1))
28207 (= pos (match-end 0)))
28208 (goto-char (match-beginning 1))
28209 (goto-char (match-end 0)))
28210 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
28211 (goto-char (match-end 0))
28212 (goto-char (match-beginning 1))))
28213 (end-of-line arg)))))
28215 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
28216 (define-key org-mode-map "\C-e" 'org-end-of-line)
28218 (defun org-kill-line (&optional arg)
28219 "Kill line, to tags or end of line."
28220 (interactive "P")
28221 (cond
28222 ((or (not org-special-ctrl-k)
28223 (bolp)
28224 (not (org-on-heading-p)))
28225 (call-interactively 'kill-line))
28226 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$"))
28227 (kill-region (point) (match-beginning 1))
28228 (org-set-tags nil t))
28229 (t (kill-region (point) (point-at-eol)))))
28231 (define-key org-mode-map "\C-k" 'org-kill-line)
28233 (defun org-invisible-p ()
28234 "Check if point is at a character currently not visible."
28235 ;; Early versions of noutline don't have `outline-invisible-p'.
28236 (if (fboundp 'outline-invisible-p)
28237 (outline-invisible-p)
28238 (get-char-property (point) 'invisible)))
28240 (defun org-invisible-p2 ()
28241 "Check if point is at a character currently not visible."
28242 (save-excursion
28243 (if (and (eolp) (not (bobp))) (backward-char 1))
28244 ;; Early versions of noutline don't have `outline-invisible-p'.
28245 (if (fboundp 'outline-invisible-p)
28246 (outline-invisible-p)
28247 (get-char-property (point) 'invisible))))
28249 (defalias 'org-back-to-heading 'outline-back-to-heading)
28250 (defalias 'org-on-heading-p 'outline-on-heading-p)
28251 (defalias 'org-at-heading-p 'outline-on-heading-p)
28252 (defun org-at-heading-or-item-p ()
28253 (or (org-on-heading-p) (org-at-item-p)))
28255 (defun org-on-target-p ()
28256 (or (org-in-regexp org-radio-target-regexp)
28257 (org-in-regexp org-target-regexp)))
28259 (defun org-up-heading-all (arg)
28260 "Move to the heading line of which the present line is a subheading.
28261 This function considers both visible and invisible heading lines.
28262 With argument, move up ARG levels."
28263 (if (fboundp 'outline-up-heading-all)
28264 (outline-up-heading-all arg) ; emacs 21 version of outline.el
28265 (outline-up-heading arg t))) ; emacs 22 version of outline.el
28267 (defun org-up-heading-safe ()
28268 "Move to the heading line of which the present line is a subheading.
28269 This version will not throw an error. It will return the level of the
28270 headline found, or nil if no higher level is found."
28271 (let ((pos (point)) start-level level
28272 (re (concat "^" outline-regexp)))
28273 (catch 'exit
28274 (outline-back-to-heading t)
28275 (setq start-level (funcall outline-level))
28276 (if (equal start-level 1) (throw 'exit nil))
28277 (while (re-search-backward re nil t)
28278 (setq level (funcall outline-level))
28279 (if (< level start-level) (throw 'exit level)))
28280 nil)))
28282 (defun org-first-sibling-p ()
28283 "Is this heading the first child of its parents?"
28284 (interactive)
28285 (let ((re (concat "^" outline-regexp))
28286 level l)
28287 (unless (org-at-heading-p t)
28288 (error "Not at a heading"))
28289 (setq level (funcall outline-level))
28290 (save-excursion
28291 (if (not (re-search-backward re nil t))
28293 (setq l (funcall outline-level))
28294 (< l level)))))
28296 (defun org-goto-sibling (&optional previous)
28297 "Goto the next sibling, even if it is invisible.
28298 When PREVIOUS is set, go to the previous sibling instead. Returns t
28299 when a sibling was found. When none is found, return nil and don't
28300 move point."
28301 (let ((fun (if previous 're-search-backward 're-search-forward))
28302 (pos (point))
28303 (re (concat "^" outline-regexp))
28304 level l)
28305 (when (condition-case nil (org-back-to-heading t) (error nil))
28306 (setq level (funcall outline-level))
28307 (catch 'exit
28308 (or previous (forward-char 1))
28309 (while (funcall fun re nil t)
28310 (setq l (funcall outline-level))
28311 (when (< l level) (goto-char pos) (throw 'exit nil))
28312 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
28313 (goto-char pos)
28314 nil))))
28316 (defun org-show-siblings ()
28317 "Show all siblings of the current headline."
28318 (save-excursion
28319 (while (org-goto-sibling) (org-flag-heading nil)))
28320 (save-excursion
28321 (while (org-goto-sibling 'previous)
28322 (org-flag-heading nil))))
28324 (defun org-show-hidden-entry ()
28325 "Show an entry where even the heading is hidden."
28326 (save-excursion
28327 (org-show-entry)))
28329 (defun org-flag-heading (flag &optional entry)
28330 "Flag the current heading. FLAG non-nil means make invisible.
28331 When ENTRY is non-nil, show the entire entry."
28332 (save-excursion
28333 (org-back-to-heading t)
28334 ;; Check if we should show the entire entry
28335 (if entry
28336 (progn
28337 (org-show-entry)
28338 (save-excursion
28339 (and (outline-next-heading)
28340 (org-flag-heading nil))))
28341 (outline-flag-region (max (point-min) (1- (point)))
28342 (save-excursion (outline-end-of-heading) (point))
28343 flag))))
28345 (defun org-end-of-subtree (&optional invisible-OK to-heading)
28346 ;; This is an exact copy of the original function, but it uses
28347 ;; `org-back-to-heading', to make it work also in invisible
28348 ;; trees. And is uses an invisible-OK argument.
28349 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
28350 (org-back-to-heading invisible-OK)
28351 (let ((first t)
28352 (level (funcall outline-level)))
28353 (while (and (not (eobp))
28354 (or first (> (funcall outline-level) level)))
28355 (setq first nil)
28356 (outline-next-heading))
28357 (unless to-heading
28358 (if (memq (preceding-char) '(?\n ?\^M))
28359 (progn
28360 ;; Go to end of line before heading
28361 (forward-char -1)
28362 (if (memq (preceding-char) '(?\n ?\^M))
28363 ;; leave blank line before heading
28364 (forward-char -1))))))
28365 (point))
28367 (defun org-show-subtree ()
28368 "Show everything after this heading at deeper levels."
28369 (outline-flag-region
28370 (point)
28371 (save-excursion
28372 (outline-end-of-subtree) (outline-next-heading) (point))
28373 nil))
28375 (defun org-show-entry ()
28376 "Show the body directly following this heading.
28377 Show the heading too, if it is currently invisible."
28378 (interactive)
28379 (save-excursion
28380 (condition-case nil
28381 (progn
28382 (org-back-to-heading t)
28383 (outline-flag-region
28384 (max (point-min) (1- (point)))
28385 (save-excursion
28386 (re-search-forward
28387 (concat "[\r\n]\\(" outline-regexp "\\)") nil 'move)
28388 (or (match-beginning 1) (point-max)))
28389 nil))
28390 (error nil))))
28392 (defun org-make-options-regexp (kwds)
28393 "Make a regular expression for keyword lines."
28394 (concat
28396 "#?[ \t]*\\+\\("
28397 (mapconcat 'regexp-quote kwds "\\|")
28398 "\\):[ \t]*"
28399 "\\(.+\\)"))
28401 ;; Make isearch reveal the necessary context
28402 (defun org-isearch-end ()
28403 "Reveal context after isearch exits."
28404 (when isearch-success ; only if search was successful
28405 (if (featurep 'xemacs)
28406 ;; Under XEmacs, the hook is run in the correct place,
28407 ;; we directly show the context.
28408 (org-show-context 'isearch)
28409 ;; In Emacs the hook runs *before* restoring the overlays.
28410 ;; So we have to use a one-time post-command-hook to do this.
28411 ;; (Emacs 22 has a special variable, see function `org-mode')
28412 (unless (and (boundp 'isearch-mode-end-hook-quit)
28413 isearch-mode-end-hook-quit)
28414 ;; Only when the isearch was not quitted.
28415 (org-add-hook 'post-command-hook 'org-isearch-post-command
28416 'append 'local)))))
28418 (defun org-isearch-post-command ()
28419 "Remove self from hook, and show context."
28420 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
28421 (org-show-context 'isearch))
28424 ;;;; Integration with and fixes for other packages
28426 ;;; Imenu support
28428 (defvar org-imenu-markers nil
28429 "All markers currently used by Imenu.")
28430 (make-variable-buffer-local 'org-imenu-markers)
28432 (defun org-imenu-new-marker (&optional pos)
28433 "Return a new marker for use by Imenu, and remember the marker."
28434 (let ((m (make-marker)))
28435 (move-marker m (or pos (point)))
28436 (push m org-imenu-markers)
28439 (defun org-imenu-get-tree ()
28440 "Produce the index for Imenu."
28441 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
28442 (setq org-imenu-markers nil)
28443 (let* ((n org-imenu-depth)
28444 (re (concat "^" outline-regexp))
28445 (subs (make-vector (1+ n) nil))
28446 (last-level 0)
28447 m tree level head)
28448 (save-excursion
28449 (save-restriction
28450 (widen)
28451 (goto-char (point-max))
28452 (while (re-search-backward re nil t)
28453 (setq level (org-reduced-level (funcall outline-level)))
28454 (when (<= level n)
28455 (looking-at org-complex-heading-regexp)
28456 (setq head (org-match-string-no-properties 4)
28457 m (org-imenu-new-marker))
28458 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
28459 (if (>= level last-level)
28460 (push (cons head m) (aref subs level))
28461 (push (cons head (aref subs (1+ level))) (aref subs level))
28462 (loop for i from (1+ level) to n do (aset subs i nil)))
28463 (setq last-level level)))))
28464 (aref subs 1)))
28466 (eval-after-load "imenu"
28467 '(progn
28468 (add-hook 'imenu-after-jump-hook
28469 (lambda () (org-show-context 'org-goto)))))
28471 ;; Speedbar support
28473 (defun org-speedbar-set-agenda-restriction ()
28474 "Restrict future agenda commands to the location at point in speedbar.
28475 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
28476 (interactive)
28477 (let (p m tp np dir txt w)
28478 (cond
28479 ((setq p (text-property-any (point-at-bol) (point-at-eol)
28480 'org-imenu t))
28481 (setq m (get-text-property p 'org-imenu-marker))
28482 (save-excursion
28483 (save-restriction
28484 (set-buffer (marker-buffer m))
28485 (goto-char m)
28486 (org-agenda-set-restriction-lock 'subtree))))
28487 ((setq p (text-property-any (point-at-bol) (point-at-eol)
28488 'speedbar-function 'speedbar-find-file))
28489 (setq tp (previous-single-property-change
28490 (1+ p) 'speedbar-function)
28491 np (next-single-property-change
28492 tp 'speedbar-function)
28493 dir (speedbar-line-directory)
28494 txt (buffer-substring-no-properties (or tp (point-min))
28495 (or np (point-max))))
28496 (save-excursion
28497 (save-restriction
28498 (set-buffer (find-file-noselect
28499 (let ((default-directory dir))
28500 (expand-file-name txt))))
28501 (unless (org-mode-p)
28502 (error "Cannot restrict to non-Org-mode file"))
28503 (org-agenda-set-restriction-lock 'file))))
28504 (t (error "Don't know how to restrict Org-mode's agenda")))
28505 (org-move-overlay org-speedbar-restriction-lock-overlay
28506 (point-at-bol) (point-at-eol))
28507 (setq current-prefix-arg nil)
28508 (org-agenda-maybe-redo)))
28510 (eval-after-load "speedbar"
28511 '(progn
28512 (speedbar-add-supported-extension ".org")
28513 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
28514 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
28515 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
28516 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
28517 (add-hook 'speedbar-visiting-tag-hook
28518 (lambda () (org-show-context 'org-goto)))))
28521 ;;; Fixes and Hacks
28523 ;; Make flyspell not check words in links, to not mess up our keymap
28524 (defun org-mode-flyspell-verify ()
28525 "Don't let flyspell put overlays at active buttons."
28526 (not (get-text-property (point) 'keymap)))
28528 ;; Make `bookmark-jump' show the jump location if it was hidden.
28529 (eval-after-load "bookmark"
28530 '(if (boundp 'bookmark-after-jump-hook)
28531 ;; We can use the hook
28532 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
28533 ;; Hook not available, use advice
28534 (defadvice bookmark-jump (after org-make-visible activate)
28535 "Make the position visible."
28536 (org-bookmark-jump-unhide))))
28538 (defun org-bookmark-jump-unhide ()
28539 "Unhide the current position, to show the bookmark location."
28540 (and (org-mode-p)
28541 (or (org-invisible-p)
28542 (save-excursion (goto-char (max (point-min) (1- (point))))
28543 (org-invisible-p)))
28544 (org-show-context 'bookmark-jump)))
28546 ;; Fix a bug in htmlize where there are text properties (face nil)
28547 (eval-after-load "htmlize"
28548 '(progn
28549 (defadvice htmlize-faces-in-buffer (after org-no-nil-faces activate)
28550 "Make sure there are no nil faces"
28551 (setq ad-return-value (delq nil ad-return-value)))))
28553 ;; Make session.el ignore our circular variable
28554 (eval-after-load "session"
28555 '(add-to-list 'session-globals-exclude 'org-mark-ring))
28557 ;;;; Experimental code
28559 (defun org-closed-in-range ()
28560 "Sparse tree of items closed in a certain time range.
28561 Still experimental, may disappear in the future."
28562 (interactive)
28563 ;; Get the time interval from the user.
28564 (let* ((time1 (time-to-seconds
28565 (org-read-date nil 'to-time nil "Starting date: ")))
28566 (time2 (time-to-seconds
28567 (org-read-date nil 'to-time nil "End date:")))
28568 ;; callback function
28569 (callback (lambda ()
28570 (let ((time
28571 (time-to-seconds
28572 (apply 'encode-time
28573 (org-parse-time-string
28574 (match-string 1))))))
28575 ;; check if time in interval
28576 (and (>= time time1) (<= time time2))))))
28577 ;; make tree, check each match with the callback
28578 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
28580 ;;;; Finish up
28582 (provide 'org)
28584 (run-hooks 'org-load-hook)
28586 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
28587 ;;; org.el ends here