Fix minor issues after release 5.23.
[org-mode.git] / org.el
blobc9c4307e3f384c8022eb35a33d42c2f998b3567e
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.23a
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.23a"
88 "The version number of the file org.el.")
90 (defun org-version (&optional here)
91 "Show the org-mode version in the echo area.
92 With prefix arg HERE, insert it at point."
93 (interactive "P")
94 (let ((version (format "Org-mode version %s" org-version)))
95 (message version)
96 (if here
97 (insert version))))
99 ;;; Compatibility constants
100 (defconst org-xemacs-p (featurep 'xemacs)) ; not used by org.el itself
101 (defconst org-format-transports-properties-p
102 (let ((x "a"))
103 (add-text-properties 0 1 '(test t) x)
104 (get-text-property 0 'test (format "%s" x)))
105 "Does format transport text properties?")
107 (defmacro org-bound-and-true-p (var)
108 "Return the value of symbol VAR if it is bound, else nil."
109 `(and (boundp (quote ,var)) ,var))
111 (defmacro org-unmodified (&rest body)
112 "Execute body without changing `buffer-modified-p'."
113 `(set-buffer-modified-p
114 (prog1 (buffer-modified-p) ,@body)))
116 (defmacro org-re (s)
117 "Replace posix classes in regular expression."
118 (if (featurep 'xemacs)
119 (let ((ss s))
120 (save-match-data
121 (while (string-match "\\[:alnum:\\]" ss)
122 (setq ss (replace-match "a-zA-Z0-9" t t ss)))
123 (while (string-match "\\[:alpha:\\]" ss)
124 (setq ss (replace-match "a-zA-Z" t t ss)))
125 ss))
128 (defmacro org-preserve-lc (&rest body)
129 `(let ((_line (org-current-line))
130 (_col (current-column)))
131 (unwind-protect
132 (progn ,@body)
133 (goto-line _line)
134 (move-to-column _col))))
136 (defmacro org-without-partial-completion (&rest body)
137 `(let ((pc-mode (and (boundp 'partial-completion-mode)
138 partial-completion-mode)))
139 (unwind-protect
140 (progn
141 (if pc-mode (partial-completion-mode -1))
142 ,@body)
143 (if pc-mode (partial-completion-mode 1)))))
145 ;;; The custom variables
147 (defgroup org nil
148 "Outline-based notes management and organizer."
149 :tag "Org"
150 :group 'outlines
151 :group 'hypermedia
152 :group 'calendar)
154 (defcustom org-load-hook nil
155 "Hook that is run after org.el has been loaded."
156 :group 'org
157 :type 'hook)
159 ;(defcustom org-default-extensions '(org-irc)
160 ; "Extensions that should always be loaded together with org.el.
161 ;If the description starts with <A>, this means the extension
162 ;will be autoloaded when needed, preloading is not necessary.
163 ;FIXME: this does not ork correctly, ignore it for now."
164 ; :group 'org
165 ; :type
166 ; '(set :greedy t
167 ; (const :tag " Mouse support (org-mouse.el)" org-mouse)
168 ; (const :tag "<A> Publishing (org-publish.el)" org-publish)
169 ; (const :tag "<A> LaTeX export (org-export-latex.el)" org-export-latex)
170 ; (const :tag " IRC/ERC links (org-irc.el)" org-irc)
171 ; (const :tag " Apple Mail message links under OS X (org-mac-message.el)" org-mac-message)))
173 ;(defun org-load-default-extensions ()
174 ; "Load all extensions listed in `org-default-extensions'."
175 ; (mapc (lambda (ext)
176 ; (condition-case nil (require ext)
177 ; (error (message "Problems while trying to load feature `%s'" ext))))
178 ; org-default-extensions))
180 ;(eval-after-load "org" '(org-load-default-extensions))
182 ;; FIXME: Needs a separate group...
183 (defcustom org-completion-fallback-command 'hippie-expand
184 "The expansion command called by \\[org-complete] in normal context.
185 Normal means, no org-mode-specific context."
186 :group 'org
187 :type 'function)
189 (defgroup org-startup nil
190 "Options concerning startup of Org-mode."
191 :tag "Org Startup"
192 :group 'org)
194 (defcustom org-startup-folded t
195 "Non-nil means, entering Org-mode will switch to OVERVIEW.
196 This can also be configured on a per-file basis by adding one of
197 the following lines anywhere in the buffer:
199 #+STARTUP: fold
200 #+STARTUP: nofold
201 #+STARTUP: content"
202 :group 'org-startup
203 :type '(choice
204 (const :tag "nofold: show all" nil)
205 (const :tag "fold: overview" t)
206 (const :tag "content: all headlines" content)))
208 (defcustom org-startup-truncated t
209 "Non-nil means, entering Org-mode will set `truncate-lines'.
210 This is useful since some lines containing links can be very long and
211 uninteresting. Also tables look terrible when wrapped."
212 :group 'org-startup
213 :type 'boolean)
215 (defcustom org-startup-align-all-tables nil
216 "Non-nil means, align all tables when visiting a file.
217 This is useful when the column width in tables is forced with <N> cookies
218 in table fields. Such tables will look correct only after the first re-align.
219 This can also be configured on a per-file basis by adding one of
220 the following lines anywhere in the buffer:
221 #+STARTUP: align
222 #+STARTUP: noalign"
223 :group 'org-startup
224 :type 'boolean)
226 (defcustom org-insert-mode-line-in-empty-file nil
227 "Non-nil means insert the first line setting Org-mode in empty files.
228 When the function `org-mode' is called interactively in an empty file, this
229 normally means that the file name does not automatically trigger Org-mode.
230 To ensure that the file will always be in Org-mode in the future, a
231 line enforcing Org-mode will be inserted into the buffer, if this option
232 has been set."
233 :group 'org-startup
234 :type 'boolean)
236 (defcustom org-replace-disputed-keys nil
237 "Non-nil means use alternative key bindings for some keys.
238 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
239 These keys are also used by other packages like `CUA-mode' or `windmove.el'.
240 If you want to use Org-mode together with one of these other modes,
241 or more generally if you would like to move some Org-mode commands to
242 other keys, set this variable and configure the keys with the variable
243 `org-disputed-keys'.
245 This option is only relevant at load-time of Org-mode, and must be set
246 *before* org.el is loaded. Changing it requires a restart of Emacs to
247 become effective."
248 :group 'org-startup
249 :type 'boolean)
251 (if (fboundp 'defvaralias)
252 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys))
254 (defcustom org-disputed-keys
255 '(([(shift up)] . [(meta p)])
256 ([(shift down)] . [(meta n)])
257 ([(shift left)] . [(meta -)])
258 ([(shift right)] . [(meta +)])
259 ([(control shift right)] . [(meta shift +)])
260 ([(control shift left)] . [(meta shift -)]))
261 "Keys for which Org-mode and other modes compete.
262 This is an alist, cars are the default keys, second element specifies
263 the alternative to use when `org-replace-disputed-keys' is t.
265 Keys can be specified in any syntax supported by `define-key'.
266 The value of this option takes effect only at Org-mode's startup,
267 therefore you'll have to restart Emacs to apply it after changing."
268 :group 'org-startup
269 :type 'alist)
271 (defun org-key (key)
272 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
273 Or return the original if not disputed."
274 (if org-replace-disputed-keys
275 (let* ((nkey (key-description key))
276 (x (org-find-if (lambda (x)
277 (equal (key-description (car x)) nkey))
278 org-disputed-keys)))
279 (if x (cdr x) key))
280 key))
282 (defun org-find-if (predicate seq)
283 (catch 'exit
284 (while seq
285 (if (funcall predicate (car seq))
286 (throw 'exit (car seq))
287 (pop seq)))))
289 (defun org-defkey (keymap key def)
290 "Define a key, possibly translated, as returned by `org-key'."
291 (define-key keymap (org-key key) def))
293 (defcustom org-ellipsis nil
294 "The ellipsis to use in the Org-mode outline.
295 When nil, just use the standard three dots. When a string, use that instead,
296 When a face, use the standart 3 dots, but with the specified face.
297 The change affects only Org-mode (which will then use its own display table).
298 Changing this requires executing `M-x org-mode' in a buffer to become
299 effective."
300 :group 'org-startup
301 :type '(choice (const :tag "Default" nil)
302 (face :tag "Face" :value org-warning)
303 (string :tag "String" :value "...#")))
305 (defvar org-display-table nil
306 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
308 (defgroup org-keywords nil
309 "Keywords in Org-mode."
310 :tag "Org Keywords"
311 :group 'org)
313 (defcustom org-deadline-string "DEADLINE:"
314 "String to mark deadline entries.
315 A deadline is this string, followed by a time stamp. Should be a word,
316 terminated by a colon. You can insert a schedule keyword and
317 a timestamp with \\[org-deadline].
318 Changes become only effective after restarting Emacs."
319 :group 'org-keywords
320 :type 'string)
322 (defcustom org-scheduled-string "SCHEDULED:"
323 "String to mark scheduled TODO entries.
324 A schedule is this string, followed by a time stamp. Should be a word,
325 terminated by a colon. You can insert a schedule keyword and
326 a timestamp with \\[org-schedule].
327 Changes become only effective after restarting Emacs."
328 :group 'org-keywords
329 :type 'string)
331 (defcustom org-closed-string "CLOSED:"
332 "String used as the prefix for timestamps logging closing a TODO entry."
333 :group 'org-keywords
334 :type 'string)
336 (defcustom org-clock-string "CLOCK:"
337 "String used as prefix for timestamps clocking work hours on an item."
338 :group 'org-keywords
339 :type 'string)
341 (defcustom org-comment-string "COMMENT"
342 "Entries starting with this keyword will never be exported.
343 An entry can be toggled between COMMENT and normal with
344 \\[org-toggle-comment].
345 Changes become only effective after restarting Emacs."
346 :group 'org-keywords
347 :type 'string)
349 (defcustom org-quote-string "QUOTE"
350 "Entries starting with this keyword will be exported in fixed-width font.
351 Quoting applies only to the text in the entry following the headline, and does
352 not extend beyond the next headline, even if that is lower level.
353 An entry can be toggled between QUOTE and normal with
354 \\[org-toggle-fixed-width-section]."
355 :group 'org-keywords
356 :type 'string)
358 (defconst org-repeat-re
359 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*\\([.+]?\\+[0-9]+[dwmy]\\)"
360 "Regular expression for specifying repeated events.
361 After a match, group 1 contains the repeat expression.")
363 (defgroup org-structure nil
364 "Options concerning the general structure of Org-mode files."
365 :tag "Org Structure"
366 :group 'org)
368 (defgroup org-reveal-location nil
369 "Options about how to make context of a location visible."
370 :tag "Org Reveal Location"
371 :group 'org-structure)
373 (defconst org-context-choice
374 '(choice
375 (const :tag "Always" t)
376 (const :tag "Never" nil)
377 (repeat :greedy t :tag "Individual contexts"
378 (cons
379 (choice :tag "Context"
380 (const agenda)
381 (const org-goto)
382 (const occur-tree)
383 (const tags-tree)
384 (const link-search)
385 (const mark-goto)
386 (const bookmark-jump)
387 (const isearch)
388 (const default))
389 (boolean))))
390 "Contexts for the reveal options.")
392 (defcustom org-show-hierarchy-above '((default . t))
393 "Non-nil means, show full hierarchy when revealing a location.
394 Org-mode often shows locations in an org-mode file which might have
395 been invisible before. When this is set, the hierarchy of headings
396 above the exposed location is shown.
397 Turning this off for example for sparse trees makes them very compact.
398 Instead of t, this can also be an alist specifying this option for different
399 contexts. Valid contexts are
400 agenda when exposing an entry from the agenda
401 org-goto when using the command `org-goto' on key C-c C-j
402 occur-tree when using the command `org-occur' on key C-c /
403 tags-tree when constructing a sparse tree based on tags matches
404 link-search when exposing search matches associated with a link
405 mark-goto when exposing the jump goal of a mark
406 bookmark-jump when exposing a bookmark location
407 isearch when exiting from an incremental search
408 default default for all contexts not set explicitly"
409 :group 'org-reveal-location
410 :type org-context-choice)
412 (defcustom org-show-following-heading '((default . nil))
413 "Non-nil means, show following heading when revealing a location.
414 Org-mode often shows locations in an org-mode file which might have
415 been invisible before. When this is set, the heading following the
416 match is shown.
417 Turning this off for example for sparse trees makes them very compact,
418 but makes it harder to edit the location of the match. In such a case,
419 use the command \\[org-reveal] to show more context.
420 Instead of t, this can also be an alist specifying this option for different
421 contexts. See `org-show-hierarchy-above' for valid contexts."
422 :group 'org-reveal-location
423 :type org-context-choice)
425 (defcustom org-show-siblings '((default . nil) (isearch t))
426 "Non-nil means, show all sibling heading when revealing a location.
427 Org-mode often shows locations in an org-mode file which might have
428 been invisible before. When this is set, the sibling of the current entry
429 heading are all made visible. If `org-show-hierarchy-above' is t,
430 the same happens on each level of the hierarchy above the current entry.
432 By default this is on for the isearch context, off for all other contexts.
433 Turning this off for example for sparse trees makes them very compact,
434 but makes it harder to edit the location of the match. In such a case,
435 use the command \\[org-reveal] to show more context.
436 Instead of t, this can also be an alist specifying this option for different
437 contexts. See `org-show-hierarchy-above' for valid contexts."
438 :group 'org-reveal-location
439 :type org-context-choice)
441 (defcustom org-show-entry-below '((default . nil))
442 "Non-nil means, show the entry below a headline when revealing a location.
443 Org-mode often shows locations in an org-mode file which might have
444 been invisible before. When this is set, the text below the headline that is
445 exposed is also shown.
447 By default this is off for all contexts.
448 Instead of t, this can also be an alist specifying this option for different
449 contexts. See `org-show-hierarchy-above' for valid contexts."
450 :group 'org-reveal-location
451 :type org-context-choice)
453 (defgroup org-cycle nil
454 "Options concerning visibility cycling in Org-mode."
455 :tag "Org Cycle"
456 :group 'org-structure)
458 (defcustom org-drawers '("PROPERTIES" "CLOCK")
459 "Names of drawers. Drawers are not opened by cycling on the headline above.
460 Drawers only open with a TAB on the drawer line itself. A drawer looks like
461 this:
462 :DRAWERNAME:
463 .....
464 :END:
465 The drawer \"PROPERTIES\" is special for capturing properties through
466 the property API.
468 Drawers can be defined on the per-file basis with a line like:
470 #+DRAWERS: HIDDEN STATE PROPERTIES"
471 :group 'org-structure
472 :type '(repeat (string :tag "Drawer Name")))
474 (defcustom org-cycle-global-at-bob nil
475 "Cycle globally if cursor is at beginning of buffer and not at a headline.
476 This makes it possible to do global cycling without having to use S-TAB or
477 C-u TAB. For this special case to work, the first line of the buffer
478 must not be a headline - it may be empty ot some other text. When used in
479 this way, `org-cycle-hook' is disables temporarily, to make sure the
480 cursor stays at the beginning of the buffer.
481 When this option is nil, don't do anything special at the beginning
482 of the buffer."
483 :group 'org-cycle
484 :type 'boolean)
486 (defcustom org-cycle-emulate-tab t
487 "Where should `org-cycle' emulate TAB.
488 nil Never
489 white Only in completely white lines
490 whitestart Only at the beginning of lines, before the first non-white char
491 t Everywhere except in headlines
492 exc-hl-bol Everywhere except at the start of a headline
493 If TAB is used in a place where it does not emulate TAB, the current subtree
494 visibility is cycled."
495 :group 'org-cycle
496 :type '(choice (const :tag "Never" nil)
497 (const :tag "Only in completely white lines" white)
498 (const :tag "Before first char in a line" whitestart)
499 (const :tag "Everywhere except in headlines" t)
500 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)
503 (defcustom org-cycle-separator-lines 2
504 "Number of empty lines needed to keep an empty line between collapsed trees.
505 If you leave an empty line between the end of a subtree and the following
506 headline, this empty line is hidden when the subtree is folded.
507 Org-mode will leave (exactly) one empty line visible if the number of
508 empty lines is equal or larger to the number given in this variable.
509 So the default 2 means, at least 2 empty lines after the end of a subtree
510 are needed to produce free space between a collapsed subtree and the
511 following headline.
513 Special case: when 0, never leave empty lines in collapsed view."
514 :group 'org-cycle
515 :type 'integer)
517 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
518 org-cycle-hide-drawers
519 org-cycle-show-empty-lines
520 org-optimize-window-after-visibility-change)
521 "Hook that is run after `org-cycle' has changed the buffer visibility.
522 The function(s) in this hook must accept a single argument which indicates
523 the new state that was set by the most recent `org-cycle' command. The
524 argument is a symbol. After a global state change, it can have the values
525 `overview', `content', or `all'. After a local state change, it can have
526 the values `folded', `children', or `subtree'."
527 :group 'org-cycle
528 :type 'hook)
530 (defgroup org-edit-structure nil
531 "Options concerning structure editing in Org-mode."
532 :tag "Org Edit Structure"
533 :group 'org-structure)
535 (defcustom org-odd-levels-only nil
536 "Non-nil means, skip even levels and only use odd levels for the outline.
537 This has the effect that two stars are being added/taken away in
538 promotion/demotion commands. It also influences how levels are
539 handled by the exporters.
540 Changing it requires restart of `font-lock-mode' to become effective
541 for fontification also in regions already fontified.
542 You may also set this on a per-file basis by adding one of the following
543 lines to the buffer:
545 #+STARTUP: odd
546 #+STARTUP: oddeven"
547 :group 'org-edit-structure
548 :group 'org-font-lock
549 :type 'boolean)
551 (defcustom org-adapt-indentation t
552 "Non-nil means, adapt indentation when promoting and demoting.
553 When this is set and the *entire* text in an entry is indented, the
554 indentation is increased by one space in a demotion command, and
555 decreased by one in a promotion command. If any line in the entry
556 body starts at column 0, indentation is not changed at all."
557 :group 'org-edit-structure
558 :type 'boolean)
560 (defcustom org-special-ctrl-a/e nil
561 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
562 When t, `C-a' will bring back the cursor to the beginning of the
563 headline text, i.e. after the stars and after a possible TODO keyword.
564 In an item, this will be the position after the bullet.
565 When the cursor is already at that position, another `C-a' will bring
566 it to the beginning of the line.
567 `C-e' will jump to the end of the headline, ignoring the presence of tags
568 in the headline. A second `C-e' will then jump to the true end of the
569 line, after any tags.
570 When set to the symbol `reversed', the first `C-a' or `C-e' works normally,
571 and only a directly following, identical keypress will bring the cursor
572 to the special positions."
573 :group 'org-edit-structure
574 :type '(choice
575 (const :tag "off" nil)
576 (const :tag "after bullet first" t)
577 (const :tag "border first" reversed)))
579 (if (fboundp 'defvaralias)
580 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e))
582 (defcustom org-special-ctrl-k nil
583 "Non-nil means `C-k' will behave specially in headlines.
584 When nil, `C-k' will call the default `kill-line' command.
585 When t, the following will happen while the cursor is in the headline:
587 - When the cursor is at the beginning of a headline, kill the entire
588 line and possible the folded subtree below the line.
589 - When in the middle of the headline text, kill the headline up to the tags.
590 - When after the headline text, kill the tags."
591 :group 'org-edit-structure
592 :type 'boolean)
594 (defcustom org-M-RET-may-split-line '((default . t))
595 "Non-nil means, M-RET will split the line at the cursor position.
596 When nil, it will go to the end of the line before making a
597 new line.
598 You may also set this option in a different way for different
599 contexts. Valid contexts are:
601 headline when creating a new headline
602 item when creating a new item
603 table in a table field
604 default the value to be used for all contexts not explicitly
605 customized"
606 :group 'org-structure
607 :group 'org-table
608 :type '(choice
609 (const :tag "Always" t)
610 (const :tag "Never" nil)
611 (repeat :greedy t :tag "Individual contexts"
612 (cons
613 (choice :tag "Context"
614 (const headline)
615 (const item)
616 (const table)
617 (const default))
618 (boolean)))))
621 (defcustom org-blank-before-new-entry '((heading . nil)
622 (plain-list-item . nil))
623 "Should `org-insert-heading' leave a blank line before new heading/item?
624 The value is an alist, with `heading' and `plain-list-item' as car,
625 and a boolean flag as cdr."
626 :group 'org-edit-structure
627 :type '(list
628 (cons (const heading) (boolean))
629 (cons (const plain-list-item) (boolean))))
631 (defcustom org-insert-heading-hook nil
632 "Hook being run after inserting a new heading."
633 :group 'org-edit-structure
634 :type 'hook)
636 (defcustom org-enable-fixed-width-editor t
637 "Non-nil means, lines starting with \":\" are treated as fixed-width.
638 This currently only means, they are never auto-wrapped.
639 When nil, such lines will be treated like ordinary lines.
640 See also the QUOTE keyword."
641 :group 'org-edit-structure
642 :type 'boolean)
644 (defcustom org-goto-auto-isearch t
645 "Non-nil means, typing characters in org-goto starts incremental search."
646 :group 'org-edit-structure
647 :type 'boolean)
649 (defgroup org-sparse-trees nil
650 "Options concerning sparse trees in Org-mode."
651 :tag "Org Sparse Trees"
652 :group 'org-structure)
654 (defcustom org-highlight-sparse-tree-matches t
655 "Non-nil means, highlight all matches that define a sparse tree.
656 The highlights will automatically disappear the next time the buffer is
657 changed by an edit command."
658 :group 'org-sparse-trees
659 :type 'boolean)
661 (defcustom org-remove-highlights-with-change t
662 "Non-nil means, any change to the buffer will remove temporary highlights.
663 Such highlights are created by `org-occur' and `org-clock-display'.
664 When nil, `C-c C-c needs to be used to get rid of the highlights.
665 The highlights created by `org-preview-latex-fragment' always need
666 `C-c C-c' to be removed."
667 :group 'org-sparse-trees
668 :group 'org-time
669 :type 'boolean)
672 (defcustom org-occur-hook '(org-first-headline-recenter)
673 "Hook that is run after `org-occur' has constructed a sparse tree.
674 This can be used to recenter the window to show as much of the structure
675 as possible."
676 :group 'org-sparse-trees
677 :type 'hook)
679 (defgroup org-plain-lists nil
680 "Options concerning plain lists in Org-mode."
681 :tag "Org Plain lists"
682 :group 'org-structure)
684 (defcustom org-cycle-include-plain-lists nil
685 "Non-nil means, include plain lists into visibility cycling.
686 This means that during cycling, plain list items will *temporarily* be
687 interpreted as outline headlines with a level given by 1000+i where i is the
688 indentation of the bullet. In all other operations, plain list items are
689 not seen as headlines. For example, you cannot assign a TODO keyword to
690 such an item."
691 :group 'org-plain-lists
692 :type 'boolean)
694 (defcustom org-plain-list-ordered-item-terminator t
695 "The character that makes a line with leading number an ordered list item.
696 Valid values are ?. and ?\). To get both terminators, use t. While
697 ?. may look nicer, it creates the danger that a line with leading
698 number may be incorrectly interpreted as an item. ?\) therefore is
699 the safe choice."
700 :group 'org-plain-lists
701 :type '(choice (const :tag "dot like in \"2.\"" ?.)
702 (const :tag "paren like in \"2)\"" ?\))
703 (const :tab "both" t)))
705 (defcustom org-auto-renumber-ordered-lists t
706 "Non-nil means, automatically renumber ordered plain lists.
707 Renumbering happens when the sequence have been changed with
708 \\[org-shiftmetaup] or \\[org-shiftmetadown]. After other editing commands,
709 use \\[org-ctrl-c-ctrl-c] to trigger renumbering."
710 :group 'org-plain-lists
711 :type 'boolean)
713 (defcustom org-provide-checkbox-statistics t
714 "Non-nil means, update checkbox statistics after insert and toggle.
715 When this is set, checkbox statistics is updated each time you either insert
716 a new checkbox with \\[org-insert-todo-heading] or toggle a checkbox
717 with \\[org-ctrl-c-ctrl-c\\]."
718 :group 'org-plain-lists
719 :type 'boolean)
721 (defgroup org-archive nil
722 "Options concerning archiving in Org-mode."
723 :tag "Org Archive"
724 :group 'org-structure)
726 (defcustom org-archive-tag "ARCHIVE"
727 "The tag that marks a subtree as archived.
728 An archived subtree does not open during visibility cycling, and does
729 not contribute to the agenda listings.
730 After changing this, font-lock must be restarted in the relevant buffers to
731 get the proper fontification."
732 :group 'org-archive
733 :group 'org-keywords
734 :type 'string)
736 (defcustom org-agenda-skip-archived-trees t
737 "Non-nil means, the agenda will skip any items located in archived trees.
738 An archived tree is a tree marked with the tag ARCHIVE."
739 :group 'org-archive
740 :group 'org-agenda-skip
741 :type 'boolean)
743 (defcustom org-cycle-open-archived-trees nil
744 "Non-nil means, `org-cycle' will open archived trees.
745 An archived tree is a tree marked with the tag ARCHIVE.
746 When nil, archived trees will stay folded. You can still open them with
747 normal outline commands like `show-all', but not with the cycling commands."
748 :group 'org-archive
749 :group 'org-cycle
750 :type 'boolean)
752 (defcustom org-sparse-tree-open-archived-trees nil
753 "Non-nil means sparse tree construction shows matches in archived trees.
754 When nil, matches in these trees are highlighted, but the trees are kept in
755 collapsed state."
756 :group 'org-archive
757 :group 'org-sparse-trees
758 :type 'boolean)
760 (defcustom org-archive-location "%s_archive::"
761 "The location where subtrees should be archived.
762 This string consists of two parts, separated by a double-colon.
764 The first part is a file name - when omitted, archiving happens in the same
765 file. %s will be replaced by the current file name (without directory part).
766 Archiving to a different file is useful to keep archived entries from
767 contributing to the Org-mode Agenda.
769 The part after the double colon is a headline. The archived entries will be
770 filed under that headline. When omitted, the subtrees are simply filed away
771 at the end of the file, as top-level entries.
773 Here are a few examples:
774 \"%s_archive::\"
775 If the current file is Projects.org, archive in file
776 Projects.org_archive, as top-level trees. This is the default.
778 \"::* Archived Tasks\"
779 Archive in the current file, under the top-level headline
780 \"* Archived Tasks\".
782 \"~/org/archive.org::\"
783 Archive in file ~/org/archive.org (absolute path), as top-level trees.
785 \"basement::** Finished Tasks\"
786 Archive in file ./basement (relative path), as level 3 trees
787 below the level 2 heading \"** Finished Tasks\".
789 You may set this option on a per-file basis by adding to the buffer a
790 line like
792 #+ARCHIVE: basement::** Finished Tasks"
793 :group 'org-archive
794 :type 'string)
796 (defcustom org-archive-mark-done t
797 "Non-nil means, mark entries as DONE when they are moved to the archive file.
798 This can be a string to set the keyword to use. When t, Org-mode will
799 use the first keyword in its list that means done."
800 :group 'org-archive
801 :type '(choice
802 (const :tag "No" nil)
803 (const :tag "Yes" t)
804 (string :tag "Use this keyword")))
806 (defcustom org-archive-stamp-time t
807 "Non-nil means, add a time stamp to entries moved to an archive file.
808 This variable is obsolete and has no effect anymore, instead add ot remove
809 `time' from the variablle `org-archive-save-context-info'."
810 :group 'org-archive
811 :type 'boolean)
813 (defcustom org-archive-save-context-info '(time file olpath category todo itags)
814 "Parts of context info that should be stored as properties when archiving.
815 When a subtree is moved to an archive file, it looses information given by
816 context, like inherited tags, the category, and possibly also the TODO
817 state (depending on the variable `org-archive-mark-done').
818 This variable can be a list of any of the following symbols:
820 time The time of archiving.
821 file The file where the entry originates.
822 itags The local tags, in the headline of the subtree.
823 ltags The tags the subtree inherits from further up the hierarchy.
824 todo The pre-archive TODO state.
825 category The category, taken from file name or #+CATEGORY lines.
826 olpath The outline path to the item. These are all headlines above
827 the current item, separated by /, like a file path.
829 For each symbol present in the list, a property will be created in
830 the archived entry, with a prefix \"PRE_ARCHIVE_\", to remember this
831 information."
832 :group 'org-archive
833 :type '(set :greedy t
834 (const :tag "Time" time)
835 (const :tag "File" file)
836 (const :tag "Category" category)
837 (const :tag "TODO state" todo)
838 (const :tag "TODO state" priority)
839 (const :tag "Inherited tags" itags)
840 (const :tag "Outline path" olpath)
841 (const :tag "Local tags" ltags)))
843 (defgroup org-imenu-and-speedbar nil
844 "Options concerning imenu and speedbar in Org-mode."
845 :tag "Org Imenu and Speedbar"
846 :group 'org-structure)
848 (defcustom org-imenu-depth 2
849 "The maximum level for Imenu access to Org-mode headlines.
850 This also applied for speedbar access."
851 :group 'org-imenu-and-speedbar
852 :type 'number)
854 (defgroup org-table nil
855 "Options concerning tables in Org-mode."
856 :tag "Org Table"
857 :group 'org)
859 (defcustom org-enable-table-editor 'optimized
860 "Non-nil means, lines starting with \"|\" are handled by the table editor.
861 When nil, such lines will be treated like ordinary lines.
863 When equal to the symbol `optimized', the table editor will be optimized to
864 do the following:
865 - Automatic overwrite mode in front of whitespace in table fields.
866 This makes the structure of the table stay in tact as long as the edited
867 field does not exceed the column width.
868 - Minimize the number of realigns. Normally, the table is aligned each time
869 TAB or RET are pressed to move to another field. With optimization this
870 happens only if changes to a field might have changed the column width.
871 Optimization requires replacing the functions `self-insert-command',
872 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
873 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
874 very good at guessing when a re-align will be necessary, but you can always
875 force one with \\[org-ctrl-c-ctrl-c].
877 If you would like to use the optimized version in Org-mode, but the
878 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
880 This variable can be used to turn on and off the table editor during a session,
881 but in order to toggle optimization, a restart is required.
883 See also the variable `org-table-auto-blank-field'."
884 :group 'org-table
885 :type '(choice
886 (const :tag "off" nil)
887 (const :tag "on" t)
888 (const :tag "on, optimized" optimized)))
890 (defcustom orgtbl-optimized (eq org-enable-table-editor 'optimized)
891 "Non-nil means, use the optimized table editor version for `orgtbl-mode'.
892 In the optimized version, the table editor takes over all simple keys that
893 normally just insert a character. In tables, the characters are inserted
894 in a way to minimize disturbing the table structure (i.e. in overwrite mode
895 for empty fields). Outside tables, the correct binding of the keys is
896 restored.
898 The default for this option is t if the optimized version is also used in
899 Org-mode. See the variable `org-enable-table-editor' for details. Changing
900 this variable requires a restart of Emacs to become effective."
901 :group 'org-table
902 :type 'boolean)
904 (defcustom orgtbl-radio-table-templates
905 '((latex-mode "% BEGIN RECEIVE ORGTBL %n
906 % END RECEIVE ORGTBL %n
907 \\begin{comment}
908 #+ORGTBL: SEND %n orgtbl-to-latex :splice nil :skip 0
909 | | |
910 \\end{comment}\n")
911 (texinfo-mode "@c BEGIN RECEIVE ORGTBL %n
912 @c END RECEIVE ORGTBL %n
913 @ignore
914 #+ORGTBL: SEND %n orgtbl-to-html :splice nil :skip 0
915 | | |
916 @end ignore\n")
917 (html-mode "<!-- BEGIN RECEIVE ORGTBL %n -->
918 <!-- END RECEIVE ORGTBL %n -->
919 <!--
920 #+ORGTBL: SEND %n orgtbl-to-html :splice nil :skip 0
921 | | |
922 -->\n"))
923 "Templates for radio tables in different major modes.
924 All occurrences of %n in a template will be replaced with the name of the
925 table, obtained by prompting the user."
926 :group 'org-table
927 :type '(repeat
928 (list (symbol :tag "Major mode")
929 (string :tag "Format"))))
931 (defgroup org-table-settings nil
932 "Settings for tables in Org-mode."
933 :tag "Org Table Settings"
934 :group 'org-table)
936 (defcustom org-table-default-size "5x2"
937 "The default size for newly created tables, Columns x Rows."
938 :group 'org-table-settings
939 :type 'string)
941 (defcustom org-table-number-regexp
942 "^\\([<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%:]*\\|\\(0[xX]\\)[0-9a-fA-F]+\\|nan\\)$"
943 "Regular expression for recognizing numbers in table columns.
944 If a table column contains mostly numbers, it will be aligned to the
945 right. If not, it will be aligned to the left.
947 The default value of this option is a regular expression which allows
948 anything which looks remotely like a number as used in scientific
949 context. For example, all of the following will be considered a
950 number:
951 12 12.2 2.4e-08 2x10^12 4.034+-0.02 2.7(10) >3.5
953 Other options offered by the customize interface are more restrictive."
954 :group 'org-table-settings
955 :type '(choice
956 (const :tag "Positive Integers"
957 "^[0-9]+$")
958 (const :tag "Integers"
959 "^[-+]?[0-9]+$")
960 (const :tag "Floating Point Numbers"
961 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.[0-9]*\\)$")
962 (const :tag "Floating Point Number or Integer"
963 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.?[0-9]*\\)$")
964 (const :tag "Exponential, Floating point, Integer"
965 "^[-+]?[0-9.]+\\([eEdD][-+0-9]+\\)?$")
966 (const :tag "Very General Number-Like, including hex"
967 "^\\([<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%]*\\|\\(0[xX]\\)[0-9a-fA-F]+\\|nan\\)$")
968 (string :tag "Regexp:")))
970 (defcustom org-table-number-fraction 0.5
971 "Fraction of numbers in a column required to make the column align right.
972 In a column all non-white fields are considered. If at least this
973 fraction of fields is matched by `org-table-number-fraction',
974 alignment to the right border applies."
975 :group 'org-table-settings
976 :type 'number)
978 (defgroup org-table-editing nil
979 "Behavior of tables during editing in Org-mode."
980 :tag "Org Table Editing"
981 :group 'org-table)
983 (defcustom org-table-automatic-realign t
984 "Non-nil means, automatically re-align table when pressing TAB or RETURN.
985 When nil, aligning is only done with \\[org-table-align], or after column
986 removal/insertion."
987 :group 'org-table-editing
988 :type 'boolean)
990 (defcustom org-table-auto-blank-field t
991 "Non-nil means, automatically blank table field when starting to type into it.
992 This only happens when typing immediately after a field motion
993 command (TAB, S-TAB or RET).
994 Only relevant when `org-enable-table-editor' is equal to `optimized'."
995 :group 'org-table-editing
996 :type 'boolean)
998 (defcustom org-table-tab-jumps-over-hlines t
999 "Non-nil means, tab in the last column of a table with jump over a hline.
1000 If a horizontal separator line is following the current line,
1001 `org-table-next-field' can either create a new row before that line, or jump
1002 over the line. When this option is nil, a new line will be created before
1003 this line."
1004 :group 'org-table-editing
1005 :type 'boolean)
1007 (defcustom org-table-tab-recognizes-table.el t
1008 "Non-nil means, TAB will automatically notice a table.el table.
1009 When it sees such a table, it moves point into it and - if necessary -
1010 calls `table-recognize-table'."
1011 :group 'org-table-editing
1012 :type 'boolean)
1014 (defgroup org-table-calculation nil
1015 "Options concerning tables in Org-mode."
1016 :tag "Org Table Calculation"
1017 :group 'org-table)
1019 (defcustom org-table-use-standard-references t
1020 "Should org-mode work with table refrences like B3 instead of @3$2?
1021 Possible values are:
1022 nil never use them
1023 from accept as input, do not present for editing
1024 t: accept as input and present for editing"
1025 :group 'org-table-calculation
1026 :type '(choice
1027 (const :tag "Never, don't even check unser input for them" nil)
1028 (const :tag "Always, both as user input, and when editing" t)
1029 (const :tag "Convert user input, don't offer during editing" 'from)))
1031 (defcustom org-table-copy-increment t
1032 "Non-nil means, increment when copying current field with \\[org-table-copy-down]."
1033 :group 'org-table-calculation
1034 :type 'boolean)
1036 (defcustom org-calc-default-modes
1037 '(calc-internal-prec 12
1038 calc-float-format (float 5)
1039 calc-angle-mode deg
1040 calc-prefer-frac nil
1041 calc-symbolic-mode nil
1042 calc-date-format (YYYY "-" MM "-" DD " " Www (" " HH ":" mm))
1043 calc-display-working-message t
1045 "List with Calc mode settings for use in calc-eval for table formulas.
1046 The list must contain alternating symbols (Calc modes variables and values).
1047 Don't remove any of the default settings, just change the values. Org-mode
1048 relies on the variables to be present in the list."
1049 :group 'org-table-calculation
1050 :type 'plist)
1052 (defcustom org-table-formula-evaluate-inline t
1053 "Non-nil means, TAB and RET evaluate a formula in current table field.
1054 If the current field starts with an equal sign, it is assumed to be a formula
1055 which should be evaluated as described in the manual and in the documentation
1056 string of the command `org-table-eval-formula'. This feature requires the
1057 Emacs calc package.
1058 When this variable is nil, formula calculation is only available through
1059 the command \\[org-table-eval-formula]."
1060 :group 'org-table-calculation
1061 :type 'boolean)
1063 (defcustom org-table-formula-use-constants t
1064 "Non-nil means, interpret constants in formulas in tables.
1065 A constant looks like `$c' or `$Grav' and will be replaced before evaluation
1066 by the value given in `org-table-formula-constants', or by a value obtained
1067 from the `constants.el' package."
1068 :group 'org-table-calculation
1069 :type 'boolean)
1071 (defcustom org-table-formula-constants nil
1072 "Alist with constant names and values, for use in table formulas.
1073 The car of each element is a name of a constant, without the `$' before it.
1074 The cdr is the value as a string. For example, if you'd like to use the
1075 speed of light in a formula, you would configure
1077 (setq org-table-formula-constants '((\"c\" . \"299792458.\")))
1079 and then use it in an equation like `$1*$c'.
1081 Constants can also be defined on a per-file basis using a line like
1083 #+CONSTANTS: c=299792458. pi=3.14 eps=2.4e-6"
1084 :group 'org-table-calculation
1085 :type '(repeat
1086 (cons (string :tag "name")
1087 (string :tag "value"))))
1089 (defvar org-table-formula-constants-local nil
1090 "Local version of `org-table-formula-constants'.")
1091 (make-variable-buffer-local 'org-table-formula-constants-local)
1093 (defcustom org-table-allow-automatic-line-recalculation t
1094 "Non-nil means, lines marked with |#| or |*| will be recomputed automatically.
1095 Automatically means, when TAB or RET or C-c C-c are pressed in the line."
1096 :group 'org-table-calculation
1097 :type 'boolean)
1099 (defgroup org-link nil
1100 "Options concerning links in Org-mode."
1101 :tag "Org Link"
1102 :group 'org)
1104 (defvar org-link-abbrev-alist-local nil
1105 "Buffer-local version of `org-link-abbrev-alist', which see.
1106 The value of this is taken from the #+LINK lines.")
1107 (make-variable-buffer-local 'org-link-abbrev-alist-local)
1109 (defcustom org-link-abbrev-alist nil
1110 "Alist of link abbreviations.
1111 The car of each element is a string, to be replaced at the start of a link.
1112 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1113 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1115 [[linkkey:tag][description]]
1117 If REPLACE is a string, the tag will simply be appended to create the link.
1118 If the string contains \"%s\", the tag will be inserted there.
1120 REPLACE may also be a function that will be called with the tag as the
1121 only argument to create the link, which should be returned as a string.
1123 See the manual for examples."
1124 :group 'org-link
1125 :type 'alist)
1127 (defcustom org-descriptive-links t
1128 "Non-nil means, hide link part and only show description of bracket links.
1129 Bracket links are like [[link][descritpion]]. This variable sets the initial
1130 state in new org-mode buffers. The setting can then be toggled on a
1131 per-buffer basis from the Org->Hyperlinks menu."
1132 :group 'org-link
1133 :type 'boolean)
1135 (defcustom org-link-file-path-type 'adaptive
1136 "How the path name in file links should be stored.
1137 Valid values are:
1139 relative Relative to the current directory, i.e. the directory of the file
1140 into which the link is being inserted.
1141 absolute Absolute path, if possible with ~ for home directory.
1142 noabbrev Absolute path, no abbreviation of home directory.
1143 adaptive Use relative path for files in the current directory and sub-
1144 directories of it. For other files, use an absolute path."
1145 :group 'org-link
1146 :type '(choice
1147 (const relative)
1148 (const absolute)
1149 (const noabbrev)
1150 (const adaptive)))
1152 (defcustom org-activate-links '(bracket angle plain radio tag date)
1153 "Types of links that should be activated in Org-mode files.
1154 This is a list of symbols, each leading to the activation of a certain link
1155 type. In principle, it does not hurt to turn on most link types - there may
1156 be a small gain when turning off unused link types. The types are:
1158 bracket The recommended [[link][description]] or [[link]] links with hiding.
1159 angular Links in angular brackes that may contain whitespace like
1160 <bbdb:Carsten Dominik>.
1161 plain Plain links in normal text, no whitespace, like http://google.com.
1162 radio Text that is matched by a radio target, see manual for details.
1163 tag Tag settings in a headline (link to tag search).
1164 date Time stamps (link to calendar).
1166 Changing this variable requires a restart of Emacs to become effective."
1167 :group 'org-link
1168 :type '(set (const :tag "Double bracket links (new style)" bracket)
1169 (const :tag "Angular bracket links (old style)" angular)
1170 (const :tag "Plain text links" plain)
1171 (const :tag "Radio target matches" radio)
1172 (const :tag "Tags" tag)
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-follow-link-hook nil
1249 "Hook that is run after a link has been followed."
1250 :group 'org-link-follow
1251 :type 'hook)
1253 (defcustom org-tab-follows-link nil
1254 "Non-nil means, on links TAB will follow the link.
1255 Needs to be set before org.el is loaded."
1256 :group 'org-link-follow
1257 :type 'boolean)
1259 (defcustom org-return-follows-link nil
1260 "Non-nil means, on links RET will follow the link.
1261 Needs to be set before org.el is loaded."
1262 :group 'org-link-follow
1263 :type 'boolean)
1265 (defcustom org-mouse-1-follows-link
1266 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1267 "Non-nil means, mouse-1 on a link will follow the link.
1268 A longer mouse click will still set point. Does not work on XEmacs.
1269 Needs to be set before org.el is loaded."
1270 :group 'org-link-follow
1271 :type 'boolean)
1273 (defcustom org-mark-ring-length 4
1274 "Number of different positions to be recorded in the ring
1275 Changing this requires a restart of Emacs to work correctly."
1276 :group 'org-link-follow
1277 :type 'interger)
1279 (defcustom org-link-frame-setup
1280 '((vm . vm-visit-folder-other-frame)
1281 (gnus . gnus-other-frame)
1282 (file . find-file-other-window))
1283 "Setup the frame configuration for following links.
1284 When following a link with Emacs, it may often be useful to display
1285 this link in another window or frame. This variable can be used to
1286 set this up for the different types of links.
1287 For VM, use any of
1288 `vm-visit-folder'
1289 `vm-visit-folder-other-frame'
1290 For Gnus, use any of
1291 `gnus'
1292 `gnus-other-frame'
1293 For FILE, use any of
1294 `find-file'
1295 `find-file-other-window'
1296 `find-file-other-frame'
1297 For the calendar, use the variable `calendar-setup'.
1298 For BBDB, it is currently only possible to display the matches in
1299 another window."
1300 :group 'org-link-follow
1301 :type '(list
1302 (cons (const vm)
1303 (choice
1304 (const vm-visit-folder)
1305 (const vm-visit-folder-other-window)
1306 (const vm-visit-folder-other-frame)))
1307 (cons (const gnus)
1308 (choice
1309 (const gnus)
1310 (const gnus-other-frame)))
1311 (cons (const file)
1312 (choice
1313 (const find-file)
1314 (const find-file-other-window)
1315 (const find-file-other-frame)))))
1317 (defcustom org-display-internal-link-with-indirect-buffer nil
1318 "Non-nil means, use indirect buffer to display infile links.
1319 Activating internal links (from one location in a file to another location
1320 in the same file) normally just jumps to the location. When the link is
1321 activated with a C-u prefix (or with mouse-3), the link is displayed in
1322 another window. When this option is set, the other window actually displays
1323 an indirect buffer clone of the current buffer, to avoid any visibility
1324 changes to the current buffer."
1325 :group 'org-link-follow
1326 :type 'boolean)
1328 (defcustom org-open-non-existing-files nil
1329 "Non-nil means, `org-open-file' will open non-existing files.
1330 When nil, an error will be generated."
1331 :group 'org-link-follow
1332 :type 'boolean)
1334 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1335 "Function and arguments to call for following mailto links.
1336 This is a list with the first element being a lisp function, and the
1337 remaining elements being arguments to the function. In string arguments,
1338 %a will be replaced by the address, and %s will be replaced by the subject
1339 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1340 :group 'org-link-follow
1341 :type '(choice
1342 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1343 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1344 (const :tag "message-mail" (message-mail "%a" "%s"))
1345 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1347 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1348 "Non-nil means, ask for confirmation before executing shell links.
1349 Shell links can be dangerous: just think about a link
1351 [[shell:rm -rf ~/*][Google Search]]
1353 This link would show up in your Org-mode document as \"Google Search\",
1354 but really it would remove your entire home directory.
1355 Therefore we advise against setting this variable to nil.
1356 Just change it to `y-or-n-p' of you want to confirm with a
1357 single keystroke rather than having to type \"yes\"."
1358 :group 'org-link-follow
1359 :type '(choice
1360 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1361 (const :tag "with y-or-n (faster)" y-or-n-p)
1362 (const :tag "no confirmation (dangerous)" nil)))
1364 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1365 "Non-nil means, ask for confirmation before executing Emacs Lisp links.
1366 Elisp links can be dangerous: just think about a link
1368 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1370 This link would show up in your Org-mode document as \"Google Search\",
1371 but really it would remove your entire home directory.
1372 Therefore we advise against setting this variable to nil.
1373 Just change it to `y-or-n-p' of you want to confirm with a
1374 single keystroke rather than having to type \"yes\"."
1375 :group 'org-link-follow
1376 :type '(choice
1377 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1378 (const :tag "with y-or-n (faster)" y-or-n-p)
1379 (const :tag "no confirmation (dangerous)" nil)))
1381 (defconst org-file-apps-defaults-gnu
1382 '((remote . emacs)
1383 (t . mailcap))
1384 "Default file applications on a UNIX or GNU/Linux system.
1385 See `org-file-apps'.")
1387 (defconst org-file-apps-defaults-macosx
1388 '((remote . emacs)
1389 (t . "open %s")
1390 ("ps" . "gv %s")
1391 ("ps.gz" . "gv %s")
1392 ("eps" . "gv %s")
1393 ("eps.gz" . "gv %s")
1394 ("dvi" . "xdvi %s")
1395 ("fig" . "xfig %s"))
1396 "Default file applications on a MacOS X system.
1397 The system \"open\" is known as a default, but we use X11 applications
1398 for some files for which the OS does not have a good default.
1399 See `org-file-apps'.")
1401 (defconst org-file-apps-defaults-windowsnt
1402 (list
1403 '(remote . emacs)
1404 (cons t
1405 (list (if (featurep 'xemacs)
1406 'mswindows-shell-execute
1407 'w32-shell-execute)
1408 "open" 'file)))
1409 "Default file applications on a Windows NT system.
1410 The system \"open\" is used for most files.
1411 See `org-file-apps'.")
1413 (defcustom org-file-apps
1415 ("txt" . emacs)
1416 ("tex" . emacs)
1417 ("ltx" . emacs)
1418 ("org" . emacs)
1419 ("el" . emacs)
1420 ("bib" . emacs)
1422 "External applications for opening `file:path' items in a document.
1423 Org-mode uses system defaults for different file types, but
1424 you can use this variable to set the application for a given file
1425 extension. The entries in this list are cons cells where the car identifies
1426 files and the cdr the corresponding command. Possible values for the
1427 file identifier are
1428 \"ext\" A string identifying an extension
1429 `directory' Matches a directory
1430 `remote' Matches a remote file, accessible through tramp or efs.
1431 Remote files most likely should be visited through Emacs
1432 because external applications cannot handle such paths.
1433 t Default for all remaining files
1435 Possible values for the command are:
1436 `emacs' The file will be visited by the current Emacs process.
1437 `default' Use the default application for this file type.
1438 string A command to be executed by a shell; %s will be replaced
1439 by the path to the file.
1440 sexp A Lisp form which will be evaluated. The file path will
1441 be available in the Lisp variable `file'.
1442 For more examples, see the system specific constants
1443 `org-file-apps-defaults-macosx'
1444 `org-file-apps-defaults-windowsnt'
1445 `org-file-apps-defaults-gnu'."
1446 :group 'org-link-follow
1447 :type '(repeat
1448 (cons (choice :value ""
1449 (string :tag "Extension")
1450 (const :tag "Default for unrecognized files" t)
1451 (const :tag "Remote file" remote)
1452 (const :tag "Links to a directory" directory))
1453 (choice :value ""
1454 (const :tag "Visit with Emacs" emacs)
1455 (const :tag "Use system default" default)
1456 (string :tag "Command")
1457 (sexp :tag "Lisp form")))))
1459 (defcustom org-mhe-search-all-folders nil
1460 "Non-nil means, that the search for the mh-message will be extended to
1461 all folders if the message cannot be found in the folder given in the link.
1462 Searching all folders is very efficient with one of the search engines
1463 supported by MH-E, but will be slow with pick."
1464 :group 'org-link-follow
1465 :type 'boolean)
1467 (defgroup org-remember nil
1468 "Options concerning interaction with remember.el."
1469 :tag "Org Remember"
1470 :group 'org)
1472 (defcustom org-directory "~/org"
1473 "Directory with org files.
1474 This directory will be used as default to prompt for org files.
1475 Used by the hooks for remember.el."
1476 :group 'org-remember
1477 :type 'directory)
1479 (defcustom org-default-notes-file "~/.notes"
1480 "Default target for storing notes.
1481 Used by the hooks for remember.el. This can be a string, or nil to mean
1482 the value of `remember-data-file'.
1483 You can set this on a per-template basis with the variable
1484 `org-remember-templates'."
1485 :group 'org-remember
1486 :type '(choice
1487 (const :tag "Default from remember-data-file" nil)
1488 file))
1490 (defcustom org-remember-store-without-prompt t
1491 "Non-nil means, `C-c C-c' stores remember note without further promts.
1492 In this case, you need `C-u C-c C-c' to get the prompts for
1493 note file and headline.
1494 When this variable is nil, `C-c C-c' give you the prompts, and
1495 `C-u C-c C-c' trigger the fasttrack."
1496 :group 'org-remember
1497 :type 'boolean)
1499 (defcustom org-remember-interactive-interface 'refile
1500 "The interface to be used for interactive filing of remember notes.
1501 This is only used when the interactive mode for selecting a filing
1502 location is used (see the variable `org-remember-store-without-prompt').
1503 Allowed vaues are:
1504 outline The interface shows an outline of the relevant file
1505 and the correct heading is found by moving through
1506 the outline or by searching with incremental search.
1507 outline-path-completion Headlines in the current buffer are offered via
1508 completion.
1509 refile Use the refile interface, and offer headlines,
1510 possibly from different buffers."
1511 :group 'org-remember
1512 :type '(choice
1513 (const :tag "Refile" refile)
1514 (const :tag "Outline" outline)
1515 (const :tag "Outline-path-completion" outline-path-completion)))
1517 (defcustom org-goto-interface 'outline
1518 "The default interface to be used for `org-goto'.
1519 Allowed vaues are:
1520 outline The interface shows an outline of the relevant file
1521 and the correct heading is found by moving through
1522 the outline or by searching with incremental search.
1523 outline-path-completion Headlines in the current buffer are offered via
1524 completion."
1525 :group 'org-remember ; FIXME: different group for org-goto and org-refile
1526 :type '(choice
1527 (const :tag "Outline" outline)
1528 (const :tag "Outline-path-completion" outline-path-completion)))
1530 (defcustom org-remember-default-headline ""
1531 "The headline that should be the default location in the notes file.
1532 When filing remember notes, the cursor will start at that position.
1533 You can set this on a per-template basis with the variable
1534 `org-remember-templates'."
1535 :group 'org-remember
1536 :type 'string)
1538 (defcustom org-remember-templates nil
1539 "Templates for the creation of remember buffers.
1540 When nil, just let remember make the buffer.
1541 When not nil, this is a list of 5-element lists. In each entry, the first
1542 element is the name of the template, which should be a single short word.
1543 The second element is a character, a unique key to select this template.
1544 The third element is the template. The fourth element is optional and can
1545 specify a destination file for remember items created with this template.
1546 The default file is given by `org-default-notes-file'. An optional fifth
1547 element can specify the headline in that file that should be offered
1548 first when the user is asked to file the entry. The default headline is
1549 given in the variable `org-remember-default-headline'.
1551 An optional sixth element specifies the contexts in which the user can
1552 select the template. This element can be either a list of major modes
1553 or a function. `org-remember' will first check whether the function
1554 returns `t' or if we are in any of the listed major mode, and select
1555 the template accordingly.
1557 The template specifies the structure of the remember buffer. It should have
1558 a first line starting with a star, to act as the org-mode headline.
1559 Furthermore, the following %-escapes will be replaced with content:
1561 %^{prompt} Prompt the user for a string and replace this sequence with it.
1562 A default value and a completion table ca be specified like this:
1563 %^{prompt|default|completion2|completion3|...}
1564 %t time stamp, date only
1565 %T time stamp with date and time
1566 %u, %U like the above, but inactive time stamps
1567 %^t like %t, but prompt for date. Similarly %^T, %^u, %^U
1568 You may define a prompt like %^{Please specify birthday}t
1569 %n user name (taken from `user-full-name')
1570 %a annotation, normally the link created with org-store-link
1571 %i initial content, the region active. If %i is indented,
1572 the entire inserted text will be indented as well.
1573 %c content of the clipboard, or current kill ring head
1574 %^g prompt for tags, with completion on tags in target file
1575 %^G prompt for tags, with completion all tags in all agenda files
1576 %:keyword specific information for certain link types, see below
1577 %[pathname] insert the contents of the file given by `pathname'
1578 %(sexp) evaluate elisp `(sexp)' and replace with the result
1579 %! Store this note immediately after filling the template
1581 %? After completing the template, position cursor here.
1583 Apart from these general escapes, you can access information specific to the
1584 link type that is created. For example, calling `remember' in emails or gnus
1585 will record the author and the subject of the message, which you can access
1586 with %:author and %:subject, respectively. Here is a complete list of what
1587 is recorded for each link type.
1589 Link type | Available information
1590 -------------------+------------------------------------------------------
1591 bbdb | %:type %:name %:company
1592 vm, wl, mh, rmail | %:type %:subject %:message-id
1593 | %:from %:fromname %:fromaddress
1594 | %:to %:toname %:toaddress
1595 | %:fromto (either \"to NAME\" or \"from NAME\")
1596 gnus | %:group, for messages also all email fields
1597 w3, w3m | %:type %:url
1598 info | %:type %:file %:node
1599 calendar | %:type %:date"
1600 :group 'org-remember
1601 :get (lambda (var) ; Make sure all entries have at least 5 elements
1602 (mapcar (lambda (x)
1603 (if (not (stringp (car x))) (setq x (cons "" x)))
1604 (cond ((= (length x) 4) (append x '("")))
1605 ((= (length x) 3) (append x '("" "")))
1606 (t x)))
1607 (default-value var)))
1608 :type '(repeat
1609 :tag "enabled"
1610 (list :value ("" ?a "\n" nil nil nil)
1611 (string :tag "Name")
1612 (character :tag "Selection Key")
1613 (string :tag "Template")
1614 (choice
1615 (file :tag "Destination file")
1616 (const :tag "Prompt for file" nil))
1617 (choice
1618 (string :tag "Destination headline")
1619 (const :tag "Selection interface for heading"))
1620 (choice
1621 (const :tag "Use by default" nil)
1622 (const :tag "Use in all contexts" t)
1623 (repeat :tag "Use only if in major mode"
1624 (symbol :tag "Major mode"))
1625 (function :tag "Perform a check against function")))))
1627 (defcustom org-reverse-note-order nil
1628 "Non-nil means, store new notes at the beginning of a file or entry.
1629 When nil, new notes will be filed to the end of a file or entry.
1630 This can also be a list with cons cells of regular expressions that
1631 are matched against file names, and values."
1632 :group 'org-remember
1633 :type '(choice
1634 (const :tag "Reverse always" t)
1635 (const :tag "Reverse never" nil)
1636 (repeat :tag "By file name regexp"
1637 (cons regexp boolean))))
1639 (defcustom org-refile-targets nil
1640 "Targets for refiling entries with \\[org-refile].
1641 This is list of cons cells. Each cell contains:
1642 - a specification of the files to be considered, either a list of files,
1643 or a symbol whose function or value fields will be used to retrieve
1644 a file name or a list of file names. Nil means, refile to a different
1645 heading in the current buffer.
1646 - A specification of how to find candidate refile targets. This may be
1647 any of
1648 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
1649 This tag has to be present in all target headlines, inheritance will
1650 not be considered.
1651 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
1652 todo keyword.
1653 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1654 headlines that are refiling targets.
1655 - a cons cell (:level . N). Any headline of level N is considered a target.
1656 - a cons cell (:maxlevel . N). Any headline with level <= N is a target."
1657 ;; FIXME: what if there are a var and func with same name???
1658 :group 'org-remember
1659 :type '(repeat
1660 (cons
1661 (choice :value org-agenda-files
1662 (const :tag "All agenda files" org-agenda-files)
1663 (const :tag "Current buffer" nil)
1664 (function) (variable) (file))
1665 (choice :tag "Identify target headline by"
1666 (cons :tag "Specific tag" (const :tag) (string))
1667 (cons :tag "TODO keyword" (const :todo) (string))
1668 (cons :tag "Regular expression" (const :regexp) (regexp))
1669 (cons :tag "Level number" (const :level) (integer))
1670 (cons :tag "Max Level number" (const :maxlevel) (integer))))))
1672 (defcustom org-refile-use-outline-path nil
1673 "Non-nil means, provide refile targets as paths.
1674 So a level 3 headline will be available as level1/level2/level3.
1675 When the value is `file', also include the file name (without directory)
1676 into the path. When `full-file-path', include the full file path."
1677 :group 'org-remember
1678 :type '(choice
1679 (const :tag "Not" nil)
1680 (const :tag "Yes" t)
1681 (const :tag "Start with file name" file)
1682 (const :tag "Start with full file path" full-file-path)))
1684 (defgroup org-todo nil
1685 "Options concerning TODO items in Org-mode."
1686 :tag "Org TODO"
1687 :group 'org)
1689 (defgroup org-progress nil
1690 "Options concerning Progress logging in Org-mode."
1691 :tag "Org Progress"
1692 :group 'org-time)
1694 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
1695 "List of TODO entry keyword sequences and their interpretation.
1696 \\<org-mode-map>This is a list of sequences.
1698 Each sequence starts with a symbol, either `sequence' or `type',
1699 indicating if the keywords should be interpreted as a sequence of
1700 action steps, or as different types of TODO items. The first
1701 keywords are states requiring action - these states will select a headline
1702 for inclusion into the global TODO list Org-mode produces. If one of
1703 the \"keywords\" is the vertical bat \"|\" the remaining keywords
1704 signify that no further action is necessary. If \"|\" is not found,
1705 the last keyword is treated as the only DONE state of the sequence.
1707 The command \\[org-todo] cycles an entry through these states, and one
1708 additional state where no keyword is present. For details about this
1709 cycling, see the manual.
1711 TODO keywords and interpretation can also be set on a per-file basis with
1712 the special #+SEQ_TODO and #+TYP_TODO lines.
1714 Each keyword can optionally specify a character for fast state selection
1715 \(in combination with the variable `org-use-fast-todo-selection')
1716 and specifiers for state change logging, using the same syntax
1717 that is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says
1718 that the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
1719 indicates to record a time stamp each time this state is selected.
1721 Each keyword may also specify if a timestamp or a note should be
1722 recorded when entering or leaving the state, by adding additional
1723 characters in the parenthesis after the keyword. This looks like this:
1724 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
1725 record only the time of the state change. With X and Y being either
1726 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
1727 Y when leaving the state if and only if the *target* state does not
1728 define X. You may omit any of the fast-selection key or X or /Y,
1729 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
1731 For backward compatibility, this variable may also be just a list
1732 of keywords - in this case the interptetation (sequence or type) will be
1733 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
1734 :group 'org-todo
1735 :group 'org-keywords
1736 :type '(choice
1737 (repeat :tag "Old syntax, just keywords"
1738 (string :tag "Keyword"))
1739 (repeat :tag "New syntax"
1740 (cons
1741 (choice
1742 :tag "Interpretation"
1743 (const :tag "Sequence (cycling hits every state)" sequence)
1744 (const :tag "Type (cycling directly to DONE)" type))
1745 (repeat
1746 (string :tag "Keyword"))))))
1748 (defvar org-todo-keywords-1 nil
1749 "All TODO and DONE keywords active in a buffer.")
1750 (make-variable-buffer-local 'org-todo-keywords-1)
1751 (defvar org-todo-keywords-for-agenda nil)
1752 (defvar org-done-keywords-for-agenda nil)
1753 (defvar org-not-done-keywords nil)
1754 (make-variable-buffer-local 'org-not-done-keywords)
1755 (defvar org-done-keywords nil)
1756 (make-variable-buffer-local 'org-done-keywords)
1757 (defvar org-todo-heads nil)
1758 (make-variable-buffer-local 'org-todo-heads)
1759 (defvar org-todo-sets nil)
1760 (make-variable-buffer-local 'org-todo-sets)
1761 (defvar org-todo-log-states nil)
1762 (make-variable-buffer-local 'org-todo-log-states)
1763 (defvar org-todo-kwd-alist nil)
1764 (make-variable-buffer-local 'org-todo-kwd-alist)
1765 (defvar org-todo-key-alist nil)
1766 (make-variable-buffer-local 'org-todo-key-alist)
1767 (defvar org-todo-key-trigger nil)
1768 (make-variable-buffer-local 'org-todo-key-trigger)
1770 (defcustom org-todo-interpretation 'sequence
1771 "Controls how TODO keywords are interpreted.
1772 This variable is in principle obsolete and is only used for
1773 backward compatibility, if the interpretation of todo keywords is
1774 not given already in `org-todo-keywords'. See that variable for
1775 more information."
1776 :group 'org-todo
1777 :group 'org-keywords
1778 :type '(choice (const sequence)
1779 (const type)))
1781 (defcustom org-use-fast-todo-selection 'prefix
1782 "Non-nil means, use the fast todo selection scheme with C-c C-t.
1783 This variable describes if and under what circumstances the cycling
1784 mechanism for TODO keywords will be replaced by a single-key, direct
1785 selection scheme.
1787 When nil, fast selection is never used.
1789 When the symbol `prefix', it will be used when `org-todo' is called with
1790 a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and `C-u t'
1791 in an agenda buffer.
1793 When t, fast selection is used by default. In this case, the prefix
1794 argument forces cycling instead.
1796 In all cases, the special interface is only used if access keys have actually
1797 been assigned by the user, i.e. if keywords in the configuration are followed
1798 by a letter in parenthesis, like TODO(t)."
1799 :group 'org-todo
1800 :type '(choice
1801 (const :tag "Never" nil)
1802 (const :tag "By default" t)
1803 (const :tag "Only with C-u C-c C-t" prefix)))
1805 (defcustom org-after-todo-state-change-hook nil
1806 "Hook which is run after the state of a TODO item was changed.
1807 The new state (a string with a TODO keyword, or nil) is available in the
1808 Lisp variable `state'."
1809 :group 'org-todo
1810 :type 'hook)
1812 (defcustom org-log-done nil
1813 "Non-nil means, record a CLOSED timestamp when moving an entry to DONE.
1814 When equal to the list (done), also prompt for a closing note.
1815 This can also be configured on a per-file basis by adding one of
1816 the following lines anywhere in the buffer:
1818 #+STARTUP: logdone
1819 #+STARTUP: lognotedone
1820 #+STARTUP: nologdone"
1821 :group 'org-todo
1822 :group 'org-progress
1823 :type '(choice
1824 (const :tag "No logging" nil)
1825 (const :tag "Record CLOSED timestamp" time)
1826 (const :tag "Record CLOSED timestamp with closing note." note)))
1828 ;; Normalize old uses of org-log-done.
1829 (cond
1830 ((eq org-log-done t) (setq org-log-done 'time))
1831 ((and (listp org-log-done) (memq 'done org-log-done))
1832 (setq org-log-done 'note)))
1834 ;; FIXME: document
1835 (defcustom org-log-note-clock-out nil
1836 "Non-nil means, recored a note when clocking out of an item.
1837 This can also be configured on a per-file basis by adding one of
1838 the following lines anywhere in the buffer:
1840 #+STARTUP: lognoteclock-out
1841 #+STARTUP: nolognoteclock-out"
1842 :group 'org-todo
1843 :group 'org-progress
1844 :type 'boolean)
1846 (defcustom org-log-done-with-time t
1847 "Non-nil means, the CLOSED time stamp will contain date and time.
1848 When nil, only the date will be recorded."
1849 :group 'org-progress
1850 :type 'boolean)
1852 (defcustom org-log-note-headings
1853 '((done . "CLOSING NOTE %t")
1854 (state . "State %-12s %t")
1855 (clock-out . ""))
1856 "Headings for notes added when clocking out or closing TODO items.
1857 The value is an alist, with the car being a symbol indicating the note
1858 context, and the cdr is the heading to be used. The heading may also be the
1859 empty string.
1860 %t in the heading will be replaced by a time stamp.
1861 %s will be replaced by the new TODO state, in double quotes.
1862 %u will be replaced by the user name.
1863 %U will be replaced by the full user name."
1864 :group 'org-todo
1865 :group 'org-progress
1866 :type '(list :greedy t
1867 (cons (const :tag "Heading when closing an item" done) string)
1868 (cons (const :tag
1869 "Heading when changing todo state (todo sequence only)"
1870 state) string)
1871 (cons (const :tag "Heading when clocking out" clock-out) string)))
1873 (defcustom org-log-states-order-reversed t
1874 "Non-nil means, the latest state change note will be directly after heading.
1875 When nil, the notes will be orderer according to time."
1876 :group 'org-todo
1877 :group 'org-progress
1878 :type 'boolean)
1880 (defcustom org-log-repeat 'time
1881 "Non-nil means, record moving through the DONE state when triggering repeat.
1882 An auto-repeating tasks is immediately switched back to TODO when marked
1883 done. If you are not logging state changes (by adding \"@\" or \"!\" to
1884 the TODO keyword definition, or recording a cloing note by setting
1885 `org-log-done', there will be no record of the task moving trhough DONE.
1886 This variable forces taking a note anyway. Possible values are:
1888 nil Don't force a record
1889 time Record a time stamp
1890 note Record a note
1892 This option can also be set with on a per-file-basis with
1894 #+STARTUP: logrepeat
1895 #+STARTUP: lognoterepeat
1896 #+STARTUP: nologrepeat
1898 You can have local logging settings for a subtree by setting the LOGGING
1899 property to one or more of these keywords."
1900 :group 'org-todo
1901 :group 'org-progress
1902 :type '(choice
1903 (const :tag "Don't force a record" nil)
1904 (const :tag "Force recording the DONE state" time)
1905 (const :tag "Force recording a note with the DONE state" note)))
1907 (defcustom org-clock-into-drawer 2
1908 "Should clocking info be wrapped into a drawer?
1909 When t, clocking info will always be inserted into a :CLOCK: drawer.
1910 If necessary, the drawer will be created.
1911 When nil, the drawer will not be created, but used when present.
1912 When an integer and the number of clocking entries in an item
1913 reaches or exceeds this number, a drawer will be created."
1914 :group 'org-todo
1915 :group 'org-progress
1916 :type '(choice
1917 (const :tag "Always" t)
1918 (const :tag "Only when drawer exists" nil)
1919 (integer :tag "When at least N clock entries")))
1921 (defcustom org-clock-out-when-done t
1922 "When t, the clock will be stopped when the relevant entry is marked DONE.
1923 Nil means, clock will keep running until stopped explicitly with
1924 `C-c C-x C-o', or until the clock is started in a different item."
1925 :group 'org-progress
1926 :type 'boolean)
1928 (defcustom org-clock-in-switch-to-state nil
1929 "Set task to a special todo state while clocking it.
1930 The value should be the state to which the entry should be switched."
1931 :group 'org-progress
1932 :group 'org-todo
1933 :type '(choice
1934 (const :tag "Don't force a state" nil)
1935 (string :tag "State")))
1937 (defgroup org-priorities nil
1938 "Priorities in Org-mode."
1939 :tag "Org Priorities"
1940 :group 'org-todo)
1942 (defcustom org-highest-priority ?A
1943 "The highest priority of TODO items. A character like ?A, ?B etc.
1944 Must have a smaller ASCII number than `org-lowest-priority'."
1945 :group 'org-priorities
1946 :type 'character)
1948 (defcustom org-lowest-priority ?C
1949 "The lowest priority of TODO items. A character like ?A, ?B etc.
1950 Must have a larger ASCII number than `org-highest-priority'."
1951 :group 'org-priorities
1952 :type 'character)
1954 (defcustom org-default-priority ?B
1955 "The default priority of TODO items.
1956 This is the priority an item get if no explicit priority is given."
1957 :group 'org-priorities
1958 :type 'character)
1960 (defcustom org-priority-start-cycle-with-default t
1961 "Non-nil means, start with default priority when starting to cycle.
1962 When this is nil, the first step in the cycle will be (depending on the
1963 command used) one higher or lower that the default priority."
1964 :group 'org-priorities
1965 :type 'boolean)
1967 (defgroup org-time nil
1968 "Options concerning time stamps and deadlines in Org-mode."
1969 :tag "Org Time"
1970 :group 'org)
1972 (defcustom org-insert-labeled-timestamps-at-point nil
1973 "Non-nil means, SCHEDULED and DEADLINE timestamps are inserted at point.
1974 When nil, these labeled time stamps are forces into the second line of an
1975 entry, just after the headline. When scheduling from the global TODO list,
1976 the time stamp will always be forced into the second line."
1977 :group 'org-time
1978 :type 'boolean)
1980 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
1981 "Formats for `format-time-string' which are used for time stamps.
1982 It is not recommended to change this constant.")
1984 (defcustom org-time-stamp-rounding-minutes '(0 5)
1985 "Number of minutes to round time stamps to.
1986 These are two values, the first applies when first creating a time stamp.
1987 The second applies when changing it with the commands `S-up' and `S-down'.
1988 When changing the time stamp, this means that it will change in steps
1989 of N minues, as given by the second value.
1991 When a setting is 0 or 1, insert the time unmodified. Useful rounding
1992 numbers should be factors of 60, so for example 5, 10, 15.
1994 When this is larger than 1, you can still force an exact time-stamp by using
1995 a double prefix argument to a time-stamp command like `C-c .' or `C-c !',
1996 and by using a prefix arg to `S-up/down' to specify the exact number
1997 of minutes to shift."
1998 :group 'org-time
1999 :get '(lambda (var) ; Make sure all entries have 5 elements
2000 (if (integerp (default-value var))
2001 (list (default-value var) 5)
2002 (default-value var)))
2003 :type '(list
2004 (integer :tag "when inserting times")
2005 (integer :tag "when modifying times")))
2007 ;; Make sure old customizations of this variable don't lead to problems.
2008 (when (integerp org-time-stamp-rounding-minutes)
2009 (setq org-time-stamp-rounding-minutes
2010 (list org-time-stamp-rounding-minutes
2011 org-time-stamp-rounding-minutes)))
2013 (defcustom org-display-custom-times nil
2014 "Non-nil means, overlay custom formats over all time stamps.
2015 The formats are defined through the variable `org-time-stamp-custom-formats'.
2016 To turn this on on a per-file basis, insert anywhere in the file:
2017 #+STARTUP: customtime"
2018 :group 'org-time
2019 :set 'set-default
2020 :type 'sexp)
2021 (make-variable-buffer-local 'org-display-custom-times)
2023 (defcustom org-time-stamp-custom-formats
2024 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
2025 "Custom formats for time stamps. See `format-time-string' for the syntax.
2026 These are overlayed over the default ISO format if the variable
2027 `org-display-custom-times' is set. Time like %H:%M should be at the
2028 end of the second format."
2029 :group 'org-time
2030 :type 'sexp)
2032 (defun org-time-stamp-format (&optional long inactive)
2033 "Get the right format for a time string."
2034 (let ((f (if long (cdr org-time-stamp-formats)
2035 (car org-time-stamp-formats))))
2036 (if inactive
2037 (concat "[" (substring f 1 -1) "]")
2038 f)))
2040 (defcustom org-read-date-prefer-future t
2041 "Non-nil means, assume future for incomplete date input from user.
2042 This affects the following situations:
2043 1. The user gives a day, but no month.
2044 For example, if today is the 15th, and you enter \"3\", Org-mode will
2045 read this as the third of *next* month. However, if you enter \"17\",
2046 it will be considered as *this* month.
2047 2. The user gives a month but not a year.
2048 For example, if it is april and you enter \"feb 2\", this will be read
2049 as feb 2, *next* year. \"May 5\", however, will be this year.
2051 When this option is nil, the current month and year will always be used
2052 as defaults."
2053 :group 'org-time
2054 :type 'boolean)
2056 (defcustom org-read-date-display-live t
2057 "Non-nil means, display current interpretation of date prompt live.
2058 This display will be in an overlay, in the minibuffer."
2059 :group 'org-time
2060 :type 'boolean)
2062 (defcustom org-read-date-popup-calendar t
2063 "Non-nil means, pop up a calendar when prompting for a date.
2064 In the calendar, the date can be selected with mouse-1. However, the
2065 minibuffer will also be active, and you can simply enter the date as well.
2066 When nil, only the minibuffer will be available."
2067 :group 'org-time
2068 :type 'boolean)
2069 (if (fboundp 'defvaralias)
2070 (defvaralias 'org-popup-calendar-for-date-prompt
2071 'org-read-date-popup-calendar))
2073 (defcustom org-extend-today-until 0
2074 "The hour when your day really ends.
2075 This has influence for the following applications:
2076 - When switching the agenda to \"today\". It it is still earlier than
2077 the time given here, the day recognized as TODAY is actually yesterday.
2078 - When a date is read from the user and it is still before the time given
2079 here, the current date and time will be assumed to be yesterday, 23:59.
2081 FIXME:
2082 IMPORTANT: This is still a very experimental feature, it may disappear
2083 again or it may be extended to mean more things."
2084 :group 'org-time
2085 :type 'number)
2087 (defcustom org-edit-timestamp-down-means-later nil
2088 "Non-nil means, S-down will increase the time in a time stamp.
2089 When nil, S-up will increase."
2090 :group 'org-time
2091 :type 'boolean)
2093 (defcustom org-calendar-follow-timestamp-change t
2094 "Non-nil means, make the calendar window follow timestamp changes.
2095 When a timestamp is modified and the calendar window is visible, it will be
2096 moved to the new date."
2097 :group 'org-time
2098 :type 'boolean)
2100 (defcustom org-clock-heading-function nil
2101 "When non-nil, should be a function to create `org-clock-heading'.
2102 This is the string shown in the mode line when a clock is running.
2103 The function is called with point at the beginning of the headline."
2104 :group 'org-time ; FIXME: Should we have a separate group????
2105 :type 'function)
2107 (defgroup org-tags nil
2108 "Options concerning tags in Org-mode."
2109 :tag "Org Tags"
2110 :group 'org)
2112 (defcustom org-tag-alist nil
2113 "List of tags allowed in Org-mode files.
2114 When this list is nil, Org-mode will base TAG input on what is already in the
2115 buffer.
2116 The value of this variable is an alist, the car of each entry must be a
2117 keyword as a string, the cdr may be a character that is used to select
2118 that tag through the fast-tag-selection interface.
2119 See the manual for details."
2120 :group 'org-tags
2121 :type '(repeat
2122 (choice
2123 (cons (string :tag "Tag name")
2124 (character :tag "Access char"))
2125 (const :tag "Start radio group" (:startgroup))
2126 (const :tag "End radio group" (:endgroup)))))
2128 (defcustom org-use-fast-tag-selection 'auto
2129 "Non-nil means, use fast tag selection scheme.
2130 This is a special interface to select and deselect tags with single keys.
2131 When nil, fast selection is never used.
2132 When the symbol `auto', fast selection is used if and only if selection
2133 characters for tags have been configured, either through the variable
2134 `org-tag-alist' or through a #+TAGS line in the buffer.
2135 When t, fast selection is always used and selection keys are assigned
2136 automatically if necessary."
2137 :group 'org-tags
2138 :type '(choice
2139 (const :tag "Always" t)
2140 (const :tag "Never" nil)
2141 (const :tag "When selection characters are configured" 'auto)))
2143 (defcustom org-fast-tag-selection-single-key nil
2144 "Non-nil means, fast tag selection exits after first change.
2145 When nil, you have to press RET to exit it.
2146 During fast tag selection, you can toggle this flag with `C-c'.
2147 This variable can also have the value `expert'. In this case, the window
2148 displaying the tags menu is not even shown, until you press C-c again."
2149 :group 'org-tags
2150 :type '(choice
2151 (const :tag "No" nil)
2152 (const :tag "Yes" t)
2153 (const :tag "Expert" expert)))
2155 (defvar org-fast-tag-selection-include-todo nil
2156 "Non-nil means, fast tags selection interface will also offer TODO states.
2157 This is an undocumented feature, you should not rely on it.")
2159 (defcustom org-tags-column -80
2160 "The column to which tags should be indented in a headline.
2161 If this number is positive, it specifies the column. If it is negative,
2162 it means that the tags should be flushright to that column. For example,
2163 -80 works well for a normal 80 character screen."
2164 :group 'org-tags
2165 :type 'integer)
2167 (defcustom org-auto-align-tags t
2168 "Non-nil means, realign tags after pro/demotion of TODO state change.
2169 These operations change the length of a headline and therefore shift
2170 the tags around. With this options turned on, after each such operation
2171 the tags are again aligned to `org-tags-column'."
2172 :group 'org-tags
2173 :type 'boolean)
2175 (defcustom org-use-tag-inheritance t
2176 "Non-nil means, tags in levels apply also for sublevels.
2177 When nil, only the tags directly given in a specific line apply there.
2178 If you turn off this option, you very likely want to turn on the
2179 companion option `org-tags-match-list-sublevels'."
2180 :group 'org-tags
2181 :type 'boolean)
2183 (defcustom org-tags-match-list-sublevels nil
2184 "Non-nil means list also sublevels of headlines matching tag search.
2185 Because of tag inheritance (see variable `org-use-tag-inheritance'),
2186 the sublevels of a headline matching a tag search often also match
2187 the same search. Listing all of them can create very long lists.
2188 Setting this variable to nil causes subtrees of a match to be skipped.
2189 This option is off by default, because inheritance in on. If you turn
2190 inheritance off, you very likely want to turn this option on.
2192 As a special case, if the tag search is restricted to TODO items, the
2193 value of this variable is ignored and sublevels are always checked, to
2194 make sure all corresponding TODO items find their way into the list."
2195 :group 'org-tags
2196 :type 'boolean)
2198 (defvar org-tags-history nil
2199 "History of minibuffer reads for tags.")
2200 (defvar org-last-tags-completion-table nil
2201 "The last used completion table for tags.")
2202 (defvar org-after-tags-change-hook nil
2203 "Hook that is run after the tags in a line have changed.")
2205 (defgroup org-properties nil
2206 "Options concerning properties in Org-mode."
2207 :tag "Org Properties"
2208 :group 'org)
2210 (defcustom org-property-format "%-10s %s"
2211 "How property key/value pairs should be formatted by `indent-line'.
2212 When `indent-line' hits a property definition, it will format the line
2213 according to this format, mainly to make sure that the values are
2214 lined-up with respect to each other."
2215 :group 'org-properties
2216 :type 'string)
2218 (defcustom org-use-property-inheritance nil
2219 "Non-nil means, properties apply also for sublevels.
2220 This setting is only relevant during property searches, not when querying
2221 an entry with `org-entry-get'. To retrieve a property with inheritance,
2222 you need to call `org-entry-get' with the inheritance flag.
2223 Turning this on can cause significant overhead when doing a search, so
2224 this is turned off by default.
2225 When nil, only the properties directly given in the current entry count.
2226 The value may also be a list of properties that shouldhave inheritance.
2228 However, note that some special properties use inheritance under special
2229 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
2230 and the properties ending in \"_ALL\" when they are used as descriptor
2231 for valid values of a property."
2232 :group 'org-properties
2233 :type '(choice
2234 (const :tag "Not" nil)
2235 (const :tag "Always" nil)
2236 (repeat :tag "Specific properties" (string :tag "Property"))))
2238 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
2239 "The default column format, if no other format has been defined.
2240 This variable can be set on the per-file basis by inserting a line
2242 #+COLUMNS: %25ITEM ....."
2243 :group 'org-properties
2244 :type 'string)
2246 (defcustom org-global-properties nil
2247 "List of property/value pairs that can be inherited by any entry.
2248 You can set buffer-local values for this by adding lines like
2250 #+PROPERTY: NAME VALUE"
2251 :group 'org-properties
2252 :type '(repeat
2253 (cons (string :tag "Property")
2254 (string :tag "Value"))))
2256 (defvar org-local-properties nil
2257 "List of property/value pairs that can be inherited by any entry.
2258 Valid for the current buffer.
2259 This variable is populated from #+PROPERTY lines.")
2261 (defgroup org-agenda nil
2262 "Options concerning agenda views in Org-mode."
2263 :tag "Org Agenda"
2264 :group 'org)
2266 (defvar org-category nil
2267 "Variable used by org files to set a category for agenda display.
2268 Such files should use a file variable to set it, for example
2270 # -*- mode: org; org-category: \"ELisp\"
2272 or contain a special line
2274 #+CATEGORY: ELisp
2276 If the file does not specify a category, then file's base name
2277 is used instead.")
2278 (make-variable-buffer-local 'org-category)
2280 (defcustom org-agenda-files nil
2281 "The files to be used for agenda display.
2282 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
2283 \\[org-remove-file]. You can also use customize to edit the list.
2285 If an entry is a directory, all files in that directory that are matched by
2286 `org-agenda-file-regexp' will be part of the file list.
2288 If the value of the variable is not a list but a single file name, then
2289 the list of agenda files is actually stored and maintained in that file, one
2290 agenda file per line."
2291 :group 'org-agenda
2292 :type '(choice
2293 (repeat :tag "List of files and directories" file)
2294 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
2296 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
2297 "Regular expression to match files for `org-agenda-files'.
2298 If any element in the list in that variable contains a directory instead
2299 of a normal file, all files in that directory that are matched by this
2300 regular expression will be included."
2301 :group 'org-agenda
2302 :type 'regexp)
2304 (defcustom org-agenda-skip-unavailable-files nil
2305 "t means to just skip non-reachable files in `org-agenda-files'.
2306 Nil means to remove them, after a query, from the list."
2307 :group 'org-agenda
2308 :type 'boolean)
2310 (defcustom org-agenda-text-search-extra-files nil
2311 "List of extra files to be searched by text search commands.
2312 These files will be search in addition to the agenda files bu the
2313 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
2314 Note that these files will only be searched for text search commands,
2315 not for the other agenda views like todo lists, tag earches or the weekly
2316 agenda. This variable is intended to list notes and possibly archive files
2317 that should also be searched by these two commands."
2318 :group 'org-agenda
2319 :type '(repeat file))
2321 (if (fboundp 'defvaralias)
2322 (defvaralias 'org-agenda-multi-occur-extra-files
2323 'org-agenda-text-search-extra-files))
2325 (defcustom org-agenda-confirm-kill 1
2326 "When set, remote killing from the agenda buffer needs confirmation.
2327 When t, a confirmation is always needed. When a number N, confirmation is
2328 only needed when the text to be killed contains more than N non-white lines."
2329 :group 'org-agenda
2330 :type '(choice
2331 (const :tag "Never" nil)
2332 (const :tag "Always" t)
2333 (number :tag "When more than N lines")))
2335 (defcustom org-calendar-to-agenda-key [?c]
2336 "The key to be installed in `calendar-mode-map' for switching to the agenda.
2337 The command `org-calendar-goto-agenda' will be bound to this key. The
2338 default is the character `c' because then `c' can be used to switch back and
2339 forth between agenda and calendar."
2340 :group 'org-agenda
2341 :type 'sexp)
2343 (defcustom org-agenda-compact-blocks nil
2344 "Non-nil means, make the block agenda more compact.
2345 This is done by leaving out unnecessary lines."
2346 :group 'org-agenda
2347 :type nil)
2349 (defgroup org-agenda-export nil
2350 "Options concerning exporting agenda views in Org-mode."
2351 :tag "Org Agenda Export"
2352 :group 'org-agenda)
2354 (defcustom org-agenda-with-colors t
2355 "Non-nil means, use colors in agenda views."
2356 :group 'org-agenda-export
2357 :type 'boolean)
2359 (defcustom org-agenda-exporter-settings nil
2360 "Alist of variable/value pairs that should be active during agenda export.
2361 This is a good place to set uptions for ps-print and for htmlize."
2362 :group 'org-agenda-export
2363 :type '(repeat
2364 (list
2365 (variable)
2366 (sexp :tag "Value"))))
2368 (defcustom org-agenda-export-html-style ""
2369 "The style specification for exported HTML Agenda files.
2370 If this variable contains a string, it will replace the default <style>
2371 section as produced by `htmlize'.
2372 Since there are different ways of setting style information, this variable
2373 needs to contain the full HTML structure to provide a style, including the
2374 surrounding HTML tags. The style specifications should include definitions
2375 the fonts used by the agenda, here is an example:
2377 <style type=\"text/css\">
2378 p { font-weight: normal; color: gray; }
2379 .org-agenda-structure {
2380 font-size: 110%;
2381 color: #003399;
2382 font-weight: 600;
2384 .org-todo {
2385 color: #cc6666;
2386 font-weight: bold;
2388 .org-done {
2389 color: #339933;
2391 .title { text-align: center; }
2392 .todo, .deadline { color: red; }
2393 .done { color: green; }
2394 </style>
2396 or, if you want to keep the style in a file,
2398 <link rel=\"stylesheet\" type=\"text/css\" href=\"mystyles.css\">
2400 As the value of this option simply gets inserted into the HTML <head> header,
2401 you can \"misuse\" it to also add other text to the header. However,
2402 <style>...</style> is required, if not present the variable will be ignored."
2403 :group 'org-agenda-export
2404 :group 'org-export-html
2405 :type 'string)
2407 (defgroup org-agenda-custom-commands nil
2408 "Options concerning agenda views in Org-mode."
2409 :tag "Org Agenda Custom Commands"
2410 :group 'org-agenda)
2412 (defconst org-sorting-choice
2413 '(choice
2414 (const time-up) (const time-down)
2415 (const category-keep) (const category-up) (const category-down)
2416 (const tag-down) (const tag-up)
2417 (const priority-up) (const priority-down))
2418 "Sorting choices.")
2420 (defconst org-agenda-custom-commands-local-options
2421 `(repeat :tag "Local settings for this command. Remember to quote values"
2422 (choice :tag "Setting"
2423 (list :tag "Any variable"
2424 (variable :tag "Variable")
2425 (sexp :tag "Value"))
2426 (list :tag "Files to be searched"
2427 (const org-agenda-files)
2428 (list
2429 (const :format "" quote)
2430 (repeat
2431 (file))))
2432 (list :tag "Sorting strategy"
2433 (const org-agenda-sorting-strategy)
2434 (list
2435 (const :format "" quote)
2436 (repeat
2437 ,org-sorting-choice)))
2438 (list :tag "Prefix format"
2439 (const org-agenda-prefix-format :value " %-12:c%?-12t% s")
2440 (string))
2441 (list :tag "Number of days in agenda"
2442 (const org-agenda-ndays)
2443 (integer :value 1))
2444 (list :tag "Fixed starting date"
2445 (const org-agenda-start-day)
2446 (string :value "2007-11-01"))
2447 (list :tag "Start on day of week"
2448 (const org-agenda-start-on-weekday)
2449 (choice :value 1
2450 (const :tag "Today" nil)
2451 (number :tag "Weekday No.")))
2452 (list :tag "Include data from diary"
2453 (const org-agenda-include-diary)
2454 (boolean))
2455 (list :tag "Deadline Warning days"
2456 (const org-deadline-warning-days)
2457 (integer :value 1))
2458 (list :tag "Standard skipping condition"
2459 :value (org-agenda-skip-function '(org-agenda-skip-entry-if))
2460 (const org-agenda-skip-function)
2461 (list
2462 (const :format "" quote)
2463 (list
2464 (choice
2465 :tag "Skiping range"
2466 (const :tag "Skip entry" org-agenda-skip-entry-if)
2467 (const :tag "Skip subtree" org-agenda-skip-subtree-if))
2468 (repeat :inline t :tag "Conditions for skipping"
2469 (choice
2470 :tag "Condition type"
2471 (list :tag "Regexp matches" :inline t (const :format "" 'regexp) (regexp))
2472 (list :tag "Regexp does not match" :inline t (const :format "" 'notregexp) (regexp))
2473 (const :tag "scheduled" 'scheduled)
2474 (const :tag "not scheduled" 'notscheduled)
2475 (const :tag "deadline" 'deadline)
2476 (const :tag "no deadline" 'notdeadline))))))
2477 (list :tag "Non-standard skipping condition"
2478 :value (org-agenda-skip-function)
2479 (list
2480 (const org-agenda-skip-function)
2481 (sexp :tag "Function or form (quoted!)")))))
2482 "Selection of examples for agenda command settings.
2483 This will be spliced into the custom type of
2484 `org-agenda-custom-commands'.")
2487 (defcustom org-agenda-custom-commands nil
2488 "Custom commands for the agenda.
2489 These commands will be offered on the splash screen displayed by the
2490 agenda dispatcher \\[org-agenda]. Each entry is a list like this:
2492 (key desc type match settings files)
2494 key The key (one or more characters as a string) to be associated
2495 with the command.
2496 desc A description of the command, when omitted or nil, a default
2497 description is built using MATCH.
2498 type The command type, any of the following symbols:
2499 agenda The daily/weekly agenda.
2500 todo Entries with a specific TODO keyword, in all agenda files.
2501 search Entries containing search words entry or headline.
2502 tags Tags/Property/TODO match in all agenda files.
2503 tags-todo Tags/P/T match in all agenda files, TODO entries only.
2504 todo-tree Sparse tree of specific TODO keyword in *current* file.
2505 tags-tree Sparse tree with all tags matches in *current* file.
2506 occur-tree Occur sparse tree for *current* file.
2507 ... A user-defined function.
2508 match What to search for:
2509 - a single keyword for TODO keyword searches
2510 - a tags match expression for tags searches
2511 - a word search expression for text searches.
2512 - a regular expression for occur searches
2513 For all other commands, this should be the empty string.
2514 settings A list of option settings, similar to that in a let form, so like
2515 this: ((opt1 val1) (opt2 val2) ...). The values will be
2516 evaluated at the moment of execution, so quote them when needed.
2517 files A list of files file to write the produced agenda buffer to
2518 with the command `org-store-agenda-views'.
2519 If a file name ends in \".html\", an HTML version of the buffer
2520 is written out. If it ends in \".ps\", a postscript version is
2521 produced. Otherwide, only the plain text is written to the file.
2523 You can also define a set of commands, to create a composite agenda buffer.
2524 In this case, an entry looks like this:
2526 (key desc (cmd1 cmd2 ...) general-settings-for-whole-set files)
2528 where
2530 desc A description string to be displayed in the dispatcher menu.
2531 cmd An agenda command, similar to the above. However, tree commands
2532 are no allowed, but instead you can get agenda and global todo list.
2533 So valid commands for a set are:
2534 (agenda \"\" settings)
2535 (alltodo \"\" settings)
2536 (stuck \"\" settings)
2537 (todo \"match\" settings files)
2538 (search \"match\" settings files)
2539 (tags \"match\" settings files)
2540 (tags-todo \"match\" settings files)
2542 Each command can carry a list of options, and another set of options can be
2543 given for the whole set of commands. Individual command options take
2544 precedence over the general options.
2546 When using several characters as key to a command, the first characters
2547 are prefix commands. For the dispatcher to display useful information, you
2548 should provide a description for the prefix, like
2550 (setq org-agenda-custom-commands
2551 '((\"h\" . \"HOME + Name tag searches\") ; describe prefix \"h\"
2552 (\"hl\" tags \"+HOME+Lisa\")
2553 (\"hp\" tags \"+HOME+Peter\")
2554 (\"hk\" tags \"+HOME+Kim\")))"
2555 :group 'org-agenda-custom-commands
2556 :type `(repeat
2557 (choice :value ("x" "Describe command here" tags "" nil)
2558 (list :tag "Single command"
2559 (string :tag "Access Key(s) ")
2560 (option (string :tag "Description"))
2561 (choice
2562 (const :tag "Agenda" agenda)
2563 (const :tag "TODO list" alltodo)
2564 (const :tag "Search words" search)
2565 (const :tag "Stuck projects" stuck)
2566 (const :tag "Tags search (all agenda files)" tags)
2567 (const :tag "Tags search of TODO entries (all agenda files)" tags-todo)
2568 (const :tag "TODO keyword search (all agenda files)" todo)
2569 (const :tag "Tags sparse tree (current buffer)" tags-tree)
2570 (const :tag "TODO keyword tree (current buffer)" todo-tree)
2571 (const :tag "Occur tree (current buffer)" occur-tree)
2572 (sexp :tag "Other, user-defined function"))
2573 (string :tag "Match (only for some commands)")
2574 ,org-agenda-custom-commands-local-options
2575 (option (repeat :tag "Export" (file :tag "Export to"))))
2576 (list :tag "Command series, all agenda files"
2577 (string :tag "Access Key(s)")
2578 (string :tag "Description ")
2579 (repeat :tag "Component"
2580 (choice
2581 (list :tag "Agenda"
2582 (const :format "" agenda)
2583 (const :tag "" :format "" "")
2584 ,org-agenda-custom-commands-local-options)
2585 (list :tag "TODO list (all keywords)"
2586 (const :format "" alltodo)
2587 (const :tag "" :format "" "")
2588 ,org-agenda-custom-commands-local-options)
2589 (list :tag "Search words"
2590 (const :format "" search)
2591 (string :tag "Match")
2592 ,org-agenda-custom-commands-local-options)
2593 (list :tag "Stuck projects"
2594 (const :format "" stuck)
2595 (const :tag "" :format "" "")
2596 ,org-agenda-custom-commands-local-options)
2597 (list :tag "Tags search"
2598 (const :format "" tags)
2599 (string :tag "Match")
2600 ,org-agenda-custom-commands-local-options)
2601 (list :tag "Tags search, TODO entries only"
2602 (const :format "" tags-todo)
2603 (string :tag "Match")
2604 ,org-agenda-custom-commands-local-options)
2605 (list :tag "TODO keyword search"
2606 (const :format "" todo)
2607 (string :tag "Match")
2608 ,org-agenda-custom-commands-local-options)
2609 (list :tag "Other, user-defined function"
2610 (symbol :tag "function")
2611 (string :tag "Match")
2612 ,org-agenda-custom-commands-local-options)))
2614 (repeat :tag "Settings for entire command set"
2615 (list (variable :tag "Any variable")
2616 (sexp :tag "Value")))
2617 (option (repeat :tag "Export" (file :tag "Export to"))))
2618 (cons :tag "Prefix key documentation"
2619 (string :tag "Access Key(s)")
2620 (string :tag "Description ")))))
2622 (defcustom org-agenda-query-register ?o
2623 "The register holding the current query string.
2624 The prupose of this is that if you construct a query string interactively,
2625 you can then use it to define a custom command."
2626 :group 'org-agenda-custom-commands
2627 :type 'character)
2629 (defcustom org-stuck-projects
2630 '("+LEVEL=2/-DONE" ("TODO" "NEXT" "NEXTACTION") nil "")
2631 "How to identify stuck projects.
2632 This is a list of four items:
2633 1. A tags/todo matcher string that is used to identify a project.
2634 The entire tree below a headline matched by this is considered one project.
2635 2. A list of TODO keywords identifying non-stuck projects.
2636 If the project subtree contains any headline with one of these todo
2637 keywords, the project is considered to be not stuck. If you specify
2638 \"*\" as a keyword, any TODO keyword will mark the project unstuck.
2639 3. A list of tags identifying non-stuck projects.
2640 If the project subtree contains any headline with one of these tags,
2641 the project is considered to be not stuck. If you specify \"*\" as
2642 a tag, any tag will mark the project unstuck.
2643 4. An arbitrary regular expression matching non-stuck projects.
2645 After defining this variable, you may use \\[org-agenda-list-stuck-projects]
2646 or `C-c a #' to produce the list."
2647 :group 'org-agenda-custom-commands
2648 :type '(list
2649 (string :tag "Tags/TODO match to identify a project")
2650 (repeat :tag "Projects are *not* stuck if they have an entry with TODO keyword any of" (string))
2651 (repeat :tag "Projects are *not* stuck if they have an entry with TAG being any of" (string))
2652 (regexp :tag "Projects are *not* stuck if this regexp matches\ninside the subtree")))
2655 (defgroup org-agenda-skip nil
2656 "Options concerning skipping parts of agenda files."
2657 :tag "Org Agenda Skip"
2658 :group 'org-agenda)
2660 (defcustom org-agenda-todo-list-sublevels t
2661 "Non-nil means, check also the sublevels of a TODO entry for TODO entries.
2662 When nil, the sublevels of a TODO entry are not checked, resulting in
2663 potentially much shorter TODO lists."
2664 :group 'org-agenda-skip
2665 :group 'org-todo
2666 :type 'boolean)
2668 (defcustom org-agenda-todo-ignore-with-date nil
2669 "Non-nil means, don't show entries with a date in the global todo list.
2670 You can use this if you prefer to mark mere appointments with a TODO keyword,
2671 but don't want them to show up in the TODO list.
2672 When this is set, it also covers deadlines and scheduled items, the settings
2673 of `org-agenda-todo-ignore-scheduled' and `org-agenda-todo-ignore-deadlines'
2674 will be ignored."
2675 :group 'org-agenda-skip
2676 :group 'org-todo
2677 :type 'boolean)
2679 (defcustom org-agenda-todo-ignore-scheduled nil
2680 "Non-nil means, don't show scheduled entries in the global todo list.
2681 The idea behind this is that by scheduling it, you have already taken care
2682 of this item.
2683 See also `org-agenda-todo-ignore-with-date'."
2684 :group 'org-agenda-skip
2685 :group 'org-todo
2686 :type 'boolean)
2688 (defcustom org-agenda-todo-ignore-deadlines nil
2689 "Non-nil means, don't show near deadline entries in the global todo list.
2690 Near means closer than `org-deadline-warning-days' days.
2691 The idea behind this is that such items will appear in the agenda anyway.
2692 See also `org-agenda-todo-ignore-with-date'."
2693 :group 'org-agenda-skip
2694 :group 'org-todo
2695 :type 'boolean)
2697 (defcustom org-agenda-skip-scheduled-if-done nil
2698 "Non-nil means don't show scheduled items in agenda when they are done.
2699 This is relevant for the daily/weekly agenda, not for the TODO list. And
2700 it applies only to the actual date of the scheduling. Warnings about
2701 an item with a past scheduling dates are always turned off when the item
2702 is DONE."
2703 :group 'org-agenda-skip
2704 :type 'boolean)
2706 (defcustom org-agenda-skip-deadline-if-done nil
2707 "Non-nil means don't show deadines when the corresponding item is done.
2708 When nil, the deadline is still shown and should give you a happy feeling.
2709 This is relevant for the daily/weekly agenda. And it applied only to the
2710 actualy date of the deadline. Warnings about approching and past-due
2711 deadlines are always turned off when the item is DONE."
2712 :group 'org-agenda-skip
2713 :type 'boolean)
2715 (defcustom org-agenda-skip-timestamp-if-done nil
2716 "Non-nil means don't select item by timestamp or -range if it is DONE."
2717 :group 'org-agenda-skip
2718 :type 'boolean)
2720 (defcustom org-timeline-show-empty-dates 3
2721 "Non-nil means, `org-timeline' also shows dates without an entry.
2722 When nil, only the days which actually have entries are shown.
2723 When t, all days between the first and the last date are shown.
2724 When an integer, show also empty dates, but if there is a gap of more than
2725 N days, just insert a special line indicating the size of the gap."
2726 :group 'org-agenda-skip
2727 :type '(choice
2728 (const :tag "None" nil)
2729 (const :tag "All" t)
2730 (number :tag "at most")))
2733 (defgroup org-agenda-startup nil
2734 "Options concerning initial settings in the Agenda in Org Mode."
2735 :tag "Org Agenda Startup"
2736 :group 'org-agenda)
2738 (defcustom org-finalize-agenda-hook nil
2739 "Hook run just before displaying an agenda buffer."
2740 :group 'org-agenda-startup
2741 :type 'hook)
2743 (defcustom org-agenda-mouse-1-follows-link nil
2744 "Non-nil means, mouse-1 on a link will follow the link in the agenda.
2745 A longer mouse click will still set point. Does not work on XEmacs.
2746 Needs to be set before org.el is loaded."
2747 :group 'org-agenda-startup
2748 :type 'boolean)
2750 (defcustom org-agenda-start-with-follow-mode nil
2751 "The initial value of follow-mode in a newly created agenda window."
2752 :group 'org-agenda-startup
2753 :type 'boolean)
2755 (defgroup org-agenda-windows nil
2756 "Options concerning the windows used by the Agenda in Org Mode."
2757 :tag "Org Agenda Windows"
2758 :group 'org-agenda)
2760 (defcustom org-agenda-window-setup 'reorganize-frame
2761 "How the agenda buffer should be displayed.
2762 Possible values for this option are:
2764 current-window Show agenda in the current window, keeping all other windows.
2765 other-frame Use `switch-to-buffer-other-frame' to display agenda.
2766 other-window Use `switch-to-buffer-other-window' to display agenda.
2767 reorganize-frame Show only two windows on the current frame, the current
2768 window and the agenda.
2769 See also the variable `org-agenda-restore-windows-after-quit'."
2770 :group 'org-agenda-windows
2771 :type '(choice
2772 (const current-window)
2773 (const other-frame)
2774 (const other-window)
2775 (const reorganize-frame)))
2777 (defcustom org-agenda-window-frame-fractions '(0.5 . 0.75)
2778 "The min and max height of the agenda window as a fraction of frame height.
2779 The value of the variable is a cons cell with two numbers between 0 and 1.
2780 It only matters if `org-agenda-window-setup' is `reorganize-frame'."
2781 :group 'org-agenda-windows
2782 :type '(cons (number :tag "Minimum") (number :tag "Maximum")))
2784 (defcustom org-agenda-restore-windows-after-quit nil
2785 "Non-nil means, restore window configuration open exiting agenda.
2786 Before the window configuration is changed for displaying the agenda,
2787 the current status is recorded. When the agenda is exited with
2788 `q' or `x' and this option is set, the old state is restored. If
2789 `org-agenda-window-setup' is `other-frame', the value of this
2790 option will be ignored.."
2791 :group 'org-agenda-windows
2792 :type 'boolean)
2794 (defcustom org-indirect-buffer-display 'other-window
2795 "How should indirect tree buffers be displayed?
2796 This applies to indirect buffers created with the commands
2797 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
2798 Valid values are:
2799 current-window Display in the current window
2800 other-window Just display in another window.
2801 dedicated-frame Create one new frame, and re-use it each time.
2802 new-frame Make a new frame each time. Note that in this case
2803 previously-made indirect buffers are kept, and you need to
2804 kill these buffers yourself."
2805 :group 'org-structure
2806 :group 'org-agenda-windows
2807 :type '(choice
2808 (const :tag "In current window" current-window)
2809 (const :tag "In current frame, other window" other-window)
2810 (const :tag "Each time a new frame" new-frame)
2811 (const :tag "One dedicated frame" dedicated-frame)))
2813 (defgroup org-agenda-daily/weekly nil
2814 "Options concerning the daily/weekly agenda."
2815 :tag "Org Agenda Daily/Weekly"
2816 :group 'org-agenda)
2818 (defcustom org-agenda-ndays 7
2819 "Number of days to include in overview display.
2820 Should be 1 or 7."
2821 :group 'org-agenda-daily/weekly
2822 :type 'number)
2824 (defcustom org-agenda-start-on-weekday 1
2825 "Non-nil means, start the overview always on the specified weekday.
2826 0 denotes Sunday, 1 denotes Monday etc.
2827 When nil, always start on the current day."
2828 :group 'org-agenda-daily/weekly
2829 :type '(choice (const :tag "Today" nil)
2830 (number :tag "Weekday No.")))
2832 (defcustom org-agenda-show-all-dates t
2833 "Non-nil means, `org-agenda' shows every day in the selected range.
2834 When nil, only the days which actually have entries are shown."
2835 :group 'org-agenda-daily/weekly
2836 :type 'boolean)
2838 (defcustom org-agenda-format-date 'org-agenda-format-date-aligned
2839 "Format string for displaying dates in the agenda.
2840 Used by the daily/weekly agenda and by the timeline. This should be
2841 a format string understood by `format-time-string', or a function returning
2842 the formatted date as a string. The function must take a single argument,
2843 a calendar-style date list like (month day year)."
2844 :group 'org-agenda-daily/weekly
2845 :type '(choice
2846 (string :tag "Format string")
2847 (function :tag "Function")))
2849 (defun org-agenda-format-date-aligned (date)
2850 "Format a date string for display in the daily/weekly agenda, or timeline.
2851 This function makes sure that dates are aligned for easy reading."
2852 (format "%-9s %2d %s %4d"
2853 (calendar-day-name date)
2854 (extract-calendar-day date)
2855 (calendar-month-name (extract-calendar-month date))
2856 (extract-calendar-year date)))
2858 (defcustom org-agenda-include-diary nil
2859 "If non-nil, include in the agenda entries from the Emacs Calendar's diary."
2860 :group 'org-agenda-daily/weekly
2861 :type 'boolean)
2863 (defcustom org-agenda-include-all-todo nil
2864 "Set means weekly/daily agenda will always contain all TODO entries.
2865 The TODO entries will be listed at the top of the agenda, before
2866 the entries for specific days."
2867 :group 'org-agenda-daily/weekly
2868 :type 'boolean)
2870 (defcustom org-agenda-repeating-timestamp-show-all t
2871 "Non-nil means, show all occurences of a repeating stamp in the agenda.
2872 When nil, only one occurence is shown, either today or the
2873 nearest into the future."
2874 :group 'org-agenda-daily/weekly
2875 :type 'boolean)
2877 (defcustom org-deadline-warning-days 14
2878 "No. of days before expiration during which a deadline becomes active.
2879 This variable governs the display in sparse trees and in the agenda.
2880 When 0 or negative, it means use this number (the absolute value of it)
2881 even if a deadline has a different individual lead time specified."
2882 :group 'org-time
2883 :group 'org-agenda-daily/weekly
2884 :type 'number)
2886 (defcustom org-scheduled-past-days 10000
2887 "No. of days to continue listing scheduled items that are not marked DONE.
2888 When an item is scheduled on a date, it shows up in the agenda on this
2889 day and will be listed until it is marked done for the number of days
2890 given here."
2891 :group 'org-agenda-daily/weekly
2892 :type 'number)
2894 (defgroup org-agenda-time-grid nil
2895 "Options concerning the time grid in the Org-mode Agenda."
2896 :tag "Org Agenda Time Grid"
2897 :group 'org-agenda)
2899 (defcustom org-agenda-use-time-grid t
2900 "Non-nil means, show a time grid in the agenda schedule.
2901 A time grid is a set of lines for specific times (like every two hours between
2902 8:00 and 20:00). The items scheduled for a day at specific times are
2903 sorted in between these lines.
2904 For details about when the grid will be shown, and what it will look like, see
2905 the variable `org-agenda-time-grid'."
2906 :group 'org-agenda-time-grid
2907 :type 'boolean)
2909 (defcustom org-agenda-time-grid
2910 '((daily today require-timed)
2911 "----------------"
2912 (800 1000 1200 1400 1600 1800 2000))
2914 "The settings for time grid for agenda display.
2915 This is a list of three items. The first item is again a list. It contains
2916 symbols specifying conditions when the grid should be displayed:
2918 daily if the agenda shows a single day
2919 weekly if the agenda shows an entire week
2920 today show grid on current date, independent of daily/weekly display
2921 require-timed show grid only if at least one item has a time specification
2923 The second item is a string which will be places behing the grid time.
2925 The third item is a list of integers, indicating the times that should have
2926 a grid line."
2927 :group 'org-agenda-time-grid
2928 :type
2929 '(list
2930 (set :greedy t :tag "Grid Display Options"
2931 (const :tag "Show grid in single day agenda display" daily)
2932 (const :tag "Show grid in weekly agenda display" weekly)
2933 (const :tag "Always show grid for today" today)
2934 (const :tag "Show grid only if any timed entries are present"
2935 require-timed)
2936 (const :tag "Skip grid times already present in an entry"
2937 remove-match))
2938 (string :tag "Grid String")
2939 (repeat :tag "Grid Times" (integer :tag "Time"))))
2941 (defgroup org-agenda-sorting nil
2942 "Options concerning sorting in the Org-mode Agenda."
2943 :tag "Org Agenda Sorting"
2944 :group 'org-agenda)
2946 (defcustom org-agenda-sorting-strategy
2947 '((agenda time-up category-keep priority-down)
2948 (todo category-keep priority-down)
2949 (tags category-keep priority-down)
2950 (search category-keep))
2951 "Sorting structure for the agenda items of a single day.
2952 This is a list of symbols which will be used in sequence to determine
2953 if an entry should be listed before another entry. The following
2954 symbols are recognized:
2956 time-up Put entries with time-of-day indications first, early first
2957 time-down Put entries with time-of-day indications first, late first
2958 category-keep Keep the default order of categories, corresponding to the
2959 sequence in `org-agenda-files'.
2960 category-up Sort alphabetically by category, A-Z.
2961 category-down Sort alphabetically by category, Z-A.
2962 tag-up Sort alphabetically by last tag, A-Z.
2963 tag-down Sort alphabetically by last tag, Z-A.
2964 priority-up Sort numerically by priority, high priority last.
2965 priority-down Sort numerically by priority, high priority first.
2967 The different possibilities will be tried in sequence, and testing stops
2968 if one comparison returns a \"not-equal\". For example, the default
2969 '(time-up category-keep priority-down)
2970 means: Pull out all entries having a specified time of day and sort them,
2971 in order to make a time schedule for the current day the first thing in the
2972 agenda listing for the day. Of the entries without a time indication, keep
2973 the grouped in categories, don't sort the categories, but keep them in
2974 the sequence given in `org-agenda-files'. Within each category sort by
2975 priority.
2977 Leaving out `category-keep' would mean that items will be sorted across
2978 categories by priority.
2980 Instead of a single list, this can also be a set of list for specific
2981 contents, with a context symbol in the car of the list, any of
2982 `agenda', `todo', `tags' for the corresponding agenda views."
2983 :group 'org-agenda-sorting
2984 :type `(choice
2985 (repeat :tag "General" ,org-sorting-choice)
2986 (list :tag "Individually"
2987 (cons (const :tag "Strategy for Weekly/Daily agenda" agenda)
2988 (repeat ,org-sorting-choice))
2989 (cons (const :tag "Strategy for TODO lists" todo)
2990 (repeat ,org-sorting-choice))
2991 (cons (const :tag "Strategy for Tags matches" tags)
2992 (repeat ,org-sorting-choice)))))
2994 (defcustom org-sort-agenda-notime-is-late t
2995 "Non-nil means, items without time are considered late.
2996 This is only relevant for sorting. When t, items which have no explicit
2997 time like 15:30 will be considered as 99:01, i.e. later than any items which
2998 do have a time. When nil, the default time is before 0:00. You can use this
2999 option to decide if the schedule for today should come before or after timeless
3000 agenda entries."
3001 :group 'org-agenda-sorting
3002 :type 'boolean)
3004 (defgroup org-agenda-line-format nil
3005 "Options concerning the entry prefix in the Org-mode agenda display."
3006 :tag "Org Agenda Line Format"
3007 :group 'org-agenda)
3009 (defcustom org-agenda-prefix-format
3010 '((agenda . " %-12:c%?-12t% s")
3011 (timeline . " % s")
3012 (todo . " %-12:c")
3013 (tags . " %-12:c")
3014 (search . " %-12:c"))
3015 "Format specifications for the prefix of items in the agenda views.
3016 An alist with four entries, for the different agenda types. The keys to the
3017 sublists are `agenda', `timeline', `todo', and `tags'. The values
3018 are format strings.
3019 This format works similar to a printf format, with the following meaning:
3021 %c the category of the item, \"Diary\" for entries from the diary, or
3022 as given by the CATEGORY keyword or derived from the file name.
3023 %T the *last* tag of the item. Last because inherited tags come
3024 first in the list.
3025 %t the time-of-day specification if one applies to the entry, in the
3026 format HH:MM
3027 %s Scheduling/Deadline information, a short string
3029 All specifiers work basically like the standard `%s' of printf, but may
3030 contain two additional characters: A question mark just after the `%' and
3031 a whitespace/punctuation character just before the final letter.
3033 If the first character after `%' is a question mark, the entire field
3034 will only be included if the corresponding value applies to the
3035 current entry. This is useful for fields which should have fixed
3036 width when present, but zero width when absent. For example,
3037 \"%?-12t\" will result in a 12 character time field if a time of the
3038 day is specified, but will completely disappear in entries which do
3039 not contain a time.
3041 If there is punctuation or whitespace character just before the final
3042 format letter, this character will be appended to the field value if
3043 the value is not empty. For example, the format \"%-12:c\" leads to
3044 \"Diary: \" if the category is \"Diary\". If the category were be
3045 empty, no additional colon would be interted.
3047 The default value of this option is \" %-12:c%?-12t% s\", meaning:
3048 - Indent the line with two space characters
3049 - Give the category in a 12 chars wide field, padded with whitespace on
3050 the right (because of `-'). Append a colon if there is a category
3051 (because of `:').
3052 - If there is a time-of-day, put it into a 12 chars wide field. If no
3053 time, don't put in an empty field, just skip it (because of '?').
3054 - Finally, put the scheduling information and append a whitespace.
3056 As another example, if you don't want the time-of-day of entries in
3057 the prefix, you could use:
3059 (setq org-agenda-prefix-format \" %-11:c% s\")
3061 See also the variables `org-agenda-remove-times-when-in-prefix' and
3062 `org-agenda-remove-tags'."
3063 :type '(choice
3064 (string :tag "General format")
3065 (list :greedy t :tag "View dependent"
3066 (cons (const agenda) (string :tag "Format"))
3067 (cons (const timeline) (string :tag "Format"))
3068 (cons (const todo) (string :tag "Format"))
3069 (cons (const tags) (string :tag "Format"))
3070 (cons (const search) (string :tag "Format"))))
3071 :group 'org-agenda-line-format)
3073 (defvar org-prefix-format-compiled nil
3074 "The compiled version of the most recently used prefix format.
3075 See the variable `org-agenda-prefix-format'.")
3077 (defcustom org-agenda-todo-keyword-format "%-1s"
3078 "Format for the TODO keyword in agenda lines.
3079 Set this to something like \"%-12s\" if you want all TODO keywords
3080 to occupy a fixed space in the agenda display."
3081 :group 'org-agenda-line-format
3082 :type 'string)
3084 (defcustom org-agenda-scheduled-leaders '("Scheduled: " "Sched.%2dx: ")
3085 "Text preceeding scheduled items in the agenda view.
3086 This is a list with two strings. The first applies when the item is
3087 scheduled on the current day. The second applies when it has been scheduled
3088 previously, it may contain a %d to capture how many days ago the item was
3089 scheduled."
3090 :group 'org-agenda-line-format
3091 :type '(list
3092 (string :tag "Scheduled today ")
3093 (string :tag "Scheduled previously")))
3095 (defcustom org-agenda-deadline-leaders '("Deadline: " "In %3d d.: ")
3096 "Text preceeding deadline items in the agenda view.
3097 This is a list with two strings. The first applies when the item has its
3098 deadline on the current day. The second applies when it is in the past or
3099 in the future, it may contain %d to capture how many days away the deadline
3100 is (was)."
3101 :group 'org-agenda-line-format
3102 :type '(list
3103 (string :tag "Deadline today ")
3104 (string :tag "Deadline relative")))
3106 (defcustom org-agenda-remove-times-when-in-prefix t
3107 "Non-nil means, remove duplicate time specifications in agenda items.
3108 When the format `org-agenda-prefix-format' contains a `%t' specifier, a
3109 time-of-day specification in a headline or diary entry is extracted and
3110 placed into the prefix. If this option is non-nil, the original specification
3111 \(a timestamp or -range, or just a plain time(range) specification like
3112 11:30-4pm) will be removed for agenda display. This makes the agenda less
3113 cluttered.
3114 The option can be t or nil. It may also be the symbol `beg', indicating
3115 that the time should only be removed what it is located at the beginning of
3116 the headline/diary entry."
3117 :group 'org-agenda-line-format
3118 :type '(choice
3119 (const :tag "Always" t)
3120 (const :tag "Never" nil)
3121 (const :tag "When at beginning of entry" beg)))
3124 (defcustom org-agenda-default-appointment-duration nil
3125 "Default duration for appointments that only have a starting time.
3126 When nil, no duration is specified in such cases.
3127 When non-nil, this must be the number of minutes, e.g. 60 for one hour."
3128 :group 'org-agenda-line-format
3129 :type '(choice
3130 (integer :tag "Minutes")
3131 (const :tag "No default duration")))
3134 (defcustom org-agenda-remove-tags nil
3135 "Non-nil means, remove the tags from the headline copy in the agenda.
3136 When this is the symbol `prefix', only remove tags when
3137 `org-agenda-prefix-format' contains a `%T' specifier."
3138 :group 'org-agenda-line-format
3139 :type '(choice
3140 (const :tag "Always" t)
3141 (const :tag "Never" nil)
3142 (const :tag "When prefix format contains %T" prefix)))
3144 (if (fboundp 'defvaralias)
3145 (defvaralias 'org-agenda-remove-tags-when-in-prefix
3146 'org-agenda-remove-tags))
3148 (defcustom org-agenda-tags-column -80
3149 "Shift tags in agenda items to this column.
3150 If this number is positive, it specifies the column. If it is negative,
3151 it means that the tags should be flushright to that column. For example,
3152 -80 works well for a normal 80 character screen."
3153 :group 'org-agenda-line-format
3154 :type 'integer)
3156 (if (fboundp 'defvaralias)
3157 (defvaralias 'org-agenda-align-tags-to-column 'org-agenda-tags-column))
3159 (defcustom org-agenda-fontify-priorities t
3160 "Non-nil means, highlight low and high priorities in agenda.
3161 When t, the highest priority entries are bold, lowest priority italic.
3162 This may also be an association list of priority faces. The face may be
3163 a names face, or a list like `(:background \"Red\")'."
3164 :group 'org-agenda-line-format
3165 :type '(choice
3166 (const :tag "Never" nil)
3167 (const :tag "Defaults" t)
3168 (repeat :tag "Specify"
3169 (list (character :tag "Priority" :value ?A)
3170 (sexp :tag "face")))))
3172 (defgroup org-latex nil
3173 "Options for embedding LaTeX code into Org-mode"
3174 :tag "Org LaTeX"
3175 :group 'org)
3177 (defcustom org-format-latex-options
3178 '(:foreground default :background default :scale 1.0
3179 :html-foreground "Black" :html-background "Transparent" :html-scale 1.0
3180 :matchers ("begin" "$" "$$" "\\(" "\\["))
3181 "Options for creating images from LaTeX fragments.
3182 This is a property list with the following properties:
3183 :foreground the foreground color for images embedded in emacs, e.g. \"Black\".
3184 `default' means use the forground of the default face.
3185 :background the background color, or \"Transparent\".
3186 `default' means use the background of the default face.
3187 :scale a scaling factor for the size of the images
3188 :html-foreground, :html-background, :html-scale
3189 The same numbers for HTML export.
3190 :matchers a list indicating which matchers should be used to
3191 find LaTeX fragments. Valid members of this list are:
3192 \"begin\" find environments
3193 \"$\" find math expressions surrounded by $...$
3194 \"$$\" find math expressions surrounded by $$....$$
3195 \"\\(\" find math expressions surrounded by \\(...\\)
3196 \"\\ [\" find math expressions surrounded by \\ [...\\]"
3197 :group 'org-latex
3198 :type 'plist)
3200 (defcustom org-format-latex-header "\\documentclass{article}
3201 \\usepackage{fullpage} % do not remove
3202 \\usepackage{amssymb}
3203 \\usepackage[usenames]{color}
3204 \\usepackage{amsmath}
3205 \\usepackage{latexsym}
3206 \\usepackage[mathscr]{eucal}
3207 \\pagestyle{empty} % do not remove"
3208 "The document header used for processing LaTeX fragments."
3209 :group 'org-latex
3210 :type 'string)
3212 (defgroup org-export nil
3213 "Options for exporting org-listings."
3214 :tag "Org Export"
3215 :group 'org)
3217 (defgroup org-export-general nil
3218 "General options for exporting Org-mode files."
3219 :tag "Org Export General"
3220 :group 'org-export)
3222 ;; FIXME
3223 (defvar org-export-publishing-directory nil)
3225 (defcustom org-export-with-special-strings t
3226 "Non-nil means, interpret \"\-\", \"--\" and \"---\" for export.
3227 When this option is turned on, these strings will be exported as:
3229 Org HTML LaTeX
3230 -----+----------+--------
3231 \\- &shy; \\-
3232 -- &ndash; --
3233 --- &mdash; ---
3234 ... &hellip; \ldots
3236 This option can also be set with the +OPTIONS line, e.g. \"-:nil\"."
3237 :group 'org-export-translation
3238 :type 'boolean)
3240 (defcustom org-export-language-setup
3241 '(("en" "Author" "Date" "Table of Contents")
3242 ("cs" "Autor" "Datum" "Obsah")
3243 ("da" "Ophavsmand" "Dato" "Indhold")
3244 ("de" "Autor" "Datum" "Inhaltsverzeichnis")
3245 ("es" "Autor" "Fecha" "\xcdndice")
3246 ("fr" "Auteur" "Date" "Table des mati\xe8res")
3247 ("it" "Autore" "Data" "Indice")
3248 ("nl" "Auteur" "Datum" "Inhoudsopgave")
3249 ("nn" "Forfattar" "Dato" "Innhold") ;; nn = Norsk (nynorsk)
3250 ("sv" "F\xf6rfattarens" "Datum" "Inneh\xe5ll"))
3251 "Terms used in export text, translated to different languages.
3252 Use the variable `org-export-default-language' to set the language,
3253 or use the +OPTION lines for a per-file setting."
3254 :group 'org-export-general
3255 :type '(repeat
3256 (list
3257 (string :tag "HTML language tag")
3258 (string :tag "Author")
3259 (string :tag "Date")
3260 (string :tag "Table of Contents"))))
3262 (defcustom org-export-default-language "en"
3263 "The default language of HTML export, as a string.
3264 This should have an association in `org-export-language-setup'."
3265 :group 'org-export-general
3266 :type 'string)
3268 (defcustom org-export-skip-text-before-1st-heading t
3269 "Non-nil means, skip all text before the first headline when exporting.
3270 When nil, that text is exported as well."
3271 :group 'org-export-general
3272 :type 'boolean)
3274 (defcustom org-export-headline-levels 3
3275 "The last level which is still exported as a headline.
3276 Inferior levels will produce itemize lists when exported.
3277 Note that a numeric prefix argument to an exporter function overrides
3278 this setting.
3280 This option can also be set with the +OPTIONS line, e.g. \"H:2\"."
3281 :group 'org-export-general
3282 :type 'number)
3284 (defcustom org-export-with-section-numbers t
3285 "Non-nil means, add section numbers to headlines when exporting.
3287 This option can also be set with the +OPTIONS line, e.g. \"num:t\"."
3288 :group 'org-export-general
3289 :type 'boolean)
3291 (defcustom org-export-with-toc t
3292 "Non-nil means, create a table of contents in exported files.
3293 The TOC contains headlines with levels up to`org-export-headline-levels'.
3294 When an integer, include levels up to N in the toc, this may then be
3295 different from `org-export-headline-levels', but it will not be allowed
3296 to be larger than the number of headline levels.
3297 When nil, no table of contents is made.
3299 Headlines which contain any TODO items will be marked with \"(*)\" in
3300 ASCII export, and with red color in HTML output, if the option
3301 `org-export-mark-todo-in-toc' is set.
3303 In HTML output, the TOC will be clickable.
3305 This option can also be set with the +OPTIONS line, e.g. \"toc:nil\"
3306 or \"toc:3\"."
3307 :group 'org-export-general
3308 :type '(choice
3309 (const :tag "No Table of Contents" nil)
3310 (const :tag "Full Table of Contents" t)
3311 (integer :tag "TOC to level")))
3313 (defcustom org-export-mark-todo-in-toc nil
3314 "Non-nil means, mark TOC lines that contain any open TODO items."
3315 :group 'org-export-general
3316 :type 'boolean)
3318 (defcustom org-export-preserve-breaks nil
3319 "Non-nil means, preserve all line breaks when exporting.
3320 Normally, in HTML output paragraphs will be reformatted. In ASCII
3321 export, line breaks will always be preserved, regardless of this variable.
3323 This option can also be set with the +OPTIONS line, e.g. \"\\n:t\"."
3324 :group 'org-export-general
3325 :type 'boolean)
3327 (defcustom org-export-with-archived-trees 'headline
3328 "Whether subtrees with the ARCHIVE tag should be exported.
3329 This can have three different values
3330 nil Do not export, pretend this tree is not present
3331 t Do export the entire tree
3332 headline Only export the headline, but skip the tree below it."
3333 :group 'org-export-general
3334 :group 'org-archive
3335 :type '(choice
3336 (const :tag "not at all" nil)
3337 (const :tag "headline only" 'headline)
3338 (const :tag "entirely" t)))
3340 (defcustom org-export-author-info t
3341 "Non-nil means, insert author name and email into the exported file.
3343 This option can also be set with the +OPTIONS line,
3344 e.g. \"author-info:nil\"."
3345 :group 'org-export-general
3346 :type 'boolean)
3348 (defcustom org-export-time-stamp-file t
3349 "Non-nil means, insert a time stamp into the exported file.
3350 The time stamp shows when the file was created.
3352 This option can also be set with the +OPTIONS line,
3353 e.g. \"timestamp:nil\"."
3354 :group 'org-export-general
3355 :type 'boolean)
3357 (defcustom org-export-with-timestamps t
3358 "If nil, do not export time stamps and associated keywords."
3359 :group 'org-export-general
3360 :type 'boolean)
3362 (defcustom org-export-remove-timestamps-from-toc t
3363 "If nil, remove timestamps from the table of contents entries."
3364 :group 'org-export-general
3365 :type 'boolean)
3367 (defcustom org-export-with-tags 'not-in-toc
3368 "If nil, do not export tags, just remove them from headlines.
3369 If this is the symbol `not-in-toc', tags will be removed from table of
3370 contents entries, but still be shown in the headlines of the document.
3372 This option can also be set with the +OPTIONS line, e.g. \"tags:nil\"."
3373 :group 'org-export-general
3374 :type '(choice
3375 (const :tag "Off" nil)
3376 (const :tag "Not in TOC" not-in-toc)
3377 (const :tag "On" t)))
3379 (defcustom org-export-with-drawers nil
3380 "Non-nil means, export with drawers like the property drawer.
3381 When t, all drawers are exported. This may also be a list of
3382 drawer names to export."
3383 :group 'org-export-general
3384 :type '(choice
3385 (const :tag "All drawers" t)
3386 (const :tag "None" nil)
3387 (repeat :tag "Selected drawers"
3388 (string :tag "Drawer name"))))
3390 (defgroup org-export-translation nil
3391 "Options for translating special ascii sequences for the export backends."
3392 :tag "Org Export Translation"
3393 :group 'org-export)
3395 (defcustom org-export-with-emphasize t
3396 "Non-nil means, interpret *word*, /word/, and _word_ as emphasized text.
3397 If the export target supports emphasizing text, the word will be
3398 typeset in bold, italic, or underlined, respectively. Works only for
3399 single words, but you can say: I *really* *mean* *this*.
3400 Not all export backends support this.
3402 This option can also be set with the +OPTIONS line, e.g. \"*:nil\"."
3403 :group 'org-export-translation
3404 :type 'boolean)
3406 (defcustom org-export-with-footnotes t
3407 "If nil, export [1] as a footnote marker.
3408 Lines starting with [1] will be formatted as footnotes.
3410 This option can also be set with the +OPTIONS line, e.g. \"f:nil\"."
3411 :group 'org-export-translation
3412 :type 'boolean)
3414 (defcustom org-export-with-sub-superscripts t
3415 "Non-nil means, interpret \"_\" and \"^\" for export.
3416 When this option is turned on, you can use TeX-like syntax for sub- and
3417 superscripts. Several characters after \"_\" or \"^\" will be
3418 considered as a single item - so grouping with {} is normally not
3419 needed. For example, the following things will be parsed as single
3420 sub- or superscripts.
3422 10^24 or 10^tau several digits will be considered 1 item.
3423 10^-12 or 10^-tau a leading sign with digits or a word
3424 x^2-y^3 will be read as x^2 - y^3, because items are
3425 terminated by almost any nonword/nondigit char.
3426 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
3428 Still, ambiguity is possible - so when in doubt use {} to enclose the
3429 sub/superscript. If you set this variable to the symbol `{}',
3430 the braces are *required* in order to trigger interpretations as
3431 sub/superscript. This can be helpful in documents that need \"_\"
3432 frequently in plain text.
3434 Not all export backends support this, but HTML does.
3436 This option can also be set with the +OPTIONS line, e.g. \"^:nil\"."
3437 :group 'org-export-translation
3438 :type '(choice
3439 (const :tag "Always interpret" t)
3440 (const :tag "Only with braces" {})
3441 (const :tag "Never interpret" nil)))
3443 (defcustom org-export-with-special-strings t
3444 "Non-nil means, interpret \"\-\", \"--\" and \"---\" for export.
3445 When this option is turned on, these strings will be exported as:
3447 \\- : &shy;
3448 -- : &ndash;
3449 --- : &mdash;
3451 Not all export backends support this, but HTML does.
3453 This option can also be set with the +OPTIONS line, e.g. \"-:nil\"."
3454 :group 'org-export-translation
3455 :type 'boolean)
3457 (defcustom org-export-with-TeX-macros t
3458 "Non-nil means, interpret simple TeX-like macros when exporting.
3459 For example, HTML export converts \\alpha to &alpha; and \\AA to &Aring;.
3460 No only real TeX macros will work here, but the standard HTML entities
3461 for math can be used as macro names as well. For a list of supported
3462 names in HTML export, see the constant `org-html-entities'.
3463 Not all export backends support this.
3465 This option can also be set with the +OPTIONS line, e.g. \"TeX:nil\"."
3466 :group 'org-export-translation
3467 :group 'org-export-latex
3468 :type 'boolean)
3470 (defcustom org-export-with-LaTeX-fragments nil
3471 "Non-nil means, convert LaTeX fragments to images when exporting to HTML.
3472 When set, the exporter will find LaTeX environments if the \\begin line is
3473 the first non-white thing on a line. It will also find the math delimiters
3474 like $a=b$ and \\( a=b \\) for inline math, $$a=b$$ and \\[ a=b \\] for
3475 display math.
3477 This option can also be set with the +OPTIONS line, e.g. \"LaTeX:t\"."
3478 :group 'org-export-translation
3479 :group 'org-export-latex
3480 :type 'boolean)
3482 (defcustom org-export-with-fixed-width t
3483 "Non-nil means, lines starting with \":\" will be in fixed width font.
3484 This can be used to have pre-formatted text, fragments of code etc. For
3485 example:
3486 : ;; Some Lisp examples
3487 : (while (defc cnt)
3488 : (ding))
3489 will be looking just like this in also HTML. See also the QUOTE keyword.
3490 Not all export backends support this.
3492 This option can also be set with the +OPTIONS line, e.g. \"::nil\"."
3493 :group 'org-export-translation
3494 :type 'boolean)
3496 (defcustom org-match-sexp-depth 3
3497 "Number of stacked braces for sub/superscript matching.
3498 This has to be set before loading org.el to be effective."
3499 :group 'org-export-translation
3500 :type 'integer)
3502 (defgroup org-export-tables nil
3503 "Options for exporting tables in Org-mode."
3504 :tag "Org Export Tables"
3505 :group 'org-export)
3507 (defcustom org-export-with-tables t
3508 "If non-nil, lines starting with \"|\" define a table.
3509 For example:
3511 | Name | Address | Birthday |
3512 |-------------+----------+-----------|
3513 | Arthur Dent | England | 29.2.2100 |
3515 Not all export backends support this.
3517 This option can also be set with the +OPTIONS line, e.g. \"|:nil\"."
3518 :group 'org-export-tables
3519 :type 'boolean)
3521 (defcustom org-export-highlight-first-table-line t
3522 "Non-nil means, highlight the first table line.
3523 In HTML export, this means use <th> instead of <td>.
3524 In tables created with table.el, this applies to the first table line.
3525 In Org-mode tables, all lines before the first horizontal separator
3526 line will be formatted with <th> tags."
3527 :group 'org-export-tables
3528 :type 'boolean)
3530 (defcustom org-export-table-remove-special-lines t
3531 "Remove special lines and marking characters in calculating tables.
3532 This removes the special marking character column from tables that are set
3533 up for spreadsheet calculations. It also removes the entire lines
3534 marked with `!', `_', or `^'. The lines with `$' are kept, because
3535 the values of constants may be useful to have."
3536 :group 'org-export-tables
3537 :type 'boolean)
3539 (defcustom org-export-prefer-native-exporter-for-tables nil
3540 "Non-nil means, always export tables created with table.el natively.
3541 Natively means, use the HTML code generator in table.el.
3542 When nil, Org-mode's own HTML generator is used when possible (i.e. if
3543 the table does not use row- or column-spanning). This has the
3544 advantage, that the automatic HTML conversions for math symbols and
3545 sub/superscripts can be applied. Org-mode's HTML generator is also
3546 much faster."
3547 :group 'org-export-tables
3548 :type 'boolean)
3550 (defgroup org-export-ascii nil
3551 "Options specific for ASCII export of Org-mode files."
3552 :tag "Org Export ASCII"
3553 :group 'org-export)
3555 (defcustom org-export-ascii-underline '(?\$ ?\# ?^ ?\~ ?\= ?\-)
3556 "Characters for underlining headings in ASCII export.
3557 In the given sequence, these characters will be used for level 1, 2, ..."
3558 :group 'org-export-ascii
3559 :type '(repeat character))
3561 (defcustom org-export-ascii-bullets '(?* ?+ ?-)
3562 "Bullet characters for headlines converted to lists in ASCII export.
3563 The first character is used for the first lest level generated in this
3564 way, and so on. If there are more levels than characters given here,
3565 the list will be repeated.
3566 Note that plain lists will keep the same bullets as the have in the
3567 Org-mode file."
3568 :group 'org-export-ascii
3569 :type '(repeat character))
3571 (defgroup org-export-xml nil
3572 "Options specific for XML export of Org-mode files."
3573 :tag "Org Export XML"
3574 :group 'org-export)
3576 (defgroup org-export-html nil
3577 "Options specific for HTML export of Org-mode files."
3578 :tag "Org Export HTML"
3579 :group 'org-export)
3581 (defcustom org-export-html-coding-system nil
3583 :group 'org-export-html
3584 :type 'coding-system)
3586 (defcustom org-export-html-extension "html"
3587 "The extension for exported HTML files."
3588 :group 'org-export-html
3589 :type 'string)
3591 (defcustom org-export-html-style
3592 "<style type=\"text/css\">
3593 html {
3594 font-family: Times, serif;
3595 font-size: 12pt;
3597 .title { text-align: center; }
3598 .todo { color: red; }
3599 .done { color: green; }
3600 .timestamp { color: grey }
3601 .timestamp-kwd { color: CadetBlue }
3602 .tag { background-color:lightblue; font-weight:normal }
3603 .target { background-color: lavender; }
3604 pre {
3605 border: 1pt solid #AEBDCC;
3606 background-color: #F3F5F7;
3607 padding: 5pt;
3608 font-family: courier, monospace;
3610 table { border-collapse: collapse; }
3611 td, th {
3612 vertical-align: top;
3613 <!--border: 1pt solid #ADB9CC;-->
3615 </style>"
3616 "The default style specification for exported HTML files.
3617 Since there are different ways of setting style information, this variable
3618 needs to contain the full HTML structure to provide a style, including the
3619 surrounding HTML tags. The style specifications should include definitions
3620 for new classes todo, done, title, and deadline. For example, valid values
3621 would be:
3623 <style type=\"text/css\">
3624 p { font-weight: normal; color: gray; }
3625 h1 { color: black; }
3626 .title { text-align: center; }
3627 .todo, .deadline { color: red; }
3628 .done { color: green; }
3629 </style>
3631 or, if you want to keep the style in a file,
3633 <link rel=\"stylesheet\" type=\"text/css\" href=\"mystyles.css\">
3635 As the value of this option simply gets inserted into the HTML <head> header,
3636 you can \"misuse\" it to add arbitrary text to the header."
3637 :group 'org-export-html
3638 :type 'string)
3641 (defcustom org-export-html-title-format "<h1 class=\"title\">%s</h1>\n"
3642 "Format for typesetting the document title in HTML export."
3643 :group 'org-export-html
3644 :type 'string)
3646 (defcustom org-export-html-toplevel-hlevel 2
3647 "The <H> level for level 1 headings in HTML export."
3648 :group 'org-export-html
3649 :type 'string)
3651 (defcustom org-export-html-link-org-files-as-html t
3652 "Non-nil means, make file links to `file.org' point to `file.html'.
3653 When org-mode is exporting an org-mode file to HTML, links to
3654 non-html files are directly put into a href tag in HTML.
3655 However, links to other Org-mode files (recognized by the
3656 extension `.org.) should become links to the corresponding html
3657 file, assuming that the linked org-mode file will also be
3658 converted to HTML.
3659 When nil, the links still point to the plain `.org' file."
3660 :group 'org-export-html
3661 :type 'boolean)
3663 (defcustom org-export-html-inline-images 'maybe
3664 "Non-nil means, inline images into exported HTML pages.
3665 This is done using an <img> tag. When nil, an anchor with href is used to
3666 link to the image. If this option is `maybe', then images in links with
3667 an empty description will be inlined, while images with a description will
3668 be linked only."
3669 :group 'org-export-html
3670 :type '(choice (const :tag "Never" nil)
3671 (const :tag "Always" t)
3672 (const :tag "When there is no description" maybe)))
3674 ;; FIXME: rename
3675 (defcustom org-export-html-expand t
3676 "Non-nil means, for HTML export, treat @<...> as HTML tag.
3677 When nil, these tags will be exported as plain text and therefore
3678 not be interpreted by a browser.
3680 This option can also be set with the +OPTIONS line, e.g. \"@:nil\"."
3681 :group 'org-export-html
3682 :type 'boolean)
3684 (defcustom org-export-html-table-tag
3685 "<table border=\"2\" cellspacing=\"0\" cellpadding=\"6\" rules=\"groups\" frame=\"hsides\">"
3686 "The HTML tag that is used to start a table.
3687 This must be a <table> tag, but you may change the options like
3688 borders and spacing."
3689 :group 'org-export-html
3690 :type 'string)
3692 (defcustom org-export-table-header-tags '("<th>" . "</th>")
3693 "The opening tag for table header fields.
3694 This is customizable so that alignment options can be specified."
3695 :group 'org-export-tables
3696 :type '(cons (string :tag "Opening tag") (string :tag "Closing tag")))
3698 (defcustom org-export-table-data-tags '("<td>" . "</td>")
3699 "The opening tag for table data fields.
3700 This is customizable so that alignment options can be specified."
3701 :group 'org-export-tables
3702 :type '(cons (string :tag "Opening tag") (string :tag "Closing tag")))
3704 (defcustom org-export-html-with-timestamp nil
3705 "If non-nil, write `org-export-html-html-helper-timestamp'
3706 into the exported HTML text. Otherwise, the buffer will just be saved
3707 to a file."
3708 :group 'org-export-html
3709 :type 'boolean)
3711 (defcustom org-export-html-html-helper-timestamp
3712 "<br/><br/><hr><p><!-- hhmts start --> <!-- hhmts end --></p>\n"
3713 "The HTML tag used as timestamp delimiter for HTML-helper-mode."
3714 :group 'org-export-html
3715 :type 'string)
3717 (defgroup org-export-icalendar nil
3718 "Options specific for iCalendar export of Org-mode files."
3719 :tag "Org Export iCalendar"
3720 :group 'org-export)
3722 (defcustom org-combined-agenda-icalendar-file "~/org.ics"
3723 "The file name for the iCalendar file covering all agenda files.
3724 This file is created with the command \\[org-export-icalendar-all-agenda-files].
3725 The file name should be absolute, the file will be overwritten without warning."
3726 :group 'org-export-icalendar
3727 :type 'file)
3729 (defcustom org-icalendar-include-todo nil
3730 "Non-nil means, export to iCalendar files should also cover TODO items."
3731 :group 'org-export-icalendar
3732 :type '(choice
3733 (const :tag "None" nil)
3734 (const :tag "Unfinished" t)
3735 (const :tag "All" all)))
3737 (defcustom org-icalendar-include-sexps t
3738 "Non-nil means, export to iCalendar files should also cover sexp entries.
3739 These are entries like in the diary, but directly in an Org-mode file."
3740 :group 'org-export-icalendar
3741 :type 'boolean)
3743 (defcustom org-icalendar-include-body 100
3744 "Amount of text below headline to be included in iCalendar export.
3745 This is a number of characters that should maximally be included.
3746 Properties, scheduling and clocking lines will always be removed.
3747 The text will be inserted into the DESCRIPTION field."
3748 :group 'org-export-icalendar
3749 :type '(choice
3750 (const :tag "Nothing" nil)
3751 (const :tag "Everything" t)
3752 (integer :tag "Max characters")))
3754 (defcustom org-icalendar-combined-name "OrgMode"
3755 "Calendar name for the combined iCalendar representing all agenda files."
3756 :group 'org-export-icalendar
3757 :type 'string)
3759 (defgroup org-font-lock nil
3760 "Font-lock settings for highlighting in Org-mode."
3761 :tag "Org Font Lock"
3762 :group 'org)
3764 (defcustom org-level-color-stars-only nil
3765 "Non-nil means fontify only the stars in each headline.
3766 When nil, the entire headline is fontified.
3767 Changing it requires restart of `font-lock-mode' to become effective
3768 also in regions already fontified."
3769 :group 'org-font-lock
3770 :type 'boolean)
3772 (defcustom org-hide-leading-stars nil
3773 "Non-nil means, hide the first N-1 stars in a headline.
3774 This works by using the face `org-hide' for these stars. This
3775 face is white for a light background, and black for a dark
3776 background. You may have to customize the face `org-hide' to
3777 make this work.
3778 Changing it requires restart of `font-lock-mode' to become effective
3779 also in regions already fontified.
3780 You may also set this on a per-file basis by adding one of the following
3781 lines to the buffer:
3783 #+STARTUP: hidestars
3784 #+STARTUP: showstars"
3785 :group 'org-font-lock
3786 :type 'boolean)
3788 (defcustom org-fontify-done-headline nil
3789 "Non-nil means, change the face of a headline if it is marked DONE.
3790 Normally, only the TODO/DONE keyword indicates the state of a headline.
3791 When this is non-nil, the headline after the keyword is set to the
3792 `org-headline-done' as an additional indication."
3793 :group 'org-font-lock
3794 :type 'boolean)
3796 (defcustom org-fontify-emphasized-text t
3797 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
3798 Changing this variable requires a restart of Emacs to take effect."
3799 :group 'org-font-lock
3800 :type 'boolean)
3802 (defcustom org-highlight-latex-fragments-and-specials nil
3803 "Non-nil means, fontify what is treated specially by the exporters."
3804 :group 'org-font-lock
3805 :type 'boolean)
3807 (defcustom org-hide-emphasis-markers nil
3808 "Non-nil mean font-lock should hide the emphasis marker characters."
3809 :group 'org-font-lock
3810 :type 'boolean)
3812 (defvar org-emph-re nil
3813 "Regular expression for matching emphasis.")
3814 (defvar org-verbatim-re nil
3815 "Regular expression for matching verbatim text.")
3816 (defvar org-emphasis-regexp-components) ; defined just below
3817 (defvar org-emphasis-alist) ; defined just below
3818 (defun org-set-emph-re (var val)
3819 "Set variable and compute the emphasis regular expression."
3820 (set var val)
3821 (when (and (boundp 'org-emphasis-alist)
3822 (boundp 'org-emphasis-regexp-components)
3823 org-emphasis-alist org-emphasis-regexp-components)
3824 (let* ((e org-emphasis-regexp-components)
3825 (pre (car e))
3826 (post (nth 1 e))
3827 (border (nth 2 e))
3828 (body (nth 3 e))
3829 (nl (nth 4 e))
3830 (stacked (and nil (nth 5 e))) ; stacked is no longer allowed, forced to nil
3831 (body1 (concat body "*?"))
3832 (markers (mapconcat 'car org-emphasis-alist ""))
3833 (vmarkers (mapconcat
3834 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
3835 org-emphasis-alist "")))
3836 ;; make sure special characters appear at the right position in the class
3837 (if (string-match "\\^" markers)
3838 (setq markers (concat (replace-match "" t t markers) "^")))
3839 (if (string-match "-" markers)
3840 (setq markers (concat (replace-match "" t t markers) "-")))
3841 (if (string-match "\\^" vmarkers)
3842 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
3843 (if (string-match "-" vmarkers)
3844 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
3845 (if (> nl 0)
3846 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
3847 (int-to-string nl) "\\}")))
3848 ;; Make the regexp
3849 (setq org-emph-re
3850 (concat "\\([" pre (if (and nil stacked) markers) "]\\|^\\)"
3851 "\\("
3852 "\\([" markers "]\\)"
3853 "\\("
3854 "[^" border "]\\|"
3855 "[^" border (if (and nil stacked) markers) "]"
3856 body1
3857 "[^" border (if (and nil stacked) markers) "]"
3858 "\\)"
3859 "\\3\\)"
3860 "\\([" post (if (and nil stacked) markers) "]\\|$\\)"))
3861 (setq org-verbatim-re
3862 (concat "\\([" pre "]\\|^\\)"
3863 "\\("
3864 "\\([" vmarkers "]\\)"
3865 "\\("
3866 "[^" border "]\\|"
3867 "[^" border "]"
3868 body1
3869 "[^" border "]"
3870 "\\)"
3871 "\\3\\)"
3872 "\\([" post "]\\|$\\)")))))
3874 (defcustom org-emphasis-regexp-components
3875 '(" \t('\"" "- \t.,:?;'\")" " \t\r\n,\"'" "." 1)
3876 "Components used to build the regular expression for emphasis.
3877 This is a list with 6 entries. Terminology: In an emphasis string
3878 like \" *strong word* \", we call the initial space PREMATCH, the final
3879 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
3880 and \"trong wor\" is the body. The different components in this variable
3881 specify what is allowed/forbidden in each part:
3883 pre Chars allowed as prematch. Beginning of line will be allowed too.
3884 post Chars allowed as postmatch. End of line will be allowed too.
3885 border The chars *forbidden* as border characters.
3886 body-regexp A regexp like \".\" to match a body character. Don't use
3887 non-shy groups here, and don't allow newline here.
3888 newline The maximum number of newlines allowed in an emphasis exp.
3890 Use customize to modify this, or restart Emacs after changing it."
3891 :group 'org-font-lock
3892 :set 'org-set-emph-re
3893 :type '(list
3894 (sexp :tag "Allowed chars in pre ")
3895 (sexp :tag "Allowed chars in post ")
3896 (sexp :tag "Forbidden chars in border ")
3897 (sexp :tag "Regexp for body ")
3898 (integer :tag "number of newlines allowed")
3899 (option (boolean :tag "Stacking (DISABLED) "))))
3901 (defcustom org-emphasis-alist
3902 '(("*" bold "<b>" "</b>")
3903 ("/" italic "<i>" "</i>")
3904 ("_" underline "<u>" "</u>")
3905 ("=" org-code "<code>" "</code>" verbatim)
3906 ("~" org-verbatim "" "" verbatim)
3907 ("+" (:strike-through t) "<del>" "</del>")
3909 "Special syntax for emphasized text.
3910 Text starting and ending with a special character will be emphasized, for
3911 example *bold*, _underlined_ and /italic/. This variable sets the marker
3912 characters, the face to be used by font-lock for highlighting in Org-mode
3913 Emacs buffers, and the HTML tags to be used for this.
3914 Use customize to modify this, or restart Emacs after changing it."
3915 :group 'org-font-lock
3916 :set 'org-set-emph-re
3917 :type '(repeat
3918 (list
3919 (string :tag "Marker character")
3920 (choice
3921 (face :tag "Font-lock-face")
3922 (plist :tag "Face property list"))
3923 (string :tag "HTML start tag")
3924 (string :tag "HTML end tag")
3925 (option (const verbatim)))))
3927 ;;; The faces
3929 (defgroup org-faces nil
3930 "Faces in Org-mode."
3931 :tag "Org Faces"
3932 :group 'org-font-lock)
3934 (defun org-compatible-face (inherits specs)
3935 "Make a compatible face specification.
3936 If INHERITS is an existing face and if the Emacs version supports it,
3937 just inherit the face. If not, use SPECS to define the face.
3938 XEmacs and Emacs 21 do not know about the `min-colors' attribute.
3939 For them we convert a (min-colors 8) entry to a `tty' entry and move it
3940 to the top of the list. The `min-colors' attribute will be removed from
3941 any other entries, and any resulting duplicates will be removed entirely."
3942 (cond
3943 ((and inherits (facep inherits)
3944 (not (featurep 'xemacs)) (> emacs-major-version 22))
3945 ;; In Emacs 23, we use inheritance where possible.
3946 ;; We only do this in Emacs 23, because only there the outline
3947 ;; faces have been changed to the original org-mode-level-faces.
3948 (list (list t :inherit inherits)))
3949 ((or (featurep 'xemacs) (< emacs-major-version 22))
3950 ;; These do not understand the `min-colors' attribute.
3951 (let (r e a)
3952 (while (setq e (pop specs))
3953 (cond
3954 ((memq (car e) '(t default)) (push e r))
3955 ((setq a (member '(min-colors 8) (car e)))
3956 (nconc r (list (cons (cons '(type tty) (delq (car a) (car e)))
3957 (cdr e)))))
3958 ((setq a (assq 'min-colors (car e)))
3959 (setq e (cons (delq a (car e)) (cdr e)))
3960 (or (assoc (car e) r) (push e r)))
3961 (t (or (assoc (car e) r) (push e r)))))
3962 (nreverse r)))
3963 (t specs)))
3964 (put 'org-compatible-face 'lisp-indent-function 1)
3966 (defface org-hide
3967 '((((background light)) (:foreground "white"))
3968 (((background dark)) (:foreground "black")))
3969 "Face used to hide leading stars in headlines.
3970 The forground color of this face should be equal to the background
3971 color of the frame."
3972 :group 'org-faces)
3974 (defface org-level-1 ;; font-lock-function-name-face
3975 (org-compatible-face 'outline-1
3976 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
3977 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
3978 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
3979 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
3980 (((class color) (min-colors 8)) (:foreground "blue" :bold t))
3981 (t (:bold t))))
3982 "Face used for level 1 headlines."
3983 :group 'org-faces)
3985 (defface org-level-2 ;; font-lock-variable-name-face
3986 (org-compatible-face 'outline-2
3987 '((((class color) (min-colors 16) (background light)) (:foreground "DarkGoldenrod"))
3988 (((class color) (min-colors 16) (background dark)) (:foreground "LightGoldenrod"))
3989 (((class color) (min-colors 8) (background light)) (:foreground "yellow"))
3990 (((class color) (min-colors 8) (background dark)) (:foreground "yellow" :bold t))
3991 (t (:bold t))))
3992 "Face used for level 2 headlines."
3993 :group 'org-faces)
3995 (defface org-level-3 ;; font-lock-keyword-face
3996 (org-compatible-face 'outline-3
3997 '((((class color) (min-colors 88) (background light)) (:foreground "Purple"))
3998 (((class color) (min-colors 88) (background dark)) (:foreground "Cyan1"))
3999 (((class color) (min-colors 16) (background light)) (:foreground "Purple"))
4000 (((class color) (min-colors 16) (background dark)) (:foreground "Cyan"))
4001 (((class color) (min-colors 8) (background light)) (:foreground "purple" :bold t))
4002 (((class color) (min-colors 8) (background dark)) (:foreground "cyan" :bold t))
4003 (t (:bold t))))
4004 "Face used for level 3 headlines."
4005 :group 'org-faces)
4007 (defface org-level-4 ;; font-lock-comment-face
4008 (org-compatible-face 'outline-4
4009 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
4010 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
4011 (((class color) (min-colors 16) (background light)) (:foreground "red"))
4012 (((class color) (min-colors 16) (background dark)) (:foreground "red1"))
4013 (((class color) (min-colors 8) (background light)) (:foreground "red" :bold t))
4014 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
4015 (t (:bold t))))
4016 "Face used for level 4 headlines."
4017 :group 'org-faces)
4019 (defface org-level-5 ;; font-lock-type-face
4020 (org-compatible-face 'outline-5
4021 '((((class color) (min-colors 16) (background light)) (:foreground "ForestGreen"))
4022 (((class color) (min-colors 16) (background dark)) (:foreground "PaleGreen"))
4023 (((class color) (min-colors 8)) (:foreground "green"))))
4024 "Face used for level 5 headlines."
4025 :group 'org-faces)
4027 (defface org-level-6 ;; font-lock-constant-face
4028 (org-compatible-face 'outline-6
4029 '((((class color) (min-colors 16) (background light)) (:foreground "CadetBlue"))
4030 (((class color) (min-colors 16) (background dark)) (:foreground "Aquamarine"))
4031 (((class color) (min-colors 8)) (:foreground "magenta"))))
4032 "Face used for level 6 headlines."
4033 :group 'org-faces)
4035 (defface org-level-7 ;; font-lock-builtin-face
4036 (org-compatible-face 'outline-7
4037 '((((class color) (min-colors 16) (background light)) (:foreground "Orchid"))
4038 (((class color) (min-colors 16) (background dark)) (:foreground "LightSteelBlue"))
4039 (((class color) (min-colors 8)) (:foreground "blue"))))
4040 "Face used for level 7 headlines."
4041 :group 'org-faces)
4043 (defface org-level-8 ;; font-lock-string-face
4044 (org-compatible-face 'outline-8
4045 '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
4046 (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
4047 (((class color) (min-colors 8)) (:foreground "green"))))
4048 "Face used for level 8 headlines."
4049 :group 'org-faces)
4051 (defface org-special-keyword ;; font-lock-string-face
4052 (org-compatible-face nil
4053 '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
4054 (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
4055 (t (:italic t))))
4056 "Face used for special keywords."
4057 :group 'org-faces)
4059 (defface org-drawer ;; font-lock-function-name-face
4060 (org-compatible-face nil
4061 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
4062 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
4063 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
4064 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
4065 (((class color) (min-colors 8)) (:foreground "blue" :bold t))
4066 (t (:bold t))))
4067 "Face used for drawers."
4068 :group 'org-faces)
4070 (defface org-property-value nil
4071 "Face used for the value of a property."
4072 :group 'org-faces)
4074 (defface org-column
4075 (org-compatible-face nil
4076 '((((class color) (min-colors 16) (background light))
4077 (:background "grey90"))
4078 (((class color) (min-colors 16) (background dark))
4079 (:background "grey30"))
4080 (((class color) (min-colors 8))
4081 (:background "cyan" :foreground "black"))
4082 (t (:inverse-video t))))
4083 "Face for column display of entry properties."
4084 :group 'org-faces)
4086 (when (fboundp 'set-face-attribute)
4087 ;; Make sure that a fixed-width face is used when we have a column table.
4088 (set-face-attribute 'org-column nil
4089 :height (face-attribute 'default :height)
4090 :family (face-attribute 'default :family)))
4092 (defface org-warning
4093 (org-compatible-face 'font-lock-warning-face
4094 '((((class color) (min-colors 16) (background light)) (:foreground "Red1" :bold t))
4095 (((class color) (min-colors 16) (background dark)) (:foreground "Pink" :bold t))
4096 (((class color) (min-colors 8) (background light)) (:foreground "red" :bold t))
4097 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
4098 (t (:bold t))))
4099 "Face for deadlines and TODO keywords."
4100 :group 'org-faces)
4102 (defface org-archived ; similar to shadow
4103 (org-compatible-face 'shadow
4104 '((((class color grayscale) (min-colors 88) (background light))
4105 (:foreground "grey50"))
4106 (((class color grayscale) (min-colors 88) (background dark))
4107 (:foreground "grey70"))
4108 (((class color) (min-colors 8) (background light))
4109 (:foreground "green"))
4110 (((class color) (min-colors 8) (background dark))
4111 (:foreground "yellow"))))
4112 "Face for headline with the ARCHIVE tag."
4113 :group 'org-faces)
4115 (defface org-link
4116 '((((class color) (background light)) (:foreground "Purple" :underline t))
4117 (((class color) (background dark)) (:foreground "Cyan" :underline t))
4118 (t (:underline t)))
4119 "Face for links."
4120 :group 'org-faces)
4122 (defface org-ellipsis
4123 '((((class color) (background light)) (:foreground "DarkGoldenrod" :underline t))
4124 (((class color) (background dark)) (:foreground "LightGoldenrod" :underline t))
4125 (t (:strike-through t)))
4126 "Face for the ellipsis in folded text."
4127 :group 'org-faces)
4129 (defface org-target
4130 '((((class color) (background light)) (:underline t))
4131 (((class color) (background dark)) (:underline t))
4132 (t (:underline t)))
4133 "Face for links."
4134 :group 'org-faces)
4136 (defface org-date
4137 '((((class color) (background light)) (:foreground "Purple" :underline t))
4138 (((class color) (background dark)) (:foreground "Cyan" :underline t))
4139 (t (:underline t)))
4140 "Face for links."
4141 :group 'org-faces)
4143 (defface org-sexp-date
4144 '((((class color) (background light)) (:foreground "Purple"))
4145 (((class color) (background dark)) (:foreground "Cyan"))
4146 (t (:underline t)))
4147 "Face for links."
4148 :group 'org-faces)
4150 (defface org-tag
4151 '((t (:bold t)))
4152 "Face for tags."
4153 :group 'org-faces)
4155 (defface org-todo ; font-lock-warning-face
4156 (org-compatible-face nil
4157 '((((class color) (min-colors 16) (background light)) (:foreground "Red1" :bold t))
4158 (((class color) (min-colors 16) (background dark)) (:foreground "Pink" :bold t))
4159 (((class color) (min-colors 8) (background light)) (:foreground "red" :bold t))
4160 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
4161 (t (:inverse-video t :bold t))))
4162 "Face for TODO keywords."
4163 :group 'org-faces)
4165 (defface org-done ;; font-lock-type-face
4166 (org-compatible-face nil
4167 '((((class color) (min-colors 16) (background light)) (:foreground "ForestGreen" :bold t))
4168 (((class color) (min-colors 16) (background dark)) (:foreground "PaleGreen" :bold t))
4169 (((class color) (min-colors 8)) (:foreground "green"))
4170 (t (:bold t))))
4171 "Face used for todo keywords that indicate DONE items."
4172 :group 'org-faces)
4174 (defface org-headline-done ;; font-lock-string-face
4175 (org-compatible-face nil
4176 '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
4177 (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
4178 (((class color) (min-colors 8) (background light)) (:bold nil))))
4179 "Face used to indicate that a headline is DONE.
4180 This face is only used if `org-fontify-done-headline' is set. If applies
4181 to the part of the headline after the DONE keyword."
4182 :group 'org-faces)
4184 (defcustom org-todo-keyword-faces nil
4185 "Faces for specific TODO keywords.
4186 This is a list of cons cells, with TODO keywords in the car
4187 and faces in the cdr. The face can be a symbol, or a property
4188 list of attributes, like (:foreground \"blue\" :weight bold :underline t)."
4189 :group 'org-faces
4190 :group 'org-todo
4191 :type '(repeat
4192 (cons
4193 (string :tag "keyword")
4194 (sexp :tag "face"))))
4196 (defface org-table ;; font-lock-function-name-face
4197 (org-compatible-face nil
4198 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
4199 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
4200 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
4201 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
4202 (((class color) (min-colors 8) (background light)) (:foreground "blue"))
4203 (((class color) (min-colors 8) (background dark)))))
4204 "Face used for tables."
4205 :group 'org-faces)
4207 (defface org-formula
4208 (org-compatible-face nil
4209 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
4210 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
4211 (((class color) (min-colors 8) (background light)) (:foreground "red"))
4212 (((class color) (min-colors 8) (background dark)) (:foreground "red"))
4213 (t (:bold t :italic t))))
4214 "Face for formulas."
4215 :group 'org-faces)
4217 (defface org-code
4218 (org-compatible-face nil
4219 '((((class color grayscale) (min-colors 88) (background light))
4220 (:foreground "grey50"))
4221 (((class color grayscale) (min-colors 88) (background dark))
4222 (:foreground "grey70"))
4223 (((class color) (min-colors 8) (background light))
4224 (:foreground "green"))
4225 (((class color) (min-colors 8) (background dark))
4226 (:foreground "yellow"))))
4227 "Face for fixed-with text like code snippets."
4228 :group 'org-faces
4229 :version "22.1")
4231 (defface org-verbatim
4232 (org-compatible-face nil
4233 '((((class color grayscale) (min-colors 88) (background light))
4234 (:foreground "grey50" :underline t))
4235 (((class color grayscale) (min-colors 88) (background dark))
4236 (:foreground "grey70" :underline t))
4237 (((class color) (min-colors 8) (background light))
4238 (:foreground "green" :underline t))
4239 (((class color) (min-colors 8) (background dark))
4240 (:foreground "yellow" :underline t))))
4241 "Face for fixed-with text like code snippets."
4242 :group 'org-faces
4243 :version "22.1")
4245 (defface org-agenda-structure ;; font-lock-function-name-face
4246 (org-compatible-face nil
4247 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
4248 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
4249 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
4250 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
4251 (((class color) (min-colors 8)) (:foreground "blue" :bold t))
4252 (t (:bold t))))
4253 "Face used in agenda for captions and dates."
4254 :group 'org-faces)
4256 (defface org-scheduled-today
4257 (org-compatible-face nil
4258 '((((class color) (min-colors 88) (background light)) (:foreground "DarkGreen"))
4259 (((class color) (min-colors 88) (background dark)) (:foreground "PaleGreen"))
4260 (((class color) (min-colors 8)) (:foreground "green"))
4261 (t (:bold t :italic t))))
4262 "Face for items scheduled for a certain day."
4263 :group 'org-faces)
4265 (defface org-scheduled-previously
4266 (org-compatible-face nil
4267 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
4268 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
4269 (((class color) (min-colors 8) (background light)) (:foreground "red"))
4270 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
4271 (t (:bold t))))
4272 "Face for items scheduled previously, and not yet done."
4273 :group 'org-faces)
4275 (defface org-upcoming-deadline
4276 (org-compatible-face nil
4277 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
4278 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
4279 (((class color) (min-colors 8) (background light)) (:foreground "red"))
4280 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
4281 (t (:bold t))))
4282 "Face for items scheduled previously, and not yet done."
4283 :group 'org-faces)
4285 (defcustom org-agenda-deadline-faces
4286 '((1.0 . org-warning)
4287 (0.5 . org-upcoming-deadline)
4288 (0.0 . default))
4289 "Faces for showing deadlines in the agenda.
4290 This is a list of cons cells. The cdr of each cell is a face to be used,
4291 and it can also just be like '(:foreground \"yellow\").
4292 Each car is a fraction of the head-warning time that must have passed for
4293 this the face in the cdr to be used for display. The numbers must be
4294 given in descending order. The head-warning time is normally taken
4295 from `org-deadline-warning-days', but can also be specified in the deadline
4296 timestamp itself, like this:
4298 DEADLINE: <2007-08-13 Mon -8d>
4300 You may use d for days, w for weeks, m for months and y for years. Months
4301 and years will only be treated in an approximate fashion (30.4 days for a
4302 month and 365.24 days for a year)."
4303 :group 'org-faces
4304 :group 'org-agenda-daily/weekly
4305 :type '(repeat
4306 (cons
4307 (number :tag "Fraction of head-warning time passed")
4308 (sexp :tag "Face"))))
4310 ;; FIXME: this is not a good face yet.
4311 (defface org-agenda-restriction-lock
4312 (org-compatible-face nil
4313 '((((class color) (min-colors 88) (background light)) (:background "yellow1"))
4314 (((class color) (min-colors 88) (background dark)) (:background "skyblue4"))
4315 (((class color) (min-colors 16) (background light)) (:background "yellow1"))
4316 (((class color) (min-colors 16) (background dark)) (:background "skyblue4"))
4317 (((class color) (min-colors 8)) (:background "cyan" :foreground "black"))
4318 (t (:inverse-video t))))
4319 "Face for showing the agenda restriction lock."
4320 :group 'org-faces)
4322 (defface org-time-grid ;; font-lock-variable-name-face
4323 (org-compatible-face nil
4324 '((((class color) (min-colors 16) (background light)) (:foreground "DarkGoldenrod"))
4325 (((class color) (min-colors 16) (background dark)) (:foreground "LightGoldenrod"))
4326 (((class color) (min-colors 8)) (:foreground "yellow" :weight light))))
4327 "Face used for time grids."
4328 :group 'org-faces)
4330 (defconst org-level-faces
4331 '(org-level-1 org-level-2 org-level-3 org-level-4
4332 org-level-5 org-level-6 org-level-7 org-level-8
4335 (defcustom org-n-level-faces (length org-level-faces)
4336 "The number of different faces to be used for headlines.
4337 Org-mode defines 8 different headline faces, so this can be at most 8.
4338 If it is less than 8, the level-1 face gets re-used for level N+1 etc."
4339 :type 'number
4340 :group 'org-faces)
4342 ;;; Functions and variables from ther packages
4343 ;; Declared here to avoid compiler warnings
4345 (eval-and-compile
4346 (unless (fboundp 'declare-function)
4347 (defmacro declare-function (fn file &optional arglist fileonly))))
4349 ;; XEmacs only
4350 (defvar outline-mode-menu-heading)
4351 (defvar outline-mode-menu-show)
4352 (defvar outline-mode-menu-hide)
4353 (defvar zmacs-regions) ; XEmacs regions
4355 ;; Emacs only
4356 (defvar mark-active)
4358 ;; Various packages
4359 ;; FIXME: get the argument lists for the UNKNOWN stuff
4360 (declare-function add-to-diary-list "diary-lib"
4361 (date string specifier &optional marker globcolor literal))
4362 (declare-function table--at-cell-p "table" (position &optional object at-column))
4363 (declare-function Info-find-node "info" (filename nodename &optional no-going-back))
4364 (declare-function bbdb "ext:bbdb-com" (string elidep))
4365 (declare-function bbdb-company "ext:bbdb-com" (string elidep))
4366 (declare-function bbdb-current-record "ext:bbdb-com" (&optional planning-on-modifying))
4367 (declare-function bbdb-name "ext:bbdb-com" (string elidep))
4368 (declare-function bbdb-record-getprop "ext:bbdb" (record property))
4369 (declare-function bbdb-record-name "ext:bbdb" (record))
4370 (declare-function bibtex-beginning-of-entry "bibtex" ())
4371 (declare-function bibtex-generate-autokey "bibtex" ())
4372 (declare-function bibtex-parse-entry "bibtex" (&optional content))
4373 (declare-function bibtex-url "bibtex" (&optional pos no-browse))
4374 (defvar calc-embedded-close-formula)
4375 (defvar calc-embedded-open-formula)
4376 (declare-function calendar-astro-date-string "cal-julian" (&optional date))
4377 (declare-function calendar-bahai-date-string "cal-bahai" (&optional date))
4378 (declare-function calendar-check-holidays "holidays" (date))
4379 (declare-function calendar-chinese-date-string "cal-china" (&optional date))
4380 (declare-function calendar-coptic-date-string "cal-coptic" (&optional date))
4381 (declare-function calendar-ethiopic-date-string "cal-coptic" (&optional date))
4382 (declare-function calendar-forward-day "cal-move" (arg))
4383 (declare-function calendar-french-date-string "cal-french" (&optional date))
4384 (declare-function calendar-goto-date "cal-move" (date))
4385 (declare-function calendar-goto-today "cal-move" ())
4386 (declare-function calendar-hebrew-date-string "cal-hebrew" (&optional date))
4387 (declare-function calendar-islamic-date-string "cal-islam" (&optional date))
4388 (declare-function calendar-iso-date-string "cal-iso" (&optional date))
4389 (declare-function calendar-julian-date-string "cal-julian" (&optional date))
4390 (declare-function calendar-mayan-date-string "cal-mayan" (&optional date))
4391 (declare-function calendar-persian-date-string "cal-persia" (&optional date))
4392 (defvar calendar-mode-map)
4393 (defvar original-date) ; dynamically scoped in calendar.el does scope this
4394 (declare-function cdlatex-tab "ext:cdlatex" ())
4395 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
4396 (declare-function elmo-folder-exists-p "ext:elmo" (folder) t)
4397 (declare-function elmo-message-entity-field "ext:elmo-msgdb" (entity field &optional type))
4398 (declare-function elmo-message-field "ext:elmo" (folder number field &optional type) t)
4399 (declare-function elmo-msgdb-overview-get-entity "ext:elmo" (&rest unknown) t)
4400 (defvar font-lock-unfontify-region-function)
4401 (declare-function gnus-article-show-summary "gnus-art" ())
4402 (declare-function gnus-summary-last-subject "gnus-sum" ())
4403 (defvar gnus-other-frame-object)
4404 (defvar gnus-group-name)
4405 (defvar gnus-article-current)
4406 (defvar Info-current-file)
4407 (defvar Info-current-node)
4408 (declare-function mh-display-msg "mh-show" (msg-num folder-name))
4409 (declare-function mh-find-path "mh-utils" ())
4410 (declare-function mh-get-header-field "mh-utils" (field))
4411 (declare-function mh-get-msg-num "mh-utils" (error-if-no-message))
4412 (declare-function mh-header-display "mh-show" ())
4413 (declare-function mh-index-previous-folder "mh-search" ())
4414 (declare-function mh-normalize-folder-name "mh-utils" (folder &optional empty-string-okay dont-remove-trailing-slash return-nil-if-folder-empty))
4415 (declare-function mh-search "mh-search" (folder search-regexp &optional redo-search-flag window-config))
4416 (declare-function mh-search-choose "mh-search" (&optional searcher))
4417 (declare-function mh-show "mh-show" (&optional message redisplay-flag))
4418 (declare-function mh-show-buffer-message-number "mh-comp" (&optional buffer))
4419 (declare-function mh-show-header-display "mh-show" t t)
4420 (declare-function mh-show-msg "mh-show" (msg))
4421 (declare-function mh-show-show "mh-show" t t)
4422 (declare-function mh-visit-folder "mh-folder" (folder &optional range index-data))
4423 (defvar mh-progs)
4424 (defvar mh-current-folder)
4425 (defvar mh-show-folder-buffer)
4426 (defvar mh-index-folder)
4427 (defvar mh-searcher)
4428 (declare-function org-export-latex-cleaned-string "org-export-latex" ())
4429 (declare-function parse-time-string "parse-time" (string))
4430 (declare-function remember "remember" (&optional initial))
4431 (declare-function remember-buffer-desc "remember" ())
4432 (declare-function remember-finalize "remember" ())
4433 (defvar remember-save-after-remembering)
4434 (defvar remember-data-file)
4435 (defvar remember-register)
4436 (defvar remember-buffer)
4437 (defvar remember-handler-functions)
4438 (defvar remember-annotation-functions)
4439 (declare-function rmail-narrow-to-non-pruned-header "rmail" ())
4440 (declare-function rmail-show-message "rmail" (&optional n no-summary))
4441 (declare-function rmail-what-message "rmail" ())
4442 (defvar rmail-current-message)
4443 (defvar texmathp-why)
4444 (declare-function vm-beginning-of-message "ext:vm-page" ())
4445 (declare-function vm-follow-summary-cursor "ext:vm-motion" ())
4446 (declare-function vm-get-header-contents "ext:vm-summary" (message header-name-regexp &optional clump-sep))
4447 (declare-function vm-isearch-narrow "ext:vm-search" ())
4448 (declare-function vm-isearch-update "ext:vm-search" ())
4449 (declare-function vm-select-folder-buffer "ext:vm-macro" ())
4450 (declare-function vm-su-message-id "ext:vm-summary" (m))
4451 (declare-function vm-su-subject "ext:vm-summary" (m))
4452 (declare-function vm-summarize "ext:vm-summary" (&optional display raise))
4453 (defvar vm-message-pointer)
4454 (defvar vm-folder-directory)
4455 (defvar w3m-current-url)
4456 (defvar w3m-current-title)
4457 ;; backward compatibility to old version of wl
4458 (declare-function wl-summary-buffer-msgdb "ext:wl-folder" (&rest unknown) t)
4459 (declare-function wl-folder-get-elmo-folder "ext:wl-folder" (entity &optional no-cache))
4460 (declare-function wl-summary-goto-folder-subr "ext:wl-summary" (&optional name scan-type other-window sticky interactive scoring force-exit))
4461 (declare-function wl-summary-jump-to-msg-by-message-id "ext:wl-summary" (&optional id))
4462 (declare-function wl-summary-line-from "ext:wl-summary" ())
4463 (declare-function wl-summary-line-subject "ext:wl-summary" ())
4464 (declare-function wl-summary-message-number "ext:wl-summary" ())
4465 (declare-function wl-summary-redisplay "ext:wl-summary" (&optional arg))
4466 (defvar wl-summary-buffer-elmo-folder)
4467 (defvar wl-summary-buffer-folder-name)
4468 (declare-function speedbar-line-directory "speedbar" (&optional depth))
4470 (defvar org-latex-regexps)
4471 (defvar constants-unit-system)
4473 ;;; Variables for pre-computed regular expressions, all buffer local
4475 (defvar org-drawer-regexp nil
4476 "Matches first line of a hidden block.")
4477 (make-variable-buffer-local 'org-drawer-regexp)
4478 (defvar org-todo-regexp nil
4479 "Matches any of the TODO state keywords.")
4480 (make-variable-buffer-local 'org-todo-regexp)
4481 (defvar org-not-done-regexp nil
4482 "Matches any of the TODO state keywords except the last one.")
4483 (make-variable-buffer-local 'org-not-done-regexp)
4484 (defvar org-todo-line-regexp nil
4485 "Matches a headline and puts TODO state into group 2 if present.")
4486 (make-variable-buffer-local 'org-todo-line-regexp)
4487 (defvar org-complex-heading-regexp nil
4488 "Matches a headline and puts everything into groups:
4489 group 1: the stars
4490 group 2: The todo keyword, maybe
4491 group 3: Priority cookie
4492 group 4: True headline
4493 group 5: Tags")
4494 (make-variable-buffer-local 'org-complex-heading-regexp)
4495 (defvar org-todo-line-tags-regexp nil
4496 "Matches a headline and puts TODO state into group 2 if present.
4497 Also put tags into group 4 if tags are present.")
4498 (make-variable-buffer-local 'org-todo-line-tags-regexp)
4499 (defvar org-nl-done-regexp nil
4500 "Matches newline followed by a headline with the DONE keyword.")
4501 (make-variable-buffer-local 'org-nl-done-regexp)
4502 (defvar org-looking-at-done-regexp nil
4503 "Matches the DONE keyword a point.")
4504 (make-variable-buffer-local 'org-looking-at-done-regexp)
4505 (defvar org-ds-keyword-length 12
4506 "Maximum length of the Deadline and SCHEDULED keywords.")
4507 (make-variable-buffer-local 'org-ds-keyword-length)
4508 (defvar org-deadline-regexp nil
4509 "Matches the DEADLINE keyword.")
4510 (make-variable-buffer-local 'org-deadline-regexp)
4511 (defvar org-deadline-time-regexp nil
4512 "Matches the DEADLINE keyword together with a time stamp.")
4513 (make-variable-buffer-local 'org-deadline-time-regexp)
4514 (defvar org-deadline-line-regexp nil
4515 "Matches the DEADLINE keyword and the rest of the line.")
4516 (make-variable-buffer-local 'org-deadline-line-regexp)
4517 (defvar org-scheduled-regexp nil
4518 "Matches the SCHEDULED keyword.")
4519 (make-variable-buffer-local 'org-scheduled-regexp)
4520 (defvar org-scheduled-time-regexp nil
4521 "Matches the SCHEDULED keyword together with a time stamp.")
4522 (make-variable-buffer-local 'org-scheduled-time-regexp)
4523 (defvar org-closed-time-regexp nil
4524 "Matches the CLOSED keyword together with a time stamp.")
4525 (make-variable-buffer-local 'org-closed-time-regexp)
4527 (defvar org-keyword-time-regexp nil
4528 "Matches any of the 4 keywords, together with the time stamp.")
4529 (make-variable-buffer-local 'org-keyword-time-regexp)
4530 (defvar org-keyword-time-not-clock-regexp nil
4531 "Matches any of the 3 keywords, together with the time stamp.")
4532 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
4533 (defvar org-maybe-keyword-time-regexp nil
4534 "Matches a timestamp, possibly preceeded by a keyword.")
4535 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
4536 (defvar org-planning-or-clock-line-re nil
4537 "Matches a line with planning or clock info.")
4538 (make-variable-buffer-local 'org-planning-or-clock-line-re)
4540 (defconst org-rm-props '(invisible t face t keymap t intangible t mouse-face t
4541 rear-nonsticky t mouse-map t fontified t)
4542 "Properties to remove when a string without properties is wanted.")
4544 (defsubst org-match-string-no-properties (num &optional string)
4545 (if (featurep 'xemacs)
4546 (let ((s (match-string num string)))
4547 (remove-text-properties 0 (length s) org-rm-props s)
4549 (match-string-no-properties num string)))
4551 (defsubst org-no-properties (s)
4552 (if (fboundp 'set-text-properties)
4553 (set-text-properties 0 (length s) nil s)
4554 (remove-text-properties 0 (length s) org-rm-props s))
4557 (defsubst org-get-alist-option (option key)
4558 (cond ((eq key t) t)
4559 ((eq option t) t)
4560 ((assoc key option) (cdr (assoc key option)))
4561 (t (cdr (assq 'default option)))))
4563 (defsubst org-inhibit-invisibility ()
4564 "Modified `buffer-invisibility-spec' for Emacs 21.
4565 Some ops with invisible text do not work correctly on Emacs 21. For these
4566 we turn off invisibility temporarily. Use this in a `let' form."
4567 (if (< emacs-major-version 22) nil buffer-invisibility-spec))
4569 (defsubst org-set-local (var value)
4570 "Make VAR local in current buffer and set it to VALUE."
4571 (set (make-variable-buffer-local var) value))
4573 (defsubst org-mode-p ()
4574 "Check if the current buffer is in Org-mode."
4575 (eq major-mode 'org-mode))
4577 (defsubst org-last (list)
4578 "Return the last element of LIST."
4579 (car (last list)))
4581 (defun org-let (list &rest body)
4582 (eval (cons 'let (cons list body))))
4583 (put 'org-let 'lisp-indent-function 1)
4585 (defun org-let2 (list1 list2 &rest body)
4586 (eval (cons 'let (cons list1 (list (cons 'let (cons list2 body)))))))
4587 (put 'org-let2 'lisp-indent-function 2)
4588 (defconst org-startup-options
4589 '(("fold" org-startup-folded t)
4590 ("overview" org-startup-folded t)
4591 ("nofold" org-startup-folded nil)
4592 ("showall" org-startup-folded nil)
4593 ("content" org-startup-folded content)
4594 ("hidestars" org-hide-leading-stars t)
4595 ("showstars" org-hide-leading-stars nil)
4596 ("odd" org-odd-levels-only t)
4597 ("oddeven" org-odd-levels-only nil)
4598 ("align" org-startup-align-all-tables t)
4599 ("noalign" org-startup-align-all-tables nil)
4600 ("customtime" org-display-custom-times t)
4601 ("logdone" org-log-done time)
4602 ("lognotedone" org-log-done note)
4603 ("nologdone" org-log-done nil)
4604 ("lognoteclock-out" org-log-note-clock-out t)
4605 ("nolognoteclock-out" org-log-note-clock-out nil)
4606 ("logrepeat" org-log-repeat state)
4607 ("lognoterepeat" org-log-repeat note)
4608 ("nologrepeat" org-log-repeat nil)
4609 ("constcgs" constants-unit-system cgs)
4610 ("constSI" constants-unit-system SI))
4611 "Variable associated with STARTUP options for org-mode.
4612 Each element is a list of three items: The startup options as written
4613 in the #+STARTUP line, the corresponding variable, and the value to
4614 set this variable to if the option is found. An optional forth element PUSH
4615 means to push this value onto the list in the variable.")
4617 (defun org-set-regexps-and-options ()
4618 "Precompute regular expressions for current buffer."
4619 (when (org-mode-p)
4620 (org-set-local 'org-todo-kwd-alist nil)
4621 (org-set-local 'org-todo-key-alist nil)
4622 (org-set-local 'org-todo-key-trigger nil)
4623 (org-set-local 'org-todo-keywords-1 nil)
4624 (org-set-local 'org-done-keywords nil)
4625 (org-set-local 'org-todo-heads nil)
4626 (org-set-local 'org-todo-sets nil)
4627 (org-set-local 'org-todo-log-states nil)
4628 (let ((re (org-make-options-regexp
4629 '("CATEGORY" "SEQ_TODO" "TYP_TODO" "TODO" "COLUMNS"
4630 "STARTUP" "ARCHIVE" "TAGS" "LINK" "PRIORITIES"
4631 "CONSTANTS" "PROPERTY" "DRAWERS")))
4632 (splitre "[ \t]+")
4633 kwds kws0 kwsa key log value cat arch tags const links hw dws
4634 tail sep kws1 prio props drawers)
4635 (save-excursion
4636 (save-restriction
4637 (widen)
4638 (goto-char (point-min))
4639 (while (re-search-forward re nil t)
4640 (setq key (match-string 1) value (org-match-string-no-properties 2))
4641 (cond
4642 ((equal key "CATEGORY")
4643 (if (string-match "[ \t]+$" value)
4644 (setq value (replace-match "" t t value)))
4645 (setq cat value))
4646 ((member key '("SEQ_TODO" "TODO"))
4647 (push (cons 'sequence (org-split-string value splitre)) kwds))
4648 ((equal key "TYP_TODO")
4649 (push (cons 'type (org-split-string value splitre)) kwds))
4650 ((equal key "TAGS")
4651 (setq tags (append tags (org-split-string value splitre))))
4652 ((equal key "COLUMNS")
4653 (org-set-local 'org-columns-default-format value))
4654 ((equal key "LINK")
4655 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
4656 (push (cons (match-string 1 value)
4657 (org-trim (match-string 2 value)))
4658 links)))
4659 ((equal key "PRIORITIES")
4660 (setq prio (org-split-string value " +")))
4661 ((equal key "PROPERTY")
4662 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4663 (push (cons (match-string 1 value) (match-string 2 value))
4664 props)))
4665 ((equal key "DRAWERS")
4666 (setq drawers (org-split-string value splitre)))
4667 ((equal key "CONSTANTS")
4668 (setq const (append const (org-split-string value splitre))))
4669 ((equal key "STARTUP")
4670 (let ((opts (org-split-string value splitre))
4671 l var val)
4672 (while (setq l (pop opts))
4673 (when (setq l (assoc l org-startup-options))
4674 (setq var (nth 1 l) val (nth 2 l))
4675 (if (not (nth 3 l))
4676 (set (make-local-variable var) val)
4677 (if (not (listp (symbol-value var)))
4678 (set (make-local-variable var) nil))
4679 (set (make-local-variable var) (symbol-value var))
4680 (add-to-list var val))))))
4681 ((equal key "ARCHIVE")
4682 (string-match " *$" value)
4683 (setq arch (replace-match "" t t value))
4684 (remove-text-properties 0 (length arch)
4685 '(face t fontified t) arch)))
4687 (when cat
4688 (org-set-local 'org-category (intern cat))
4689 (push (cons "CATEGORY" cat) props))
4690 (when prio
4691 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
4692 (setq prio (mapcar 'string-to-char prio))
4693 (org-set-local 'org-highest-priority (nth 0 prio))
4694 (org-set-local 'org-lowest-priority (nth 1 prio))
4695 (org-set-local 'org-default-priority (nth 2 prio)))
4696 (and props (org-set-local 'org-local-properties (nreverse props)))
4697 (and drawers (org-set-local 'org-drawers drawers))
4698 (and arch (org-set-local 'org-archive-location arch))
4699 (and links (setq org-link-abbrev-alist-local (nreverse links)))
4700 ;; Process the TODO keywords
4701 (unless kwds
4702 ;; Use the global values as if they had been given locally.
4703 (setq kwds (default-value 'org-todo-keywords))
4704 (if (stringp (car kwds))
4705 (setq kwds (list (cons org-todo-interpretation
4706 (default-value 'org-todo-keywords)))))
4707 (setq kwds (reverse kwds)))
4708 (setq kwds (nreverse kwds))
4709 (let (inter kws kw)
4710 (while (setq kws (pop kwds))
4711 (setq inter (pop kws) sep (member "|" kws)
4712 kws0 (delete "|" (copy-sequence kws))
4713 kwsa nil
4714 kws1 (mapcar
4715 (lambda (x)
4716 ;; 1 2
4717 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
4718 (progn
4719 (setq kw (match-string 1 x)
4720 key (and (match-end 2) (match-string 2 x))
4721 log (org-extract-log-state-settings x))
4722 (push (cons kw (and key (string-to-char key))) kwsa)
4723 (and log (push log org-todo-log-states))
4725 (error "Invalid TODO keyword %s" x)))
4726 kws0)
4727 kwsa (if kwsa (append '((:startgroup))
4728 (nreverse kwsa)
4729 '((:endgroup))))
4730 hw (car kws1)
4731 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
4732 tail (list inter hw (car dws) (org-last dws)))
4733 (add-to-list 'org-todo-heads hw 'append)
4734 (push kws1 org-todo-sets)
4735 (setq org-done-keywords (append org-done-keywords dws nil))
4736 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
4737 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
4738 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
4739 (setq org-todo-sets (nreverse org-todo-sets)
4740 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
4741 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
4742 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
4743 ;; Process the constants
4744 (when const
4745 (let (e cst)
4746 (while (setq e (pop const))
4747 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
4748 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
4749 (setq org-table-formula-constants-local cst)))
4751 ;; Process the tags.
4752 (when tags
4753 (let (e tgs)
4754 (while (setq e (pop tags))
4755 (cond
4756 ((equal e "{") (push '(:startgroup) tgs))
4757 ((equal e "}") (push '(:endgroup) tgs))
4758 ((string-match (org-re "^\\([[:alnum:]_@]+\\)(\\(.\\))$") e)
4759 (push (cons (match-string 1 e)
4760 (string-to-char (match-string 2 e)))
4761 tgs))
4762 (t (push (list e) tgs))))
4763 (org-set-local 'org-tag-alist nil)
4764 (while (setq e (pop tgs))
4765 (or (and (stringp (car e))
4766 (assoc (car e) org-tag-alist))
4767 (push e org-tag-alist))))))
4769 ;; Compute the regular expressions and other local variables
4770 (if (not org-done-keywords)
4771 (setq org-done-keywords (list (org-last org-todo-keywords-1))))
4772 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
4773 (length org-scheduled-string)))
4774 org-drawer-regexp
4775 (concat "^[ \t]*:\\("
4776 (mapconcat 'regexp-quote org-drawers "\\|")
4777 "\\):[ \t]*$")
4778 org-not-done-keywords
4779 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
4780 org-todo-regexp
4781 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords-1
4782 "\\|") "\\)\\>")
4783 org-not-done-regexp
4784 (concat "\\<\\("
4785 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
4786 "\\)\\>")
4787 org-todo-line-regexp
4788 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
4789 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4790 "\\)\\>\\)?[ \t]*\\(.*\\)")
4791 org-complex-heading-regexp
4792 (concat "^\\(\\*+\\)\\(?:[ \t]+\\("
4793 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4794 "\\)\\>\\)?\\(?:[ \t]*\\(\\[#.\\]\\)\\)?[ \t]*\\(.*?\\)"
4795 "\\(?:[ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
4796 org-nl-done-regexp
4797 (concat "\n\\*+[ \t]+"
4798 "\\(?:" (mapconcat 'regexp-quote org-done-keywords "\\|")
4799 "\\)" "\\>")
4800 org-todo-line-tags-regexp
4801 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
4802 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4803 (org-re
4804 "\\)\\>\\)? *\\(.*?\\([ \t]:[[:alnum:]:_@]+:[ \t]*\\)?$\\)"))
4805 org-looking-at-done-regexp
4806 (concat "^" "\\(?:"
4807 (mapconcat 'regexp-quote org-done-keywords "\\|") "\\)"
4808 "\\>")
4809 org-deadline-regexp (concat "\\<" org-deadline-string)
4810 org-deadline-time-regexp
4811 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
4812 org-deadline-line-regexp
4813 (concat "\\<\\(" org-deadline-string "\\).*")
4814 org-scheduled-regexp
4815 (concat "\\<" org-scheduled-string)
4816 org-scheduled-time-regexp
4817 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
4818 org-closed-time-regexp
4819 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
4820 org-keyword-time-regexp
4821 (concat "\\<\\(" org-scheduled-string
4822 "\\|" org-deadline-string
4823 "\\|" org-closed-string
4824 "\\|" org-clock-string "\\)"
4825 " *[[<]\\([^]>]+\\)[]>]")
4826 org-keyword-time-not-clock-regexp
4827 (concat "\\<\\(" org-scheduled-string
4828 "\\|" org-deadline-string
4829 "\\|" org-closed-string
4830 "\\)"
4831 " *[[<]\\([^]>]+\\)[]>]")
4832 org-maybe-keyword-time-regexp
4833 (concat "\\(\\<\\(" org-scheduled-string
4834 "\\|" org-deadline-string
4835 "\\|" org-closed-string
4836 "\\|" org-clock-string "\\)\\)?"
4837 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
4838 org-planning-or-clock-line-re
4839 (concat "\\(?:^[ \t]*\\(" org-scheduled-string
4840 "\\|" org-deadline-string
4841 "\\|" org-closed-string "\\|" org-clock-string
4842 "\\)\\>\\)")
4844 (org-compute-latex-and-specials-regexp)
4845 (org-set-font-lock-defaults)))
4847 (defun org-extract-log-state-settings (x)
4848 "Extract the log state setting from a TODO keyword string.
4849 This will extract info from a string like \"WAIT(w@/!)\"."
4850 (let (kw key log1 log2)
4851 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
4852 (setq kw (match-string 1 x)
4853 key (and (match-end 2) (match-string 2 x))
4854 log1 (and (match-end 3) (match-string 3 x))
4855 log2 (and (match-end 4) (match-string 4 x)))
4856 (and (or log1 log2)
4857 (list kw
4858 (and log1 (if (equal log1 "!") 'time 'note))
4859 (and log2 (if (equal log2 "!") 'time 'note)))))))
4861 (defun org-remove-keyword-keys (list)
4862 "Remove a pair of parenthesis at the end of each string in LIST."
4863 (mapcar (lambda (x)
4864 (if (string-match "(.*)$" x)
4865 (substring x 0 (match-beginning 0))
4867 list))
4869 ;; FIXME: this could be done much better, using second characters etc.
4870 (defun org-assign-fast-keys (alist)
4871 "Assign fast keys to a keyword-key alist.
4872 Respect keys that are already there."
4873 (let (new e k c c1 c2 (char ?a))
4874 (while (setq e (pop alist))
4875 (cond
4876 ((equal e '(:startgroup)) (push e new))
4877 ((equal e '(:endgroup)) (push e new))
4879 (setq k (car e) c2 nil)
4880 (if (cdr e)
4881 (setq c (cdr e))
4882 ;; automatically assign a character.
4883 (setq c1 (string-to-char
4884 (downcase (substring
4885 k (if (= (string-to-char k) ?@) 1 0)))))
4886 (if (or (rassoc c1 new) (rassoc c1 alist))
4887 (while (or (rassoc char new) (rassoc char alist))
4888 (setq char (1+ char)))
4889 (setq c2 c1))
4890 (setq c (or c2 char)))
4891 (push (cons k c) new))))
4892 (nreverse new)))
4894 ;;; Some variables ujsed in various places
4896 (defvar org-window-configuration nil
4897 "Used in various places to store a window configuration.")
4898 (defvar org-finish-function nil
4899 "Function to be called when `C-c C-c' is used.
4900 This is for getting out of special buffers like remember.")
4903 ;; FIXME: Occasionally check by commenting these, to make sure
4904 ;; no other functions uses these, forgetting to let-bind them.
4905 (defvar entry)
4906 (defvar state)
4907 (defvar last-state)
4908 (defvar date)
4909 (defvar description)
4911 ;; Defined somewhere in this file, but used before definition.
4912 (defvar orgtbl-mode-menu) ; defined when orgtbl mode get initialized
4913 (defvar org-agenda-buffer-name)
4914 (defvar org-agenda-undo-list)
4915 (defvar org-agenda-pending-undo-list)
4916 (defvar org-agenda-overriding-header)
4917 (defvar orgtbl-mode)
4918 (defvar org-html-entities)
4919 (defvar org-struct-menu)
4920 (defvar org-org-menu)
4921 (defvar org-tbl-menu)
4922 (defvar org-agenda-keymap)
4924 ;;;; Emacs/XEmacs compatibility
4926 ;; Overlay compatibility functions
4927 (defun org-make-overlay (beg end &optional buffer)
4928 (if (featurep 'xemacs)
4929 (make-extent beg end buffer)
4930 (make-overlay beg end buffer)))
4931 (defun org-delete-overlay (ovl)
4932 (if (featurep 'xemacs) (delete-extent ovl) (delete-overlay ovl)))
4933 (defun org-detach-overlay (ovl)
4934 (if (featurep 'xemacs) (detach-extent ovl) (delete-overlay ovl)))
4935 (defun org-move-overlay (ovl beg end &optional buffer)
4936 (if (featurep 'xemacs)
4937 (set-extent-endpoints ovl beg end (or buffer (current-buffer)))
4938 (move-overlay ovl beg end buffer)))
4939 (defun org-overlay-put (ovl prop value)
4940 (if (featurep 'xemacs)
4941 (set-extent-property ovl prop value)
4942 (overlay-put ovl prop value)))
4943 (defun org-overlay-display (ovl text &optional face evap)
4944 "Make overlay OVL display TEXT with face FACE."
4945 (if (featurep 'xemacs)
4946 (let ((gl (make-glyph text)))
4947 (and face (set-glyph-face gl face))
4948 (set-extent-property ovl 'invisible t)
4949 (set-extent-property ovl 'end-glyph gl))
4950 (overlay-put ovl 'display text)
4951 (if face (overlay-put ovl 'face face))
4952 (if evap (overlay-put ovl 'evaporate t))))
4953 (defun org-overlay-before-string (ovl text &optional face evap)
4954 "Make overlay OVL display TEXT with face FACE."
4955 (if (featurep 'xemacs)
4956 (let ((gl (make-glyph text)))
4957 (and face (set-glyph-face gl face))
4958 (set-extent-property ovl 'begin-glyph gl))
4959 (if face (org-add-props text nil 'face face))
4960 (overlay-put ovl 'before-string text)
4961 (if evap (overlay-put ovl 'evaporate t))))
4962 (defun org-overlay-get (ovl prop)
4963 (if (featurep 'xemacs)
4964 (extent-property ovl prop)
4965 (overlay-get ovl prop)))
4966 (defun org-overlays-at (pos)
4967 (if (featurep 'xemacs) (extents-at pos) (overlays-at pos)))
4968 (defun org-overlays-in (&optional start end)
4969 (if (featurep 'xemacs)
4970 (extent-list nil start end)
4971 (overlays-in start end)))
4972 (defun org-overlay-start (o)
4973 (if (featurep 'xemacs) (extent-start-position o) (overlay-start o)))
4974 (defun org-overlay-end (o)
4975 (if (featurep 'xemacs) (extent-end-position o) (overlay-end o)))
4976 (defun org-find-overlays (prop &optional pos delete)
4977 "Find all overlays specifying PROP at POS or point.
4978 If DELETE is non-nil, delete all those overlays."
4979 (let ((overlays (org-overlays-at (or pos (point))))
4980 ov found)
4981 (while (setq ov (pop overlays))
4982 (if (org-overlay-get ov prop)
4983 (if delete (org-delete-overlay ov) (push ov found))))
4984 found))
4986 ;; Region compatibility
4988 (defun org-add-hook (hook function &optional append local)
4989 "Add-hook, compatible with both Emacsen."
4990 (if (and local (featurep 'xemacs))
4991 (add-local-hook hook function append)
4992 (add-hook hook function append local)))
4994 (defvar org-ignore-region nil
4995 "To temporarily disable the active region.")
4997 (defun org-region-active-p ()
4998 "Is `transient-mark-mode' on and the region active?
4999 Works on both Emacs and XEmacs."
5000 (if org-ignore-region
5002 (if (featurep 'xemacs)
5003 (and zmacs-regions (region-active-p))
5004 (if (fboundp 'use-region-p)
5005 (use-region-p)
5006 (and transient-mark-mode mark-active))))) ; Emacs 22 and before
5008 ;; Invisibility compatibility
5010 (defun org-add-to-invisibility-spec (arg)
5011 "Add elements to `buffer-invisibility-spec'.
5012 See documentation for `buffer-invisibility-spec' for the kind of elements
5013 that can be added."
5014 (cond
5015 ((fboundp 'add-to-invisibility-spec)
5016 (add-to-invisibility-spec arg))
5017 ((or (null buffer-invisibility-spec) (eq buffer-invisibility-spec t))
5018 (setq buffer-invisibility-spec (list arg)))
5020 (setq buffer-invisibility-spec
5021 (cons arg buffer-invisibility-spec)))))
5023 (defun org-remove-from-invisibility-spec (arg)
5024 "Remove elements from `buffer-invisibility-spec'."
5025 (if (fboundp 'remove-from-invisibility-spec)
5026 (remove-from-invisibility-spec arg)
5027 (if (consp buffer-invisibility-spec)
5028 (setq buffer-invisibility-spec
5029 (delete arg buffer-invisibility-spec)))))
5031 (defun org-in-invisibility-spec-p (arg)
5032 "Is ARG a member of `buffer-invisibility-spec'?"
5033 (if (consp buffer-invisibility-spec)
5034 (member arg buffer-invisibility-spec)
5035 nil))
5037 ;;;; Define the Org-mode
5039 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
5040 (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."))
5043 ;; We use a before-change function to check if a table might need
5044 ;; an update.
5045 (defvar org-table-may-need-update t
5046 "Indicates that a table might need an update.
5047 This variable is set by `org-before-change-function'.
5048 `org-table-align' sets it back to nil.")
5049 (defvar org-mode-map)
5050 (defvar org-mode-hook nil)
5051 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
5052 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
5053 (defvar org-table-buffer-is-an nil)
5054 (defconst org-outline-regexp "\\*+ ")
5056 ;;;###autoload
5057 (define-derived-mode org-mode outline-mode "Org"
5058 "Outline-based notes management and organizer, alias
5059 \"Carsten's outline-mode for keeping track of everything.\"
5061 Org-mode develops organizational tasks around a NOTES file which
5062 contains information about projects as plain text. Org-mode is
5063 implemented on top of outline-mode, which is ideal to keep the content
5064 of large files well structured. It supports ToDo items, deadlines and
5065 time stamps, which magically appear in the diary listing of the Emacs
5066 calendar. Tables are easily created with a built-in table editor.
5067 Plain text URL-like links connect to websites, emails (VM), Usenet
5068 messages (Gnus), BBDB entries, and any files related to the project.
5069 For printing and sharing of notes, an Org-mode file (or a part of it)
5070 can be exported as a structured ASCII or HTML file.
5072 The following commands are available:
5074 \\{org-mode-map}"
5076 ;; Get rid of Outline menus, they are not needed
5077 ;; Need to do this here because define-derived-mode sets up
5078 ;; the keymap so late. Still, it is a waste to call this each time
5079 ;; we switch another buffer into org-mode.
5080 (if (featurep 'xemacs)
5081 (when (boundp 'outline-mode-menu-heading)
5082 ;; Assume this is Greg's port, it used easymenu
5083 (easy-menu-remove outline-mode-menu-heading)
5084 (easy-menu-remove outline-mode-menu-show)
5085 (easy-menu-remove outline-mode-menu-hide))
5086 (define-key org-mode-map [menu-bar headings] 'undefined)
5087 (define-key org-mode-map [menu-bar hide] 'undefined)
5088 (define-key org-mode-map [menu-bar show] 'undefined))
5090 (easy-menu-add org-org-menu)
5091 (easy-menu-add org-tbl-menu)
5092 (org-install-agenda-files-menu)
5093 (if org-descriptive-links (org-add-to-invisibility-spec '(org-link)))
5094 (org-add-to-invisibility-spec '(org-cwidth))
5095 (when (featurep 'xemacs)
5096 (org-set-local 'line-move-ignore-invisible t))
5097 (org-set-local 'outline-regexp org-outline-regexp)
5098 (org-set-local 'outline-level 'org-outline-level)
5099 (when (and org-ellipsis
5100 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
5101 (fboundp 'make-glyph-code))
5102 (unless org-display-table
5103 (setq org-display-table (make-display-table)))
5104 (set-display-table-slot
5105 org-display-table 4
5106 (vconcat (mapcar
5107 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
5108 org-ellipsis)))
5109 (if (stringp org-ellipsis) org-ellipsis "..."))))
5110 (setq buffer-display-table org-display-table))
5111 (org-set-regexps-and-options)
5112 ;; Calc embedded
5113 (org-set-local 'calc-embedded-open-mode "# ")
5114 (modify-syntax-entry ?# "<")
5115 (modify-syntax-entry ?@ "w")
5116 (if org-startup-truncated (setq truncate-lines t))
5117 (org-set-local 'font-lock-unfontify-region-function
5118 'org-unfontify-region)
5119 ;; Activate before-change-function
5120 (org-set-local 'org-table-may-need-update t)
5121 (org-add-hook 'before-change-functions 'org-before-change-function nil
5122 'local)
5123 ;; Check for running clock before killing a buffer
5124 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
5125 ;; Paragraphs and auto-filling
5126 (org-set-autofill-regexps)
5127 (setq indent-line-function 'org-indent-line-function)
5128 (org-update-radio-target-regexp)
5130 ;; Comment characters
5131 ; (org-set-local 'comment-start "#") ;; FIXME: this breaks wrapping
5132 (org-set-local 'comment-padding " ")
5134 ;; Align options lines
5135 (org-set-local
5136 'align-mode-rules-list
5137 '((org-in-buffer-settings
5138 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5139 (modes . '(org-mode)))))
5141 ;; Imenu
5142 (org-set-local 'imenu-create-index-function
5143 'org-imenu-get-tree)
5145 ;; Make isearch reveal context
5146 (if (or (featurep 'xemacs)
5147 (not (boundp 'outline-isearch-open-invisible-function)))
5148 ;; Emacs 21 and XEmacs make use of the hook
5149 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
5150 ;; Emacs 22 deals with this through a special variable
5151 (org-set-local 'outline-isearch-open-invisible-function
5152 (lambda (&rest ignore) (org-show-context 'isearch))))
5154 ;; If empty file that did not turn on org-mode automatically, make it to.
5155 (if (and org-insert-mode-line-in-empty-file
5156 (interactive-p)
5157 (= (point-min) (point-max)))
5158 (insert "# -*- mode: org -*-\n\n"))
5160 (unless org-inhibit-startup
5161 (when org-startup-align-all-tables
5162 (let ((bmp (buffer-modified-p)))
5163 (org-table-map-tables 'org-table-align)
5164 (set-buffer-modified-p bmp)))
5165 (org-cycle-hide-drawers 'all)
5166 (cond
5167 ((eq org-startup-folded t)
5168 (org-cycle '(4)))
5169 ((eq org-startup-folded 'content)
5170 (let ((this-command 'org-cycle) (last-command 'org-cycle))
5171 (org-cycle '(4)) (org-cycle '(4)))))))
5173 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
5175 (defsubst org-call-with-arg (command arg)
5176 "Call COMMAND interactively, but pretend prefix are was ARG."
5177 (let ((current-prefix-arg arg)) (call-interactively command)))
5179 (defsubst org-current-line (&optional pos)
5180 (save-excursion
5181 (and pos (goto-char pos))
5182 ;; works also in narrowed buffer, because we start at 1, not point-min
5183 (+ (if (bolp) 1 0) (count-lines 1 (point)))))
5185 (defun org-current-time ()
5186 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
5187 (if (> (car org-time-stamp-rounding-minutes) 1)
5188 (let ((r (car org-time-stamp-rounding-minutes))
5189 (time (decode-time)))
5190 (apply 'encode-time
5191 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5192 (nthcdr 2 time))))
5193 (current-time)))
5195 (defun org-add-props (string plist &rest props)
5196 "Add text properties to entire string, from beginning to end.
5197 PLIST may be a list of properties, PROPS are individual properties and values
5198 that will be added to PLIST. Returns the string that was modified."
5199 (add-text-properties
5200 0 (length string) (if props (append plist props) plist) string)
5201 string)
5202 (put 'org-add-props 'lisp-indent-function 2)
5205 ;;;; Font-Lock stuff, including the activators
5207 (defvar org-mouse-map (make-sparse-keymap))
5208 (org-defkey org-mouse-map
5209 (if (featurep 'xemacs) [button2] [mouse-2]) 'org-open-at-mouse)
5210 (org-defkey org-mouse-map
5211 (if (featurep 'xemacs) [button3] [mouse-3]) 'org-find-file-at-mouse)
5212 (when org-mouse-1-follows-link
5213 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5214 (when org-tab-follows-link
5215 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5216 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5217 (when org-return-follows-link
5218 (org-defkey org-mouse-map [(return)] 'org-open-at-point)
5219 (org-defkey org-mouse-map "\C-m" 'org-open-at-point))
5221 (require 'font-lock)
5223 (defconst org-non-link-chars "]\t\n\r<>")
5224 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news" "bbdb" "vm"
5225 "wl" "mhe" "rmail" "gnus" "shell" "info" "elisp" "message"))
5226 (defvar org-link-re-with-space nil
5227 "Matches a link with spaces, optional angular brackets around it.")
5228 (defvar org-link-re-with-space2 nil
5229 "Matches a link with spaces, optional angular brackets around it.")
5230 (defvar org-angle-link-re nil
5231 "Matches link with angular brackets, spaces are allowed.")
5232 (defvar org-plain-link-re nil
5233 "Matches plain link, without spaces.")
5234 (defvar org-bracket-link-regexp nil
5235 "Matches a link in double brackets.")
5236 (defvar org-bracket-link-analytic-regexp nil
5237 "Regular expression used to analyze links.
5238 Here is what the match groups contain after a match:
5239 1: http:
5240 2: http
5241 3: path
5242 4: [desc]
5243 5: desc")
5244 (defvar org-any-link-re nil
5245 "Regular expression matching any link.")
5247 (defun org-make-link-regexps ()
5248 "Update the link regular expressions.
5249 This should be called after the variable `org-link-types' has changed."
5250 (setq org-link-re-with-space
5251 (concat
5252 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
5253 "\\([^" org-non-link-chars " ]"
5254 "[^" org-non-link-chars "]*"
5255 "[^" org-non-link-chars " ]\\)>?")
5256 org-link-re-with-space2
5257 (concat
5258 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
5259 "\\([^" org-non-link-chars " ]"
5260 "[^]\t\n\r]*"
5261 "[^" org-non-link-chars " ]\\)>?")
5262 org-angle-link-re
5263 (concat
5264 "<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
5265 "\\([^" org-non-link-chars " ]"
5266 "[^" org-non-link-chars "]*"
5267 "\\)>")
5268 org-plain-link-re
5269 (concat
5270 "\\<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
5271 "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5272 org-bracket-link-regexp
5273 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5274 org-bracket-link-analytic-regexp
5275 (concat
5276 "\\[\\["
5277 "\\(\\(" (mapconcat 'identity org-link-types "\\|") "\\):\\)?"
5278 "\\([^]]+\\)"
5279 "\\]"
5280 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5281 "\\]")
5282 org-any-link-re
5283 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5284 org-angle-link-re "\\)\\|\\("
5285 org-plain-link-re "\\)")))
5287 (org-make-link-regexps)
5289 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)>"
5290 "Regular expression for fast time stamp matching.")
5291 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)[]>]"
5292 "Regular expression for fast time stamp matching.")
5293 (defconst org-ts-regexp0 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5294 "Regular expression matching time strings for analysis.
5295 This one does not require the space after the date, so it can be used
5296 on a string that terminates immediately after the date.")
5297 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) +\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5298 "Regular expression matching time strings for analysis.")
5299 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
5300 "Regular expression matching time stamps, with groups.")
5301 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
5302 "Regular expression matching time stamps (also [..]), with groups.")
5303 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
5304 "Regular expression matching a time stamp range.")
5305 (defconst org-tr-regexp-both
5306 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
5307 "Regular expression matching a time stamp range.")
5308 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
5309 org-ts-regexp "\\)?")
5310 "Regular expression matching a time stamp or time stamp range.")
5311 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
5312 org-ts-regexp-both "\\)?")
5313 "Regular expression matching a time stamp or time stamp range.
5314 The time stamps may be either active or inactive.")
5316 (defvar org-emph-face nil)
5318 (defun org-do-emphasis-faces (limit)
5319 "Run through the buffer and add overlays to links."
5320 (let (rtn)
5321 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5322 (if (not (= (char-after (match-beginning 3))
5323 (char-after (match-beginning 4))))
5324 (progn
5325 (setq rtn t)
5326 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5327 'face
5328 (nth 1 (assoc (match-string 3)
5329 org-emphasis-alist)))
5330 (add-text-properties (match-beginning 2) (match-end 2)
5331 '(font-lock-multiline t))
5332 (when org-hide-emphasis-markers
5333 (add-text-properties (match-end 4) (match-beginning 5)
5334 '(invisible org-link))
5335 (add-text-properties (match-beginning 3) (match-end 3)
5336 '(invisible org-link)))))
5337 (backward-char 1))
5338 rtn))
5340 (defun org-emphasize (&optional char)
5341 "Insert or change an emphasis, i.e. a font like bold or italic.
5342 If there is an active region, change that region to a new emphasis.
5343 If there is no region, just insert the marker characters and position
5344 the cursor between them.
5345 CHAR should be either the marker character, or the first character of the
5346 HTML tag associated with that emphasis. If CHAR is a space, the means
5347 to remove the emphasis of the selected region.
5348 If char is not given (for example in an interactive call) it
5349 will be prompted for."
5350 (interactive)
5351 (let ((eal org-emphasis-alist) e det
5352 (erc org-emphasis-regexp-components)
5353 (prompt "")
5354 (string "") beg end move tag c s)
5355 (if (org-region-active-p)
5356 (setq beg (region-beginning) end (region-end)
5357 string (buffer-substring beg end))
5358 (setq move t))
5360 (while (setq e (pop eal))
5361 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
5362 c (aref tag 0))
5363 (push (cons c (string-to-char (car e))) det)
5364 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
5365 (substring tag 1)))))
5366 (unless char
5367 (message "%s" (concat "Emphasis marker or tag:" prompt))
5368 (setq char (read-char-exclusive)))
5369 (setq char (or (cdr (assoc char det)) char))
5370 (if (equal char ?\ )
5371 (setq s "" move nil)
5372 (unless (assoc (char-to-string char) org-emphasis-alist)
5373 (error "No such emphasis marker: \"%c\"" char))
5374 (setq s (char-to-string char)))
5375 (while (and (> (length string) 1)
5376 (equal (substring string 0 1) (substring string -1))
5377 (assoc (substring string 0 1) org-emphasis-alist))
5378 (setq string (substring string 1 -1)))
5379 (setq string (concat s string s))
5380 (if beg (delete-region beg end))
5381 (unless (or (bolp)
5382 (string-match (concat "[" (nth 0 erc) "\n]")
5383 (char-to-string (char-before (point)))))
5384 (insert " "))
5385 (unless (string-match (concat "[" (nth 1 erc) "\n]")
5386 (char-to-string (char-after (point))))
5387 (insert " ") (backward-char 1))
5388 (insert string)
5389 (and move (backward-char 1))))
5391 (defconst org-nonsticky-props
5392 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
5395 (defun org-activate-plain-links (limit)
5396 "Run through the buffer and add overlays to links."
5397 (catch 'exit
5398 (let (f)
5399 (while (re-search-forward org-plain-link-re limit t)
5400 (setq f (get-text-property (match-beginning 0) 'face))
5401 (if (or (eq f 'org-tag)
5402 (and (listp f) (memq 'org-tag f)))
5404 (add-text-properties (match-beginning 0) (match-end 0)
5405 (list 'mouse-face 'highlight
5406 'rear-nonsticky org-nonsticky-props
5407 'keymap org-mouse-map
5409 (throw 'exit t))))))
5411 (defun org-activate-code (limit)
5412 (if (re-search-forward "^[ \t]*\\(:.*\\)" limit t)
5413 (unless (get-text-property (match-beginning 1) 'face)
5414 (remove-text-properties (match-beginning 0) (match-end 0)
5415 '(display t invisible t intangible t))
5416 t)))
5418 (defun org-activate-angle-links (limit)
5419 "Run through the buffer and add overlays to links."
5420 (if (re-search-forward org-angle-link-re limit t)
5421 (progn
5422 (add-text-properties (match-beginning 0) (match-end 0)
5423 (list 'mouse-face 'highlight
5424 'rear-nonsticky org-nonsticky-props
5425 'keymap org-mouse-map
5427 t)))
5429 (defmacro org-maybe-intangible (props)
5430 "Add '(intangigble t) to PROPS if Emacs version is earlier than Emacs 22.
5431 In emacs 21, invisible text is not avoided by the command loop, so the
5432 intangible property is needed to make sure point skips this text.
5433 In Emacs 22, this is not necessary. The intangible text property has
5434 led to problems with flyspell. These problems are fixed in flyspell.el,
5435 but we still avoid setting the property in Emacs 22 and later.
5436 We use a macro so that the test can happen at compilation time."
5437 (if (< emacs-major-version 22)
5438 `(append '(intangible t) ,props)
5439 props))
5441 (defun org-activate-bracket-links (limit)
5442 "Run through the buffer and add overlays to bracketed links."
5443 (if (re-search-forward org-bracket-link-regexp limit t)
5444 (let* ((help (concat "LINK: "
5445 (org-match-string-no-properties 1)))
5446 ;; FIXME: above we should remove the escapes.
5447 ;; but that requires another match, protecting match data,
5448 ;; a lot of overhead for font-lock.
5449 (ip (org-maybe-intangible
5450 (list 'invisible 'org-link 'rear-nonsticky org-nonsticky-props
5451 'keymap org-mouse-map 'mouse-face 'highlight
5452 'font-lock-multiline t 'help-echo help)))
5453 (vp (list 'rear-nonsticky org-nonsticky-props
5454 'keymap org-mouse-map 'mouse-face 'highlight
5455 ' font-lock-multiline t 'help-echo help)))
5456 ;; We need to remove the invisible property here. Table narrowing
5457 ;; may have made some of this invisible.
5458 (remove-text-properties (match-beginning 0) (match-end 0)
5459 '(invisible nil))
5460 (if (match-end 3)
5461 (progn
5462 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
5463 (add-text-properties (match-beginning 3) (match-end 3) vp)
5464 (add-text-properties (match-end 3) (match-end 0) ip))
5465 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
5466 (add-text-properties (match-beginning 1) (match-end 1) vp)
5467 (add-text-properties (match-end 1) (match-end 0) ip))
5468 t)))
5470 (defun org-activate-dates (limit)
5471 "Run through the buffer and add overlays to dates."
5472 (if (re-search-forward org-tsr-regexp-both limit t)
5473 (progn
5474 (add-text-properties (match-beginning 0) (match-end 0)
5475 (list 'mouse-face 'highlight
5476 'rear-nonsticky org-nonsticky-props
5477 'keymap org-mouse-map))
5478 (when org-display-custom-times
5479 (if (match-end 3)
5480 (org-display-custom-time (match-beginning 3) (match-end 3)))
5481 (org-display-custom-time (match-beginning 1) (match-end 1)))
5482 t)))
5484 (defvar org-target-link-regexp nil
5485 "Regular expression matching radio targets in plain text.")
5486 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
5487 "Regular expression matching a link target.")
5488 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
5489 "Regular expression matching a radio target.")
5490 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
5491 "Regular expression matching any target.")
5493 (defun org-activate-target-links (limit)
5494 "Run through the buffer and add overlays to target matches."
5495 (when org-target-link-regexp
5496 (let ((case-fold-search t))
5497 (if (re-search-forward org-target-link-regexp limit t)
5498 (progn
5499 (add-text-properties (match-beginning 0) (match-end 0)
5500 (list 'mouse-face 'highlight
5501 'rear-nonsticky org-nonsticky-props
5502 'keymap org-mouse-map
5503 'help-echo "Radio target link"
5504 'org-linked-text t))
5505 t)))))
5507 (defun org-update-radio-target-regexp ()
5508 "Find all radio targets in this file and update the regular expression."
5509 (interactive)
5510 (when (memq 'radio org-activate-links)
5511 (setq org-target-link-regexp
5512 (org-make-target-link-regexp (org-all-targets 'radio)))
5513 (org-restart-font-lock)))
5515 (defun org-hide-wide-columns (limit)
5516 (let (s e)
5517 (setq s (text-property-any (point) (or limit (point-max))
5518 'org-cwidth t))
5519 (when s
5520 (setq e (next-single-property-change s 'org-cwidth))
5521 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
5522 (goto-char e)
5523 t)))
5525 (defvar org-latex-and-specials-regexp nil
5526 "Regular expression for highlighting export special stuff.")
5527 (defvar org-match-substring-regexp)
5528 (defvar org-match-substring-with-braces-regexp)
5529 (defvar org-export-html-special-string-regexps)
5531 (defun org-compute-latex-and-specials-regexp ()
5532 "Compute regular expression for stuff treated specially by exporters."
5533 (if (not org-highlight-latex-fragments-and-specials)
5534 (org-set-local 'org-latex-and-specials-regexp nil)
5535 (let*
5536 ((matchers (plist-get org-format-latex-options :matchers))
5537 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
5538 org-latex-regexps)))
5539 (options (org-combine-plists (org-default-export-plist)
5540 (org-infile-export-plist)))
5541 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
5542 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
5543 (org-export-with-TeX-macros (plist-get options :TeX-macros))
5544 (org-export-html-expand (plist-get options :expand-quoted-html))
5545 (org-export-with-special-strings (plist-get options :special-strings))
5546 (re-sub
5547 (cond
5548 ((equal org-export-with-sub-superscripts '{})
5549 (list org-match-substring-with-braces-regexp))
5550 (org-export-with-sub-superscripts
5551 (list org-match-substring-regexp))
5552 (t nil)))
5553 (re-latex
5554 (if org-export-with-LaTeX-fragments
5555 (mapcar (lambda (x) (nth 1 x)) latexs)))
5556 (re-macros
5557 (if org-export-with-TeX-macros
5558 (list (concat "\\\\"
5559 (regexp-opt
5560 (append (mapcar 'car org-html-entities)
5561 (if (boundp 'org-latex-entities)
5562 org-latex-entities nil))
5563 'words))) ; FIXME
5565 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
5566 (re-special (if org-export-with-special-strings
5567 (mapcar (lambda (x) (car x))
5568 org-export-html-special-string-regexps)))
5569 (re-rest
5570 (delq nil
5571 (list
5572 (if org-export-html-expand "@<[^>\n]+>")
5573 ))))
5574 (org-set-local
5575 'org-latex-and-specials-regexp
5576 (mapconcat 'identity (append re-latex re-sub re-macros re-special
5577 re-rest) "\\|")))))
5579 (defface org-latex-and-export-specials
5580 (let ((font (cond ((assq :inherit custom-face-attributes)
5581 '(:inherit underline))
5582 (t '(:underline t)))))
5583 `((((class grayscale) (background light))
5584 (:foreground "DimGray" ,@font))
5585 (((class grayscale) (background dark))
5586 (:foreground "LightGray" ,@font))
5587 (((class color) (background light))
5588 (:foreground "SaddleBrown"))
5589 (((class color) (background dark))
5590 (:foreground "burlywood"))
5591 (t (,@font))))
5592 "Face used to highlight math latex and other special exporter stuff."
5593 :group 'org-faces)
5595 (defun org-do-latex-and-special-faces (limit)
5596 "Run through the buffer and add overlays to links."
5597 (when org-latex-and-specials-regexp
5598 (let (rtn d)
5599 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
5600 limit t))
5601 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
5602 'face))
5603 '(org-code org-verbatim underline)))
5604 (progn
5605 (setq rtn t
5606 d (cond ((member (char-after (1+ (match-beginning 0)))
5607 '(?_ ?^)) 1)
5608 (t 0)))
5609 (font-lock-prepend-text-property
5610 (+ d (match-beginning 0)) (match-end 0)
5611 'face 'org-latex-and-export-specials)
5612 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
5613 '(font-lock-multiline t)))))
5614 rtn)))
5616 (defun org-restart-font-lock ()
5617 "Restart font-lock-mode, to force refontification."
5618 (when (and (boundp 'font-lock-mode) font-lock-mode)
5619 (font-lock-mode -1)
5620 (font-lock-mode 1)))
5622 (defun org-all-targets (&optional radio)
5623 "Return a list of all targets in this file.
5624 With optional argument RADIO, only find radio targets."
5625 (let ((re (if radio org-radio-target-regexp org-target-regexp))
5626 rtn)
5627 (save-excursion
5628 (goto-char (point-min))
5629 (while (re-search-forward re nil t)
5630 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
5631 rtn)))
5633 (defun org-make-target-link-regexp (targets)
5634 "Make regular expression matching all strings in TARGETS.
5635 The regular expression finds the targets also if there is a line break
5636 between words."
5637 (and targets
5638 (concat
5639 "\\<\\("
5640 (mapconcat
5641 (lambda (x)
5642 (while (string-match " +" x)
5643 (setq x (replace-match "\\s-+" t t x)))
5645 targets
5646 "\\|")
5647 "\\)\\>")))
5649 (defun org-activate-tags (limit)
5650 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \r\n]") limit t)
5651 (progn
5652 (add-text-properties (match-beginning 1) (match-end 1)
5653 (list 'mouse-face 'highlight
5654 'rear-nonsticky org-nonsticky-props
5655 'keymap org-mouse-map))
5656 t)))
5658 (defun org-outline-level ()
5659 (save-excursion
5660 (looking-at outline-regexp)
5661 (if (match-beginning 1)
5662 (+ (org-get-string-indentation (match-string 1)) 1000)
5663 (1- (- (match-end 0) (match-beginning 0))))))
5665 (defvar org-font-lock-keywords nil)
5667 (defconst org-property-re (org-re "^[ \t]*\\(:\\([[:alnum:]_]+\\):\\)[ \t]*\\(\\S-.*\\)")
5668 "Regular expression matching a property line.")
5670 (defun org-set-font-lock-defaults ()
5671 (let* ((em org-fontify-emphasized-text)
5672 (lk org-activate-links)
5673 (org-font-lock-extra-keywords
5674 (list
5675 ;; Headlines
5676 '("^\\(\\**\\)\\(\\* \\)\\(.*\\)" (1 (org-get-level-face 1))
5677 (2 (org-get-level-face 2)) (3 (org-get-level-face 3)))
5678 ;; Table lines
5679 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
5680 (1 'org-table t))
5681 ;; Table internals
5682 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
5683 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
5684 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
5685 ;; Drawers
5686 (list org-drawer-regexp '(0 'org-special-keyword t))
5687 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
5688 ;; Properties
5689 (list org-property-re
5690 '(1 'org-special-keyword t)
5691 '(3 'org-property-value t))
5692 (if org-format-transports-properties-p
5693 '("| *\\(<[0-9]+>\\) *" (1 'org-formula t)))
5694 ;; Links
5695 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
5696 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
5697 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
5698 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
5699 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
5700 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
5701 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
5702 '(org-hide-wide-columns (0 nil append))
5703 ;; TODO lines
5704 (list (concat "^\\*+[ \t]+" org-todo-regexp)
5705 '(1 (org-get-todo-face 1) t))
5706 ;; DONE
5707 (if org-fontify-done-headline
5708 (list (concat "^[*]+ +\\<\\("
5709 (mapconcat 'regexp-quote org-done-keywords "\\|")
5710 "\\)\\(.*\\)")
5711 '(2 'org-headline-done t))
5712 nil)
5713 ;; Priorities
5714 (list (concat "\\[#[A-Z0-9]\\]") '(0 'org-special-keyword t))
5715 ;; Special keywords
5716 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
5717 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
5718 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
5719 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
5720 ;; Emphasis
5721 (if em
5722 (if (featurep 'xemacs)
5723 '(org-do-emphasis-faces (0 nil append))
5724 '(org-do-emphasis-faces)))
5725 ;; Checkboxes
5726 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)"
5727 2 'bold prepend)
5728 (if org-provide-checkbox-statistics
5729 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
5730 (0 (org-get-checkbox-statistics-face) t)))
5731 (list (concat "^\\*+ \\(.*:" org-archive-tag ":.*\\)")
5732 '(1 'org-archived prepend))
5733 ;; Specials
5734 '(org-do-latex-and-special-faces)
5735 ;; Code
5736 '(org-activate-code (1 'org-code t))
5737 ;; COMMENT
5738 (list (concat "^\\*+[ \t]+\\<\\(" org-comment-string
5739 "\\|" org-quote-string "\\)\\>")
5740 '(1 'org-special-keyword t))
5741 '("^#.*" (0 'font-lock-comment-face t))
5743 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
5744 ;; Now set the full font-lock-keywords
5745 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
5746 (org-set-local 'font-lock-defaults
5747 '(org-font-lock-keywords t nil nil backward-paragraph))
5748 (kill-local-variable 'font-lock-keywords) nil))
5750 (defvar org-m nil)
5751 (defvar org-l nil)
5752 (defvar org-f nil)
5753 (defun org-get-level-face (n)
5754 "Get the right face for match N in font-lock matching of healdines."
5755 (setq org-l (- (match-end 2) (match-beginning 1) 1))
5756 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
5757 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
5758 (cond
5759 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
5760 ((eq n 2) org-f)
5761 (t (if org-level-color-stars-only nil org-f))))
5763 (defun org-get-todo-face (kwd)
5764 "Get the right face for a TODO keyword KWD.
5765 If KWD is a number, get the corresponding match group."
5766 (if (numberp kwd) (setq kwd (match-string kwd)))
5767 (or (cdr (assoc kwd org-todo-keyword-faces))
5768 (and (member kwd org-done-keywords) 'org-done)
5769 'org-todo))
5771 (defun org-unfontify-region (beg end &optional maybe_loudly)
5772 "Remove fontification and activation overlays from links."
5773 (font-lock-default-unfontify-region beg end)
5774 (let* ((buffer-undo-list t)
5775 (inhibit-read-only t) (inhibit-point-motion-hooks t)
5776 (inhibit-modification-hooks t)
5777 deactivate-mark buffer-file-name buffer-file-truename)
5778 (remove-text-properties beg end
5779 '(mouse-face t keymap t org-linked-text t
5780 invisible t intangible t))))
5782 ;;;; Visibility cycling, including org-goto and indirect buffer
5784 ;;; Cycling
5786 (defvar org-cycle-global-status nil)
5787 (make-variable-buffer-local 'org-cycle-global-status)
5788 (defvar org-cycle-subtree-status nil)
5789 (make-variable-buffer-local 'org-cycle-subtree-status)
5791 ;;;###autoload
5792 (defun org-cycle (&optional arg)
5793 "Visibility cycling for Org-mode.
5795 - When this function is called with a prefix argument, rotate the entire
5796 buffer through 3 states (global cycling)
5797 1. OVERVIEW: Show only top-level headlines.
5798 2. CONTENTS: Show all headlines of all levels, but no body text.
5799 3. SHOW ALL: Show everything.
5801 - When point is at the beginning of a headline, rotate the subtree started
5802 by this line through 3 different states (local cycling)
5803 1. FOLDED: Only the main headline is shown.
5804 2. CHILDREN: The main headline and the direct children are shown.
5805 From this state, you can move to one of the children
5806 and zoom in further.
5807 3. SUBTREE: Show the entire subtree, including body text.
5809 - When there is a numeric prefix, go up to a heading with level ARG, do
5810 a `show-subtree' and return to the previous cursor position. If ARG
5811 is negative, go up that many levels.
5813 - When point is not at the beginning of a headline, execute
5814 `indent-relative', like TAB normally does. See the option
5815 `org-cycle-emulate-tab' for details.
5817 - Special case: if point is at the beginning of the buffer and there is
5818 no headline in line 1, this function will act as if called with prefix arg.
5819 But only if also the variable `org-cycle-global-at-bob' is t."
5820 (interactive "P")
5821 (let* ((outline-regexp
5822 (if (and (org-mode-p) org-cycle-include-plain-lists)
5823 "\\(?:\\*+ \\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) \\)"
5824 outline-regexp))
5825 (bob-special (and org-cycle-global-at-bob (bobp)
5826 (not (looking-at outline-regexp))))
5827 (org-cycle-hook
5828 (if bob-special
5829 (delq 'org-optimize-window-after-visibility-change
5830 (copy-sequence org-cycle-hook))
5831 org-cycle-hook))
5832 (pos (point)))
5834 (if (or bob-special (equal arg '(4)))
5835 ;; special case: use global cycling
5836 (setq arg t))
5838 (cond
5840 ((org-at-table-p 'any)
5841 ;; Enter the table or move to the next field in the table
5842 (or (org-table-recognize-table.el)
5843 (progn
5844 (if arg (org-table-edit-field t)
5845 (org-table-justify-field-maybe)
5846 (call-interactively 'org-table-next-field)))))
5848 ((eq arg t) ;; Global cycling
5850 (cond
5851 ((and (eq last-command this-command)
5852 (eq org-cycle-global-status 'overview))
5853 ;; We just created the overview - now do table of contents
5854 ;; This can be slow in very large buffers, so indicate action
5855 (message "CONTENTS...")
5856 (org-content)
5857 (message "CONTENTS...done")
5858 (setq org-cycle-global-status 'contents)
5859 (run-hook-with-args 'org-cycle-hook 'contents))
5861 ((and (eq last-command this-command)
5862 (eq org-cycle-global-status 'contents))
5863 ;; We just showed the table of contents - now show everything
5864 (show-all)
5865 (message "SHOW ALL")
5866 (setq org-cycle-global-status 'all)
5867 (run-hook-with-args 'org-cycle-hook 'all))
5870 ;; Default action: go to overview
5871 (org-overview)
5872 (message "OVERVIEW")
5873 (setq org-cycle-global-status 'overview)
5874 (run-hook-with-args 'org-cycle-hook 'overview))))
5876 ((and org-drawers org-drawer-regexp
5877 (save-excursion
5878 (beginning-of-line 1)
5879 (looking-at org-drawer-regexp)))
5880 ;; Toggle block visibility
5881 (org-flag-drawer
5882 (not (get-char-property (match-end 0) 'invisible))))
5884 ((integerp arg)
5885 ;; Show-subtree, ARG levels up from here.
5886 (save-excursion
5887 (org-back-to-heading)
5888 (outline-up-heading (if (< arg 0) (- arg)
5889 (- (funcall outline-level) arg)))
5890 (org-show-subtree)))
5892 ((and (save-excursion (beginning-of-line 1) (looking-at outline-regexp))
5893 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
5894 ;; At a heading: rotate between three different views
5895 (org-back-to-heading)
5896 (let ((goal-column 0) eoh eol eos)
5897 ;; First, some boundaries
5898 (save-excursion
5899 (org-back-to-heading)
5900 (save-excursion
5901 (beginning-of-line 2)
5902 (while (and (not (eobp)) ;; this is like `next-line'
5903 (get-char-property (1- (point)) 'invisible))
5904 (beginning-of-line 2)) (setq eol (point)))
5905 (outline-end-of-heading) (setq eoh (point))
5906 (org-end-of-subtree t)
5907 (unless (eobp)
5908 (skip-chars-forward " \t\n")
5909 (beginning-of-line 1) ; in case this is an item
5911 (setq eos (1- (point))))
5912 ;; Find out what to do next and set `this-command'
5913 (cond
5914 ((= eos eoh)
5915 ;; Nothing is hidden behind this heading
5916 (message "EMPTY ENTRY")
5917 (setq org-cycle-subtree-status nil)
5918 (save-excursion
5919 (goto-char eos)
5920 (outline-next-heading)
5921 (if (org-invisible-p) (org-flag-heading nil))))
5922 ((or (>= eol eos)
5923 (not (string-match "\\S-" (buffer-substring eol eos))))
5924 ;; Entire subtree is hidden in one line: open it
5925 (org-show-entry)
5926 (show-children)
5927 (message "CHILDREN")
5928 (save-excursion
5929 (goto-char eos)
5930 (outline-next-heading)
5931 (if (org-invisible-p) (org-flag-heading nil)))
5932 (setq org-cycle-subtree-status 'children)
5933 (run-hook-with-args 'org-cycle-hook 'children))
5934 ((and (eq last-command this-command)
5935 (eq org-cycle-subtree-status 'children))
5936 ;; We just showed the children, now show everything.
5937 (org-show-subtree)
5938 (message "SUBTREE")
5939 (setq org-cycle-subtree-status 'subtree)
5940 (run-hook-with-args 'org-cycle-hook 'subtree))
5942 ;; Default action: hide the subtree.
5943 (hide-subtree)
5944 (message "FOLDED")
5945 (setq org-cycle-subtree-status 'folded)
5946 (run-hook-with-args 'org-cycle-hook 'folded)))))
5948 ;; TAB emulation
5949 (buffer-read-only (org-back-to-heading))
5951 ((org-try-cdlatex-tab))
5953 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
5954 (or (not (bolp))
5955 (not (looking-at outline-regexp))))
5956 (call-interactively (global-key-binding "\t")))
5958 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
5959 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
5960 (or (and (eq org-cycle-emulate-tab 'white)
5961 (= (match-end 0) (point-at-eol)))
5962 (and (eq org-cycle-emulate-tab 'whitestart)
5963 (>= (match-end 0) pos))))
5965 (eq org-cycle-emulate-tab t))
5966 ; (if (and (looking-at "[ \n\r\t]")
5967 ; (string-match "^[ \t]*$" (buffer-substring
5968 ; (point-at-bol) (point))))
5969 ; (progn
5970 ; (beginning-of-line 1)
5971 ; (and (looking-at "[ \t]+") (replace-match ""))))
5972 (call-interactively (global-key-binding "\t")))
5974 (t (save-excursion
5975 (org-back-to-heading)
5976 (org-cycle))))))
5978 ;;;###autoload
5979 (defun org-global-cycle (&optional arg)
5980 "Cycle the global visibility. For details see `org-cycle'."
5981 (interactive "P")
5982 (let ((org-cycle-include-plain-lists
5983 (if (org-mode-p) org-cycle-include-plain-lists nil)))
5984 (if (integerp arg)
5985 (progn
5986 (show-all)
5987 (hide-sublevels arg)
5988 (setq org-cycle-global-status 'contents))
5989 (org-cycle '(4)))))
5991 (defun org-overview ()
5992 "Switch to overview mode, shoing only top-level headlines.
5993 Really, this shows all headlines with level equal or greater than the level
5994 of the first headline in the buffer. This is important, because if the
5995 first headline is not level one, then (hide-sublevels 1) gives confusing
5996 results."
5997 (interactive)
5998 (let ((level (save-excursion
5999 (goto-char (point-min))
6000 (if (re-search-forward (concat "^" outline-regexp) nil t)
6001 (progn
6002 (goto-char (match-beginning 0))
6003 (funcall outline-level))))))
6004 (and level (hide-sublevels level))))
6006 (defun org-content (&optional arg)
6007 "Show all headlines in the buffer, like a table of contents.
6008 With numerical argument N, show content up to level N."
6009 (interactive "P")
6010 (save-excursion
6011 ;; Visit all headings and show their offspring
6012 (and (integerp arg) (org-overview))
6013 (goto-char (point-max))
6014 (catch 'exit
6015 (while (and (progn (condition-case nil
6016 (outline-previous-visible-heading 1)
6017 (error (goto-char (point-min))))
6019 (looking-at outline-regexp))
6020 (if (integerp arg)
6021 (show-children (1- arg))
6022 (show-branches))
6023 (if (bobp) (throw 'exit nil))))))
6026 (defun org-optimize-window-after-visibility-change (state)
6027 "Adjust the window after a change in outline visibility.
6028 This function is the default value of the hook `org-cycle-hook'."
6029 (when (get-buffer-window (current-buffer))
6030 (cond
6031 ; ((eq state 'overview) (org-first-headline-recenter 1))
6032 ; ((eq state 'overview) (org-beginning-of-line))
6033 ((eq state 'content) nil)
6034 ((eq state 'all) nil)
6035 ((eq state 'folded) nil)
6036 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
6037 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
6039 (defun org-compact-display-after-subtree-move ()
6040 (let (beg end)
6041 (save-excursion
6042 (if (org-up-heading-safe)
6043 (progn
6044 (hide-subtree)
6045 (show-entry)
6046 (show-children)
6047 (org-cycle-show-empty-lines 'children)
6048 (org-cycle-hide-drawers 'children))
6049 (org-overview)))))
6051 (defun org-cycle-show-empty-lines (state)
6052 "Show empty lines above all visible headlines.
6053 The region to be covered depends on STATE when called through
6054 `org-cycle-hook'. Lisp program can use t for STATE to get the
6055 entire buffer covered. Note that an empty line is only shown if there
6056 are at least `org-cycle-separator-lines' empty lines before the headeline."
6057 (when (> org-cycle-separator-lines 0)
6058 (save-excursion
6059 (let* ((n org-cycle-separator-lines)
6060 (re (cond
6061 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
6062 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
6063 (t (let ((ns (number-to-string (- n 2))))
6064 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
6065 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
6066 beg end)
6067 (cond
6068 ((memq state '(overview contents t))
6069 (setq beg (point-min) end (point-max)))
6070 ((memq state '(children folded))
6071 (setq beg (point) end (progn (org-end-of-subtree t t)
6072 (beginning-of-line 2)
6073 (point)))))
6074 (when beg
6075 (goto-char beg)
6076 (while (re-search-forward re end t)
6077 (if (not (get-char-property (match-end 1) 'invisible))
6078 (outline-flag-region
6079 (match-beginning 1) (match-end 1) nil)))))))
6080 ;; Never hide empty lines at the end of the file.
6081 (save-excursion
6082 (goto-char (point-max))
6083 (outline-previous-heading)
6084 (outline-end-of-heading)
6085 (if (and (looking-at "[ \t\n]+")
6086 (= (match-end 0) (point-max)))
6087 (outline-flag-region (point) (match-end 0) nil))))
6089 (defun org-subtree-end-visible-p ()
6090 "Is the end of the current subtree visible?"
6091 (pos-visible-in-window-p
6092 (save-excursion (org-end-of-subtree t) (point))))
6094 (defun org-first-headline-recenter (&optional N)
6095 "Move cursor to the first headline and recenter the headline.
6096 Optional argument N means, put the headline into the Nth line of the window."
6097 (goto-char (point-min))
6098 (when (re-search-forward (concat "^\\(" outline-regexp "\\)") nil t)
6099 (beginning-of-line)
6100 (recenter (prefix-numeric-value N))))
6102 ;;; Org-goto
6104 (defvar org-goto-window-configuration nil)
6105 (defvar org-goto-marker nil)
6106 (defvar org-goto-map
6107 (let ((map (make-sparse-keymap)))
6108 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
6109 (while (setq cmd (pop cmds))
6110 (substitute-key-definition cmd cmd map global-map)))
6111 (suppress-keymap map)
6112 (org-defkey map "\C-m" 'org-goto-ret)
6113 (org-defkey map [(return)] 'org-goto-ret)
6114 (org-defkey map [(left)] 'org-goto-left)
6115 (org-defkey map [(right)] 'org-goto-right)
6116 (org-defkey map [(control ?g)] 'org-goto-quit)
6117 (org-defkey map "\C-i" 'org-cycle)
6118 (org-defkey map [(tab)] 'org-cycle)
6119 (org-defkey map [(down)] 'outline-next-visible-heading)
6120 (org-defkey map [(up)] 'outline-previous-visible-heading)
6121 (if org-goto-auto-isearch
6122 (if (fboundp 'define-key-after)
6123 (define-key-after map [t] 'org-goto-local-auto-isearch)
6124 nil)
6125 (org-defkey map "q" 'org-goto-quit)
6126 (org-defkey map "n" 'outline-next-visible-heading)
6127 (org-defkey map "p" 'outline-previous-visible-heading)
6128 (org-defkey map "f" 'outline-forward-same-level)
6129 (org-defkey map "b" 'outline-backward-same-level)
6130 (org-defkey map "u" 'outline-up-heading))
6131 (org-defkey map "/" 'org-occur)
6132 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
6133 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
6134 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
6135 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
6136 (org-defkey map "\C-c\C-u" 'outline-up-heading)
6137 map))
6139 (defconst org-goto-help
6140 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
6141 RET=jump to location [Q]uit and return to previous location
6142 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
6144 (defvar org-goto-start-pos) ; dynamically scoped parameter
6146 (defun org-goto (&optional alternative-interface)
6147 "Look up a different location in the current file, keeping current visibility.
6149 When you want look-up or go to a different location in a document, the
6150 fastest way is often to fold the entire buffer and then dive into the tree.
6151 This method has the disadvantage, that the previous location will be folded,
6152 which may not be what you want.
6154 This command works around this by showing a copy of the current buffer
6155 in an indirect buffer, in overview mode. You can dive into the tree in
6156 that copy, use org-occur and incremental search to find a location.
6157 When pressing RET or `Q', the command returns to the original buffer in
6158 which the visibility is still unchanged. After RET is will also jump to
6159 the location selected in the indirect buffer and expose the
6160 the headline hierarchy above."
6161 (interactive "P")
6162 (let* ((org-refile-targets '((nil . (:maxlevel . 10))))
6163 (org-refile-use-outline-path t)
6164 (interface
6165 (if (not alternative-interface)
6166 org-goto-interface
6167 (if (eq org-goto-interface 'outline)
6168 'outline-path-completion
6169 'outline)))
6170 (org-goto-start-pos (point))
6171 (selected-point
6172 (if (eq interface 'outline)
6173 (car (org-get-location (current-buffer) org-goto-help))
6174 (nth 3 (org-refile-get-location "Goto: ")))))
6175 (if selected-point
6176 (progn
6177 (org-mark-ring-push org-goto-start-pos)
6178 (goto-char selected-point)
6179 (if (or (org-invisible-p) (org-invisible-p2))
6180 (org-show-context 'org-goto)))
6181 (message "Quit"))))
6183 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
6184 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
6185 (defvar org-goto-local-auto-isearch-map) ; defined below
6187 (defun org-get-location (buf help)
6188 "Let the user select a location in the Org-mode buffer BUF.
6189 This function uses a recursive edit. It returns the selected position
6190 or nil."
6191 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
6192 (isearch-hide-immediately nil)
6193 (isearch-search-fun-function
6194 (lambda () 'org-goto-local-search-forward-headings))
6195 (org-goto-selected-point org-goto-exit-command))
6196 (save-excursion
6197 (save-window-excursion
6198 (delete-other-windows)
6199 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
6200 (switch-to-buffer
6201 (condition-case nil
6202 (make-indirect-buffer (current-buffer) "*org-goto*")
6203 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
6204 (with-output-to-temp-buffer "*Help*"
6205 (princ help))
6206 (shrink-window-if-larger-than-buffer (get-buffer-window "*Help*"))
6207 (setq buffer-read-only nil)
6208 (let ((org-startup-truncated t)
6209 (org-startup-folded nil)
6210 (org-startup-align-all-tables nil))
6211 (org-mode)
6212 (org-overview))
6213 (setq buffer-read-only t)
6214 (if (and (boundp 'org-goto-start-pos)
6215 (integer-or-marker-p org-goto-start-pos))
6216 (let ((org-show-hierarchy-above t)
6217 (org-show-siblings t)
6218 (org-show-following-heading t))
6219 (goto-char org-goto-start-pos)
6220 (and (org-invisible-p) (org-show-context)))
6221 (goto-char (point-min)))
6222 (org-beginning-of-line)
6223 (message "Select location and press RET")
6224 (use-local-map org-goto-map)
6225 (recursive-edit)
6227 (kill-buffer "*org-goto*")
6228 (cons org-goto-selected-point org-goto-exit-command)))
6230 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
6231 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
6232 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
6233 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
6235 (defun org-goto-local-search-forward-headings (string bound noerror)
6236 "Search and make sure that anu matches are in headlines."
6237 (catch 'return
6238 (while (search-forward string bound noerror)
6239 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
6240 (and (member :headline context)
6241 (not (member :tags context))))
6242 (throw 'return (point))))))
6244 (defun org-goto-local-auto-isearch ()
6245 "Start isearch."
6246 (interactive)
6247 (goto-char (point-min))
6248 (let ((keys (this-command-keys)))
6249 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
6250 (isearch-mode t)
6251 (isearch-process-search-char (string-to-char keys)))))
6253 (defun org-goto-ret (&optional arg)
6254 "Finish `org-goto' by going to the new location."
6255 (interactive "P")
6256 (setq org-goto-selected-point (point)
6257 org-goto-exit-command 'return)
6258 (throw 'exit nil))
6260 (defun org-goto-left ()
6261 "Finish `org-goto' by going to the new location."
6262 (interactive)
6263 (if (org-on-heading-p)
6264 (progn
6265 (beginning-of-line 1)
6266 (setq org-goto-selected-point (point)
6267 org-goto-exit-command 'left)
6268 (throw 'exit nil))
6269 (error "Not on a heading")))
6271 (defun org-goto-right ()
6272 "Finish `org-goto' by going to the new location."
6273 (interactive)
6274 (if (org-on-heading-p)
6275 (progn
6276 (setq org-goto-selected-point (point)
6277 org-goto-exit-command 'right)
6278 (throw 'exit nil))
6279 (error "Not on a heading")))
6281 (defun org-goto-quit ()
6282 "Finish `org-goto' without cursor motion."
6283 (interactive)
6284 (setq org-goto-selected-point nil)
6285 (setq org-goto-exit-command 'quit)
6286 (throw 'exit nil))
6288 ;;; Indirect buffer display of subtrees
6290 (defvar org-indirect-dedicated-frame nil
6291 "This is the frame being used for indirect tree display.")
6292 (defvar org-last-indirect-buffer nil)
6294 (defun org-tree-to-indirect-buffer (&optional arg)
6295 "Create indirect buffer and narrow it to current subtree.
6296 With numerical prefix ARG, go up to this level and then take that tree.
6297 If ARG is negative, go up that many levels.
6298 If `org-indirect-buffer-display' is not `new-frame', the command removes the
6299 indirect buffer previously made with this command, to avoid proliferation of
6300 indirect buffers. However, when you call the command with a `C-u' prefix, or
6301 when `org-indirect-buffer-display' is `new-frame', the last buffer
6302 is kept so that you can work with several indirect buffers at the same time.
6303 If `org-indirect-buffer-display' is `dedicated-frame', the C-u prefix also
6304 requests that a new frame be made for the new buffer, so that the dedicated
6305 frame is not changed."
6306 (interactive "P")
6307 (let ((cbuf (current-buffer))
6308 (cwin (selected-window))
6309 (pos (point))
6310 beg end level heading ibuf)
6311 (save-excursion
6312 (org-back-to-heading t)
6313 (when (numberp arg)
6314 (setq level (org-outline-level))
6315 (if (< arg 0) (setq arg (+ level arg)))
6316 (while (> (setq level (org-outline-level)) arg)
6317 (outline-up-heading 1 t)))
6318 (setq beg (point)
6319 heading (org-get-heading))
6320 (org-end-of-subtree t) (setq end (point)))
6321 (if (and (buffer-live-p org-last-indirect-buffer)
6322 (not (eq org-indirect-buffer-display 'new-frame))
6323 (not arg))
6324 (kill-buffer org-last-indirect-buffer))
6325 (setq ibuf (org-get-indirect-buffer cbuf)
6326 org-last-indirect-buffer ibuf)
6327 (cond
6328 ((or (eq org-indirect-buffer-display 'new-frame)
6329 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
6330 (select-frame (make-frame))
6331 (delete-other-windows)
6332 (switch-to-buffer ibuf)
6333 (org-set-frame-title heading))
6334 ((eq org-indirect-buffer-display 'dedicated-frame)
6335 (raise-frame
6336 (select-frame (or (and org-indirect-dedicated-frame
6337 (frame-live-p org-indirect-dedicated-frame)
6338 org-indirect-dedicated-frame)
6339 (setq org-indirect-dedicated-frame (make-frame)))))
6340 (delete-other-windows)
6341 (switch-to-buffer ibuf)
6342 (org-set-frame-title (concat "Indirect: " heading)))
6343 ((eq org-indirect-buffer-display 'current-window)
6344 (switch-to-buffer ibuf))
6345 ((eq org-indirect-buffer-display 'other-window)
6346 (pop-to-buffer ibuf))
6347 (t (error "Invalid value.")))
6348 (if (featurep 'xemacs)
6349 (save-excursion (org-mode) (turn-on-font-lock)))
6350 (narrow-to-region beg end)
6351 (show-all)
6352 (goto-char pos)
6353 (and (window-live-p cwin) (select-window cwin))))
6355 (defun org-get-indirect-buffer (&optional buffer)
6356 (setq buffer (or buffer (current-buffer)))
6357 (let ((n 1) (base (buffer-name buffer)) bname)
6358 (while (buffer-live-p
6359 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
6360 (setq n (1+ n)))
6361 (condition-case nil
6362 (make-indirect-buffer buffer bname 'clone)
6363 (error (make-indirect-buffer buffer bname)))))
6365 (defun org-set-frame-title (title)
6366 "Set the title of the current frame to the string TITLE."
6367 ;; FIXME: how to name a single frame in XEmacs???
6368 (unless (featurep 'xemacs)
6369 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
6371 ;;;; Structure editing
6373 ;;; Inserting headlines
6375 (defun org-insert-heading (&optional force-heading)
6376 "Insert a new heading or item with same depth at point.
6377 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
6378 If point is at the beginning of a headline, insert a sibling before the
6379 current headline. If point is not at the beginning, do not split the line,
6380 but create the new hedline after the current line."
6381 (interactive "P")
6382 (if (= (buffer-size) 0)
6383 (insert "\n* ")
6384 (when (or force-heading (not (org-insert-item)))
6385 (let* ((head (save-excursion
6386 (condition-case nil
6387 (progn
6388 (org-back-to-heading)
6389 (match-string 0))
6390 (error "*"))))
6391 (blank (cdr (assq 'heading org-blank-before-new-entry)))
6392 pos)
6393 (cond
6394 ((and (org-on-heading-p) (bolp)
6395 (or (bobp)
6396 (save-excursion (backward-char 1) (not (org-invisible-p)))))
6397 ;; insert before the current line
6398 (open-line (if blank 2 1)))
6399 ((and (bolp)
6400 (or (bobp)
6401 (save-excursion
6402 (backward-char 1) (not (org-invisible-p)))))
6403 ;; insert right here
6404 nil)
6406 ; ;; in the middle of the line
6407 ; (org-show-entry)
6408 ; (if (org-get-alist-option org-M-RET-may-split-line 'headline)
6409 ; (if (and
6410 ; (org-on-heading-p)
6411 ; (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \r\n]"))
6412 ; ;; protect the tags
6413 ;; (let ((tags (match-string 2)) pos)
6414 ; (delete-region (match-beginning 1) (match-end 1))
6415 ; (setq pos (point-at-bol))
6416 ; (newline (if blank 2 1))
6417 ; (save-excursion
6418 ; (goto-char pos)
6419 ; (end-of-line 1)
6420 ; (insert " " tags)
6421 ; (org-set-tags nil 'align)))
6422 ; (newline (if blank 2 1)))
6423 ; (newline (if blank 2 1))))
6426 ;; in the middle of the line
6427 (org-show-entry)
6428 (let ((split
6429 (org-get-alist-option org-M-RET-may-split-line 'headline))
6430 tags pos)
6431 (if (org-on-heading-p)
6432 (progn
6433 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
6434 (setq tags (and (match-end 2) (match-string 2)))
6435 (and (match-end 1)
6436 (delete-region (match-beginning 1) (match-end 1)))
6437 (setq pos (point-at-bol))
6438 (or split (end-of-line 1))
6439 (delete-horizontal-space)
6440 (newline (if blank 2 1))
6441 (when tags
6442 (save-excursion
6443 (goto-char pos)
6444 (end-of-line 1)
6445 (insert " " tags)
6446 (org-set-tags nil 'align))))
6447 (or split (end-of-line 1))
6448 (newline (if blank 2 1))))))
6449 (insert head) (just-one-space)
6450 (setq pos (point))
6451 (end-of-line 1)
6452 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
6453 (run-hooks 'org-insert-heading-hook)))))
6455 (defun org-insert-heading-after-current ()
6456 "Insert a new heading with same level as current, after current subtree."
6457 (interactive)
6458 (org-back-to-heading)
6459 (org-insert-heading)
6460 (org-move-subtree-down)
6461 (end-of-line 1))
6463 (defun org-insert-todo-heading (arg)
6464 "Insert a new heading with the same level and TODO state as current heading.
6465 If the heading has no TODO state, or if the state is DONE, use the first
6466 state (TODO by default). Also with prefix arg, force first state."
6467 (interactive "P")
6468 (when (not (org-insert-item 'checkbox))
6469 (org-insert-heading)
6470 (save-excursion
6471 (org-back-to-heading)
6472 (outline-previous-heading)
6473 (looking-at org-todo-line-regexp))
6474 (if (or arg
6475 (not (match-beginning 2))
6476 (member (match-string 2) org-done-keywords))
6477 (insert (car org-todo-keywords-1) " ")
6478 (insert (match-string 2) " "))))
6480 (defun org-insert-subheading (arg)
6481 "Insert a new subheading and demote it.
6482 Works for outline headings and for plain lists alike."
6483 (interactive "P")
6484 (org-insert-heading arg)
6485 (cond
6486 ((org-on-heading-p) (org-do-demote))
6487 ((org-at-item-p) (org-indent-item 1))))
6489 (defun org-insert-todo-subheading (arg)
6490 "Insert a new subheading with TODO keyword or checkbox and demote it.
6491 Works for outline headings and for plain lists alike."
6492 (interactive "P")
6493 (org-insert-todo-heading arg)
6494 (cond
6495 ((org-on-heading-p) (org-do-demote))
6496 ((org-at-item-p) (org-indent-item 1))))
6498 ;;; Promotion and Demotion
6500 (defun org-promote-subtree ()
6501 "Promote the entire subtree.
6502 See also `org-promote'."
6503 (interactive)
6504 (save-excursion
6505 (org-map-tree 'org-promote))
6506 (org-fix-position-after-promote))
6508 (defun org-demote-subtree ()
6509 "Demote the entire subtree. See `org-demote'.
6510 See also `org-promote'."
6511 (interactive)
6512 (save-excursion
6513 (org-map-tree 'org-demote))
6514 (org-fix-position-after-promote))
6517 (defun org-do-promote ()
6518 "Promote the current heading higher up the tree.
6519 If the region is active in `transient-mark-mode', promote all headings
6520 in the region."
6521 (interactive)
6522 (save-excursion
6523 (if (org-region-active-p)
6524 (org-map-region 'org-promote (region-beginning) (region-end))
6525 (org-promote)))
6526 (org-fix-position-after-promote))
6528 (defun org-do-demote ()
6529 "Demote the current heading lower down the tree.
6530 If the region is active in `transient-mark-mode', demote all headings
6531 in the region."
6532 (interactive)
6533 (save-excursion
6534 (if (org-region-active-p)
6535 (org-map-region 'org-demote (region-beginning) (region-end))
6536 (org-demote)))
6537 (org-fix-position-after-promote))
6539 (defun org-fix-position-after-promote ()
6540 "Make sure that after pro/demotion cursor position is right."
6541 (let ((pos (point)))
6542 (when (save-excursion
6543 (beginning-of-line 1)
6544 (looking-at org-todo-line-regexp)
6545 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
6546 (cond ((eobp) (insert " "))
6547 ((eolp) (insert " "))
6548 ((equal (char-after) ?\ ) (forward-char 1))))))
6550 (defun org-reduced-level (l)
6551 (if org-odd-levels-only (1+ (floor (/ l 2))) l))
6553 (defun org-get-valid-level (level &optional change)
6554 "Rectify a level change under the influence of `org-odd-levels-only'
6555 LEVEL is a current level, CHANGE is by how much the level should be
6556 modified. Even if CHANGE is nil, LEVEL may be returned modified because
6557 even level numbers will become the next higher odd number."
6558 (if org-odd-levels-only
6559 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
6560 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
6561 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
6562 (max 1 (+ level change))))
6564 (if (featurep 'xemacs)
6565 (define-obsolete-function-alias 'org-get-legal-level
6566 'org-get-valid-level)
6567 (define-obsolete-function-alias 'org-get-legal-level
6568 'org-get-valid-level "23.1"))
6570 (defun org-promote ()
6571 "Promote the current heading higher up the tree.
6572 If the region is active in `transient-mark-mode', promote all headings
6573 in the region."
6574 (org-back-to-heading t)
6575 (let* ((level (save-match-data (funcall outline-level)))
6576 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
6577 (diff (abs (- level (length up-head) -1))))
6578 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
6579 (replace-match up-head nil t)
6580 ;; Fixup tag positioning
6581 (and org-auto-align-tags (org-set-tags nil t))
6582 (if org-adapt-indentation (org-fixup-indentation (- diff)))))
6584 (defun org-demote ()
6585 "Demote the current heading lower down the tree.
6586 If the region is active in `transient-mark-mode', demote all headings
6587 in the region."
6588 (org-back-to-heading t)
6589 (let* ((level (save-match-data (funcall outline-level)))
6590 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
6591 (diff (abs (- level (length down-head) -1))))
6592 (replace-match down-head nil t)
6593 ;; Fixup tag positioning
6594 (and org-auto-align-tags (org-set-tags nil t))
6595 (if org-adapt-indentation (org-fixup-indentation diff))))
6597 (defun org-map-tree (fun)
6598 "Call FUN for every heading underneath the current one."
6599 (org-back-to-heading)
6600 (let ((level (funcall outline-level)))
6601 (save-excursion
6602 (funcall fun)
6603 (while (and (progn
6604 (outline-next-heading)
6605 (> (funcall outline-level) level))
6606 (not (eobp)))
6607 (funcall fun)))))
6609 (defun org-map-region (fun beg end)
6610 "Call FUN for every heading between BEG and END."
6611 (let ((org-ignore-region t))
6612 (save-excursion
6613 (setq end (copy-marker end))
6614 (goto-char beg)
6615 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
6616 (< (point) end))
6617 (funcall fun))
6618 (while (and (progn
6619 (outline-next-heading)
6620 (< (point) end))
6621 (not (eobp)))
6622 (funcall fun)))))
6624 (defun org-fixup-indentation (diff)
6625 "Change the indentation in the current entry by DIFF
6626 However, if any line in the current entry has no indentation, or if it
6627 would end up with no indentation after the change, nothing at all is done."
6628 (save-excursion
6629 (let ((end (save-excursion (outline-next-heading)
6630 (point-marker)))
6631 (prohibit (if (> diff 0)
6632 "^\\S-"
6633 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
6634 col)
6635 (unless (save-excursion (end-of-line 1)
6636 (re-search-forward prohibit end t))
6637 (while (and (< (point) end)
6638 (re-search-forward "^[ \t]+" end t))
6639 (goto-char (match-end 0))
6640 (setq col (current-column))
6641 (if (< diff 0) (replace-match ""))
6642 (indent-to (+ diff col))))
6643 (move-marker end nil))))
6645 (defun org-convert-to-odd-levels ()
6646 "Convert an org-mode file with all levels allowed to one with odd levels.
6647 This will leave level 1 alone, convert level 2 to level 3, level 3 to
6648 level 5 etc."
6649 (interactive)
6650 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
6651 (let ((org-odd-levels-only nil) n)
6652 (save-excursion
6653 (goto-char (point-min))
6654 (while (re-search-forward "^\\*\\*+ " nil t)
6655 (setq n (- (length (match-string 0)) 2))
6656 (while (>= (setq n (1- n)) 0)
6657 (org-demote))
6658 (end-of-line 1))))))
6661 (defun org-convert-to-oddeven-levels ()
6662 "Convert an org-mode file with only odd levels to one with odd and even levels.
6663 This promotes level 3 to level 2, level 5 to level 3 etc. If the file contains a
6664 section with an even level, conversion would destroy the structure of the file. An error
6665 is signaled in this case."
6666 (interactive)
6667 (goto-char (point-min))
6668 ;; First check if there are no even levels
6669 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
6670 (org-show-context t)
6671 (error "Not all levels are odd in this file. Conversion not possible."))
6672 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
6673 (let ((org-odd-levels-only nil) n)
6674 (save-excursion
6675 (goto-char (point-min))
6676 (while (re-search-forward "^\\*\\*+ " nil t)
6677 (setq n (/ (1- (length (match-string 0))) 2))
6678 (while (>= (setq n (1- n)) 0)
6679 (org-promote))
6680 (end-of-line 1))))))
6682 (defun org-tr-level (n)
6683 "Make N odd if required."
6684 (if org-odd-levels-only (1+ (/ n 2)) n))
6686 ;;; Vertical tree motion, cutting and pasting of subtrees
6688 (defun org-move-subtree-up (&optional arg)
6689 "Move the current subtree up past ARG headlines of the same level."
6690 (interactive "p")
6691 (org-move-subtree-down (- (prefix-numeric-value arg))))
6693 (defun org-move-subtree-down (&optional arg)
6694 "Move the current subtree down past ARG headlines of the same level."
6695 (interactive "p")
6696 (setq arg (prefix-numeric-value arg))
6697 (let ((movfunc (if (> arg 0) 'outline-get-next-sibling
6698 'outline-get-last-sibling))
6699 (ins-point (make-marker))
6700 (cnt (abs arg))
6701 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
6702 ;; Select the tree
6703 (org-back-to-heading)
6704 (setq beg0 (point))
6705 (save-excursion
6706 (setq ne-beg (org-back-over-empty-lines))
6707 (setq beg (point)))
6708 (save-match-data
6709 (save-excursion (outline-end-of-heading)
6710 (setq folded (org-invisible-p)))
6711 (outline-end-of-subtree))
6712 (outline-next-heading)
6713 (setq ne-end (org-back-over-empty-lines))
6714 (setq end (point))
6715 (goto-char beg0)
6716 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
6717 ;; include less whitespace
6718 (save-excursion
6719 (goto-char beg)
6720 (forward-line (- ne-beg ne-end))
6721 (setq beg (point))))
6722 ;; Find insertion point, with error handling
6723 (while (> cnt 0)
6724 (or (and (funcall movfunc) (looking-at outline-regexp))
6725 (progn (goto-char beg0)
6726 (error "Cannot move past superior level or buffer limit")))
6727 (setq cnt (1- cnt)))
6728 (if (> arg 0)
6729 ;; Moving forward - still need to move over subtree
6730 (progn (org-end-of-subtree t t)
6731 (save-excursion
6732 (org-back-over-empty-lines)
6733 (or (bolp) (newline)))))
6734 (setq ne-ins (org-back-over-empty-lines))
6735 (move-marker ins-point (point))
6736 (setq txt (buffer-substring beg end))
6737 (delete-region beg end)
6738 (outline-flag-region (1- beg) beg nil)
6739 (outline-flag-region (1- (point)) (point) nil)
6740 (insert txt)
6741 (or (bolp) (insert "\n"))
6742 (setq ins-end (point))
6743 (goto-char ins-point)
6744 (org-skip-whitespace)
6745 (when (and (< arg 0)
6746 (org-first-sibling-p)
6747 (> ne-ins ne-beg))
6748 ;; Move whitespace back to beginning
6749 (save-excursion
6750 (goto-char ins-end)
6751 (let ((kill-whole-line t))
6752 (kill-line (- ne-ins ne-beg)) (point)))
6753 (insert (make-string (- ne-ins ne-beg) ?\n)))
6754 (move-marker ins-point nil)
6755 (org-compact-display-after-subtree-move)
6756 (unless folded
6757 (org-show-entry)
6758 (show-children)
6759 (org-cycle-hide-drawers 'children))))
6761 (defvar org-subtree-clip ""
6762 "Clipboard for cut and paste of subtrees.
6763 This is actually only a copy of the kill, because we use the normal kill
6764 ring. We need it to check if the kill was created by `org-copy-subtree'.")
6766 (defvar org-subtree-clip-folded nil
6767 "Was the last copied subtree folded?
6768 This is used to fold the tree back after pasting.")
6770 (defun org-cut-subtree (&optional n)
6771 "Cut the current subtree into the clipboard.
6772 With prefix arg N, cut this many sequential subtrees.
6773 This is a short-hand for marking the subtree and then cutting it."
6774 (interactive "p")
6775 (org-copy-subtree n 'cut))
6777 (defun org-copy-subtree (&optional n cut)
6778 "Cut the current subtree into the clipboard.
6779 With prefix arg N, cut this many sequential subtrees.
6780 This is a short-hand for marking the subtree and then copying it.
6781 If CUT is non-nil, actually cut the subtree."
6782 (interactive "p")
6783 (let (beg end folded (beg0 (point)))
6784 (if (interactive-p)
6785 (org-back-to-heading nil) ; take what looks like a subtree
6786 (org-back-to-heading t)) ; take what is really there
6787 (org-back-over-empty-lines)
6788 (setq beg (point))
6789 (skip-chars-forward " \t\r\n")
6790 (save-match-data
6791 (save-excursion (outline-end-of-heading)
6792 (setq folded (org-invisible-p)))
6793 (condition-case nil
6794 (outline-forward-same-level (1- n))
6795 (error nil))
6796 (org-end-of-subtree t t))
6797 (org-back-over-empty-lines)
6798 (setq end (point))
6799 (goto-char beg0)
6800 (when (> end beg)
6801 (setq org-subtree-clip-folded folded)
6802 (if cut (kill-region beg end) (copy-region-as-kill beg end))
6803 (setq org-subtree-clip (current-kill 0))
6804 (message "%s: Subtree(s) with %d characters"
6805 (if cut "Cut" "Copied")
6806 (length org-subtree-clip)))))
6808 (defun org-paste-subtree (&optional level tree)
6809 "Paste the clipboard as a subtree, with modification of headline level.
6810 The entire subtree is promoted or demoted in order to match a new headline
6811 level. By default, the new level is derived from the visible headings
6812 before and after the insertion point, and taken to be the inferior headline
6813 level of the two. So if the previous visible heading is level 3 and the
6814 next is level 4 (or vice versa), level 4 will be used for insertion.
6815 This makes sure that the subtree remains an independent subtree and does
6816 not swallow low level entries.
6818 You can also force a different level, either by using a numeric prefix
6819 argument, or by inserting the heading marker by hand. For example, if the
6820 cursor is after \"*****\", then the tree will be shifted to level 5.
6822 If you want to insert the tree as is, just use \\[yank].
6824 If optional TREE is given, use this text instead of the kill ring."
6825 (interactive "P")
6826 (unless (org-kill-is-subtree-p tree)
6827 (error "%s"
6828 (substitute-command-keys
6829 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
6830 (let* ((txt (or tree (and kill-ring (current-kill 0))))
6831 (^re (concat "^\\(" outline-regexp "\\)"))
6832 (re (concat "\\(" outline-regexp "\\)"))
6833 (^re_ (concat "\\(\\*+\\)[ \t]*"))
6835 (old-level (if (string-match ^re txt)
6836 (- (match-end 0) (match-beginning 0) 1)
6837 -1))
6838 (force-level (cond (level (prefix-numeric-value level))
6839 ((string-match
6840 ^re_ (buffer-substring (point-at-bol) (point)))
6841 (- (match-end 1) (match-beginning 1)))
6842 (t nil)))
6843 (previous-level (save-excursion
6844 (condition-case nil
6845 (progn
6846 (outline-previous-visible-heading 1)
6847 (if (looking-at re)
6848 (- (match-end 0) (match-beginning 0) 1)
6850 (error 1))))
6851 (next-level (save-excursion
6852 (condition-case nil
6853 (progn
6854 (or (looking-at outline-regexp)
6855 (outline-next-visible-heading 1))
6856 (if (looking-at re)
6857 (- (match-end 0) (match-beginning 0) 1)
6859 (error 1))))
6860 (new-level (or force-level (max previous-level next-level)))
6861 (shift (if (or (= old-level -1)
6862 (= new-level -1)
6863 (= old-level new-level))
6865 (- new-level old-level)))
6866 (delta (if (> shift 0) -1 1))
6867 (func (if (> shift 0) 'org-demote 'org-promote))
6868 (org-odd-levels-only nil)
6869 beg end)
6870 ;; Remove the forced level indicator
6871 (if force-level
6872 (delete-region (point-at-bol) (point)))
6873 ;; Paste
6874 (beginning-of-line 1)
6875 (org-back-over-empty-lines) ;; FIXME: correct fix????
6876 (setq beg (point))
6877 (insert-before-markers txt) ;; FIXME: correct fix????
6878 (unless (string-match "\n\\'" txt) (insert "\n"))
6879 (setq end (point))
6880 (goto-char beg)
6881 (skip-chars-forward " \t\n\r")
6882 (setq beg (point))
6883 ;; Shift if necessary
6884 (unless (= shift 0)
6885 (save-restriction
6886 (narrow-to-region beg end)
6887 (while (not (= shift 0))
6888 (org-map-region func (point-min) (point-max))
6889 (setq shift (+ delta shift)))
6890 (goto-char (point-min))))
6891 (when (interactive-p)
6892 (message "Clipboard pasted as level %d subtree" new-level))
6893 (if (and kill-ring
6894 (eq org-subtree-clip (current-kill 0))
6895 org-subtree-clip-folded)
6896 ;; The tree was folded before it was killed/copied
6897 (hide-subtree))))
6899 (defun org-kill-is-subtree-p (&optional txt)
6900 "Check if the current kill is an outline subtree, or a set of trees.
6901 Returns nil if kill does not start with a headline, or if the first
6902 headline level is not the largest headline level in the tree.
6903 So this will actually accept several entries of equal levels as well,
6904 which is OK for `org-paste-subtree'.
6905 If optional TXT is given, check this string instead of the current kill."
6906 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
6907 (start-level (and kill
6908 (string-match (concat "\\`\\([ \t\n\r]*?\n\\)?\\("
6909 org-outline-regexp "\\)")
6910 kill)
6911 (- (match-end 2) (match-beginning 2) 1)))
6912 (re (concat "^" org-outline-regexp))
6913 (start (1+ (match-beginning 2))))
6914 (if (not start-level)
6915 (progn
6916 nil) ;; does not even start with a heading
6917 (catch 'exit
6918 (while (setq start (string-match re kill (1+ start)))
6919 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
6920 (throw 'exit nil)))
6921 t))))
6923 (defun org-narrow-to-subtree ()
6924 "Narrow buffer to the current subtree."
6925 (interactive)
6926 (save-excursion
6927 (save-match-data
6928 (narrow-to-region
6929 (progn (org-back-to-heading) (point))
6930 (progn (org-end-of-subtree t t) (point))))))
6933 ;;; Outline Sorting
6935 (defun org-sort (with-case)
6936 "Call `org-sort-entries-or-items' or `org-table-sort-lines'.
6937 Optional argument WITH-CASE means sort case-sensitively."
6938 (interactive "P")
6939 (if (org-at-table-p)
6940 (org-call-with-arg 'org-table-sort-lines with-case)
6941 (org-call-with-arg 'org-sort-entries-or-items with-case)))
6943 (defvar org-priority-regexp) ; defined later in the file
6945 (defun org-sort-entries-or-items (&optional with-case sorting-type getkey-func property)
6946 "Sort entries on a certain level of an outline tree.
6947 If there is an active region, the entries in the region are sorted.
6948 Else, if the cursor is before the first entry, sort the top-level items.
6949 Else, the children of the entry at point are sorted.
6951 Sorting can be alphabetically, numerically, and by date/time as given by
6952 the first time stamp in the entry. The command prompts for the sorting
6953 type unless it has been given to the function through the SORTING-TYPE
6954 argument, which needs to a character, any of (?n ?N ?a ?A ?t ?T ?p ?P ?f ?F).
6955 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
6956 called with point at the beginning of the record. It must return either
6957 a string or a number that should serve as the sorting key for that record.
6959 Comparing entries ignores case by default. However, with an optional argument
6960 WITH-CASE, the sorting considers case as well."
6961 (interactive "P")
6962 (let ((case-func (if with-case 'identity 'downcase))
6963 start beg end stars re re2
6964 txt what tmp plain-list-p)
6965 ;; Find beginning and end of region to sort
6966 (cond
6967 ((org-region-active-p)
6968 ;; we will sort the region
6969 (setq end (region-end)
6970 what "region")
6971 (goto-char (region-beginning))
6972 (if (not (org-on-heading-p)) (outline-next-heading))
6973 (setq start (point)))
6974 ((org-at-item-p)
6975 ;; we will sort this plain list
6976 (org-beginning-of-item-list) (setq start (point))
6977 (org-end-of-item-list) (setq end (point))
6978 (goto-char start)
6979 (setq plain-list-p t
6980 what "plain list"))
6981 ((or (org-on-heading-p)
6982 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
6983 ;; we will sort the children of the current headline
6984 (org-back-to-heading)
6985 (setq start (point)
6986 end (progn (org-end-of-subtree t t)
6987 (org-back-over-empty-lines)
6988 (point))
6989 what "children")
6990 (goto-char start)
6991 (show-subtree)
6992 (outline-next-heading))
6994 ;; we will sort the top-level entries in this file
6995 (goto-char (point-min))
6996 (or (org-on-heading-p) (outline-next-heading))
6997 (setq start (point) end (point-max) what "top-level")
6998 (goto-char start)
6999 (show-all)))
7001 (setq beg (point))
7002 (if (>= beg end) (error "Nothing to sort"))
7004 (unless plain-list-p
7005 (looking-at "\\(\\*+\\)")
7006 (setq stars (match-string 1)
7007 re (concat "^" (regexp-quote stars) " +")
7008 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[^*]")
7009 txt (buffer-substring beg end))
7010 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
7011 (if (and (not (equal stars "*")) (string-match re2 txt))
7012 (error "Region to sort contains a level above the first entry")))
7014 (unless sorting-type
7015 (message
7016 (if plain-list-p
7017 "Sort %s: [a]lpha [n]umeric [t]ime [f]unc A/N/T/F means reversed:"
7018 "Sort %s: [a]lpha [n]umeric [t]ime [p]riority p[r]operty [f]unc A/N/T/P/F means reversed:")
7019 what)
7020 (setq sorting-type (read-char-exclusive))
7022 (and (= (downcase sorting-type) ?f)
7023 (setq getkey-func
7024 (completing-read "Sort using function: "
7025 obarray 'fboundp t nil nil))
7026 (setq getkey-func (intern getkey-func)))
7028 (and (= (downcase sorting-type) ?r)
7029 (setq property
7030 (completing-read "Property: "
7031 (mapcar 'list (org-buffer-property-keys t))
7032 nil t))))
7034 (message "Sorting entries...")
7036 (save-restriction
7037 (narrow-to-region start end)
7039 (let ((dcst (downcase sorting-type))
7040 (now (current-time)))
7041 (sort-subr
7042 (/= dcst sorting-type)
7043 ;; This function moves to the beginning character of the "record" to
7044 ;; be sorted.
7045 (if plain-list-p
7046 (lambda nil
7047 (if (org-at-item-p) t (goto-char (point-max))))
7048 (lambda nil
7049 (if (re-search-forward re nil t)
7050 (goto-char (match-beginning 0))
7051 (goto-char (point-max)))))
7052 ;; This function moves to the last character of the "record" being
7053 ;; sorted.
7054 (if plain-list-p
7055 'org-end-of-item
7056 (lambda nil
7057 (save-match-data
7058 (condition-case nil
7059 (outline-forward-same-level 1)
7060 (error
7061 (goto-char (point-max)))))))
7063 ;; This function returns the value that gets sorted against.
7064 (if plain-list-p
7065 (lambda nil
7066 (when (looking-at "[ \t]*[-+*0-9.)]+[ \t]+")
7067 (cond
7068 ((= dcst ?n)
7069 (string-to-number (buffer-substring (match-end 0)
7070 (point-at-eol))))
7071 ((= dcst ?a)
7072 (buffer-substring (match-end 0) (point-at-eol)))
7073 ((= dcst ?t)
7074 (if (re-search-forward org-ts-regexp
7075 (point-at-eol) t)
7076 (org-time-string-to-time (match-string 0))
7077 now))
7078 ((= dcst ?f)
7079 (if getkey-func
7080 (progn
7081 (setq tmp (funcall getkey-func))
7082 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
7083 tmp)
7084 (error "Invalid key function `%s'" getkey-func)))
7085 (t (error "Invalid sorting type `%c'" sorting-type)))))
7086 (lambda nil
7087 (cond
7088 ((= dcst ?n)
7089 (if (looking-at outline-regexp)
7090 (string-to-number (buffer-substring (match-end 0)
7091 (point-at-eol)))
7092 nil))
7093 ((= dcst ?a)
7094 (funcall case-func (buffer-substring (point-at-bol)
7095 (point-at-eol))))
7096 ((= dcst ?t)
7097 (if (re-search-forward org-ts-regexp
7098 (save-excursion
7099 (forward-line 2)
7100 (point)) t)
7101 (org-time-string-to-time (match-string 0))
7102 now))
7103 ((= dcst ?p)
7104 (if (re-search-forward org-priority-regexp (point-at-eol) t)
7105 (string-to-char (match-string 2))
7106 org-default-priority))
7107 ((= dcst ?r)
7108 (or (org-entry-get nil property) ""))
7109 ((= dcst ?f)
7110 (if getkey-func
7111 (progn
7112 (setq tmp (funcall getkey-func))
7113 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
7114 tmp)
7115 (error "Invalid key function `%s'" getkey-func)))
7116 (t (error "Invalid sorting type `%c'" sorting-type)))))
7118 (cond
7119 ((= dcst ?a) 'string<)
7120 ((= dcst ?t) 'time-less-p)
7121 (t nil)))))
7122 (message "Sorting entries...done")))
7124 (defun org-do-sort (table what &optional with-case sorting-type)
7125 "Sort TABLE of WHAT according to SORTING-TYPE.
7126 The user will be prompted for the SORTING-TYPE if the call to this
7127 function does not specify it. WHAT is only for the prompt, to indicate
7128 what is being sorted. The sorting key will be extracted from
7129 the car of the elements of the table.
7130 If WITH-CASE is non-nil, the sorting will be case-sensitive."
7131 (unless sorting-type
7132 (message
7133 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
7134 what)
7135 (setq sorting-type (read-char-exclusive)))
7136 (let ((dcst (downcase sorting-type))
7137 extractfun comparefun)
7138 ;; Define the appropriate functions
7139 (cond
7140 ((= dcst ?n)
7141 (setq extractfun 'string-to-number
7142 comparefun (if (= dcst sorting-type) '< '>)))
7143 ((= dcst ?a)
7144 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
7145 (lambda(x) (downcase (org-sort-remove-invisible x))))
7146 comparefun (if (= dcst sorting-type)
7147 'string<
7148 (lambda (a b) (and (not (string< a b))
7149 (not (string= a b)))))))
7150 ((= dcst ?t)
7151 (setq extractfun
7152 (lambda (x)
7153 (if (string-match org-ts-regexp x)
7154 (time-to-seconds
7155 (org-time-string-to-time (match-string 0 x)))
7157 comparefun (if (= dcst sorting-type) '< '>)))
7158 (t (error "Invalid sorting type `%c'" sorting-type)))
7160 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
7161 table)
7162 (lambda (a b) (funcall comparefun (car a) (car b))))))
7164 ;;;; Plain list items, including checkboxes
7166 ;;; Plain list items
7168 (defun org-at-item-p ()
7169 "Is point in a line starting a hand-formatted item?"
7170 (let ((llt org-plain-list-ordered-item-terminator))
7171 (save-excursion
7172 (goto-char (point-at-bol))
7173 (looking-at
7174 (cond
7175 ((eq llt t) "\\([ \t]*\\([-+]\\|\\([0-9]+[.)]\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
7176 ((= llt ?.) "\\([ \t]*\\([-+]\\|\\([0-9]+\\.\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
7177 ((= llt ?\)) "\\([ \t]*\\([-+]\\|\\([0-9]+))\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
7178 (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))))))
7180 (defun org-in-item-p ()
7181 "It the cursor inside a plain list item.
7182 Does not have to be the first line."
7183 (save-excursion
7184 (condition-case nil
7185 (progn
7186 (org-beginning-of-item)
7187 (org-at-item-p)
7189 (error nil))))
7191 (defun org-insert-item (&optional checkbox)
7192 "Insert a new item at the current level.
7193 Return t when things worked, nil when we are not in an item."
7194 (when (save-excursion
7195 (condition-case nil
7196 (progn
7197 (org-beginning-of-item)
7198 (org-at-item-p)
7199 (if (org-invisible-p) (error "Invisible item"))
7201 (error nil)))
7202 (let* ((bul (match-string 0))
7203 (eow (save-excursion (beginning-of-line 1) (looking-at "[ \t]*")
7204 (match-end 0)))
7205 (blank (cdr (assq 'plain-list-item org-blank-before-new-entry)))
7206 pos)
7207 (cond
7208 ((and (org-at-item-p) (<= (point) eow))
7209 ;; before the bullet
7210 (beginning-of-line 1)
7211 (open-line (if blank 2 1)))
7212 ((<= (point) eow)
7213 (beginning-of-line 1))
7215 (unless (org-get-alist-option org-M-RET-may-split-line 'item)
7216 (end-of-line 1)
7217 (delete-horizontal-space))
7218 (newline (if blank 2 1))))
7219 (insert bul (if checkbox "[ ]" ""))
7220 (just-one-space)
7221 (setq pos (point))
7222 (end-of-line 1)
7223 (unless (= (point) pos) (just-one-space) (backward-delete-char 1)))
7224 (org-maybe-renumber-ordered-list)
7225 (and checkbox (org-update-checkbox-count-maybe))
7228 ;;; Checkboxes
7230 (defun org-at-item-checkbox-p ()
7231 "Is point at a line starting a plain-list item with a checklet?"
7232 (and (org-at-item-p)
7233 (save-excursion
7234 (goto-char (match-end 0))
7235 (skip-chars-forward " \t")
7236 (looking-at "\\[[- X]\\]"))))
7238 (defun org-toggle-checkbox (&optional arg)
7239 "Toggle the checkbox in the current line."
7240 (interactive "P")
7241 (catch 'exit
7242 (let (beg end status (firstnew 'unknown))
7243 (cond
7244 ((org-region-active-p)
7245 (setq beg (region-beginning) end (region-end)))
7246 ((org-on-heading-p)
7247 (setq beg (point) end (save-excursion (outline-next-heading) (point))))
7248 ((org-at-item-checkbox-p)
7249 (let ((pos (point)))
7250 (replace-match
7251 (cond (arg "[-]")
7252 ((member (match-string 0) '("[ ]" "[-]")) "[X]")
7253 (t "[ ]"))
7254 t t)
7255 (goto-char pos))
7256 (throw 'exit t))
7257 (t (error "Not at a checkbox or heading, and no active region")))
7258 (save-excursion
7259 (goto-char beg)
7260 (while (< (point) end)
7261 (when (org-at-item-checkbox-p)
7262 (setq status (equal (match-string 0) "[X]"))
7263 (when (eq firstnew 'unknown)
7264 (setq firstnew (not status)))
7265 (replace-match
7266 (if (if arg (not status) firstnew) "[X]" "[ ]") t t))
7267 (beginning-of-line 2)))))
7268 (org-update-checkbox-count-maybe))
7270 (defun org-update-checkbox-count-maybe ()
7271 "Update checkbox statistics unless turned off by user."
7272 (when org-provide-checkbox-statistics
7273 (org-update-checkbox-count)))
7275 (defun org-update-checkbox-count (&optional all)
7276 "Update the checkbox statistics in the current section.
7277 This will find all statistic cookies like [57%] and [6/12] and update them
7278 with the current numbers. With optional prefix argument ALL, do this for
7279 the whole buffer."
7280 (interactive "P")
7281 (save-excursion
7282 (let* ((buffer-invisibility-spec (org-inhibit-invisibility)) ; Emacs 21
7283 (beg (condition-case nil
7284 (progn (outline-back-to-heading) (point))
7285 (error (point-min))))
7286 (end (move-marker (make-marker)
7287 (progn (outline-next-heading) (point))))
7288 (re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
7289 (re-box "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)")
7290 (re-find (concat re "\\|" re-box))
7291 beg-cookie end-cookie is-percent c-on c-off lim
7292 eline curr-ind next-ind continue-from startsearch
7293 (cstat 0)
7295 (when all
7296 (goto-char (point-min))
7297 (outline-next-heading)
7298 (setq beg (point) end (point-max)))
7299 (goto-char end)
7300 ;; find each statistic cookie
7301 (while (re-search-backward re-find beg t)
7302 (setq beg-cookie (match-beginning 1)
7303 end-cookie (match-end 1)
7304 cstat (+ cstat (if end-cookie 1 0))
7305 startsearch (point-at-eol)
7306 continue-from (point-at-bol)
7307 is-percent (match-beginning 2)
7308 lim (cond
7309 ((org-on-heading-p) (outline-next-heading) (point))
7310 ((org-at-item-p) (org-end-of-item) (point))
7311 (t nil))
7312 c-on 0
7313 c-off 0)
7314 (when lim
7315 ;; find first checkbox for this cookie and gather
7316 ;; statistics from all that are at this indentation level
7317 (goto-char startsearch)
7318 (if (re-search-forward re-box lim t)
7319 (progn
7320 (org-beginning-of-item)
7321 (setq curr-ind (org-get-indentation))
7322 (setq next-ind curr-ind)
7323 (while (= curr-ind next-ind)
7324 (save-excursion (end-of-line) (setq eline (point)))
7325 (if (re-search-forward re-box eline t)
7326 (if (member (match-string 2) '("[ ]" "[-]"))
7327 (setq c-off (1+ c-off))
7328 (setq c-on (1+ c-on))
7331 (org-end-of-item)
7332 (setq next-ind (org-get-indentation))
7334 (goto-char continue-from)
7335 ;; update cookie
7336 (when end-cookie
7337 (delete-region beg-cookie end-cookie)
7338 (goto-char beg-cookie)
7339 (insert
7340 (if is-percent
7341 (format "[%d%%]" (/ (* 100 c-on) (max 1 (+ c-on c-off))))
7342 (format "[%d/%d]" c-on (+ c-on c-off)))))
7343 ;; update items checkbox if it has one
7344 (when (org-at-item-p)
7345 (org-beginning-of-item)
7346 (when (and (> (+ c-on c-off) 0)
7347 (re-search-forward re-box (point-at-eol) t))
7348 (setq beg-cookie (match-beginning 2)
7349 end-cookie (match-end 2))
7350 (delete-region beg-cookie end-cookie)
7351 (goto-char beg-cookie)
7352 (cond ((= c-off 0) (insert "[X]"))
7353 ((= c-on 0) (insert "[ ]"))
7354 (t (insert "[-]")))
7356 (goto-char continue-from))
7357 (when (interactive-p)
7358 (message "Checkbox satistics updated %s (%d places)"
7359 (if all "in entire file" "in current outline entry") cstat)))))
7361 (defun org-get-checkbox-statistics-face ()
7362 "Select the face for checkbox statistics.
7363 The face will be `org-done' when all relevant boxes are checked. Otherwise
7364 it will be `org-todo'."
7365 (if (match-end 1)
7366 (if (equal (match-string 1) "100%") 'org-done 'org-todo)
7367 (if (and (> (match-end 2) (match-beginning 2))
7368 (equal (match-string 2) (match-string 3)))
7369 'org-done
7370 'org-todo)))
7372 (defun org-get-indentation (&optional line)
7373 "Get the indentation of the current line, interpreting tabs.
7374 When LINE is given, assume it represents a line and compute its indentation."
7375 (if line
7376 (if (string-match "^ *" (org-remove-tabs line))
7377 (match-end 0))
7378 (save-excursion
7379 (beginning-of-line 1)
7380 (skip-chars-forward " \t")
7381 (current-column))))
7383 (defun org-remove-tabs (s &optional width)
7384 "Replace tabulators in S with spaces.
7385 Assumes that s is a single line, starting in column 0."
7386 (setq width (or width tab-width))
7387 (while (string-match "\t" s)
7388 (setq s (replace-match
7389 (make-string
7390 (- (* width (/ (+ (match-beginning 0) width) width))
7391 (match-beginning 0)) ?\ )
7392 t t s)))
7395 (defun org-fix-indentation (line ind)
7396 "Fix indentation in LINE.
7397 IND is a cons cell with target and minimum indentation.
7398 If the current indenation in LINE is smaller than the minimum,
7399 leave it alone. If it is larger than ind, set it to the target."
7400 (let* ((l (org-remove-tabs line))
7401 (i (org-get-indentation l))
7402 (i1 (car ind)) (i2 (cdr ind)))
7403 (if (>= i i2) (setq l (substring line i2)))
7404 (if (> i1 0)
7405 (concat (make-string i1 ?\ ) l)
7406 l)))
7408 (defcustom org-empty-line-terminates-plain-lists nil
7409 "Non-nil means, an empty line ends all plain list levels.
7410 When nil, empty lines are part of the preceeding item."
7411 :group 'org-plain-lists
7412 :type 'boolean)
7414 (defun org-beginning-of-item ()
7415 "Go to the beginning of the current hand-formatted item.
7416 If the cursor is not in an item, throw an error."
7417 (interactive)
7418 (let ((pos (point))
7419 (limit (save-excursion
7420 (condition-case nil
7421 (progn
7422 (org-back-to-heading)
7423 (beginning-of-line 2) (point))
7424 (error (point-min)))))
7425 (ind-empty (if org-empty-line-terminates-plain-lists 0 10000))
7426 ind ind1)
7427 (if (org-at-item-p)
7428 (beginning-of-line 1)
7429 (beginning-of-line 1)
7430 (skip-chars-forward " \t")
7431 (setq ind (current-column))
7432 (if (catch 'exit
7433 (while t
7434 (beginning-of-line 0)
7435 (if (or (bobp) (< (point) limit)) (throw 'exit nil))
7437 (if (looking-at "[ \t]*$")
7438 (setq ind1 ind-empty)
7439 (skip-chars-forward " \t")
7440 (setq ind1 (current-column)))
7441 (if (< ind1 ind)
7442 (progn (beginning-of-line 1) (throw 'exit (org-at-item-p))))))
7444 (goto-char pos)
7445 (error "Not in an item")))))
7447 (defun org-end-of-item ()
7448 "Go to the end of the current hand-formatted item.
7449 If the cursor is not in an item, throw an error."
7450 (interactive)
7451 (let* ((pos (point))
7452 ind1
7453 (ind-empty (if org-empty-line-terminates-plain-lists 0 10000))
7454 (limit (save-excursion (outline-next-heading) (point)))
7455 (ind (save-excursion
7456 (org-beginning-of-item)
7457 (skip-chars-forward " \t")
7458 (current-column)))
7459 (end (catch 'exit
7460 (while t
7461 (beginning-of-line 2)
7462 (if (eobp) (throw 'exit (point)))
7463 (if (>= (point) limit) (throw 'exit (point-at-bol)))
7464 (if (looking-at "[ \t]*$")
7465 (setq ind1 ind-empty)
7466 (skip-chars-forward " \t")
7467 (setq ind1 (current-column)))
7468 (if (<= ind1 ind)
7469 (throw 'exit (point-at-bol)))))))
7470 (if end
7471 (goto-char end)
7472 (goto-char pos)
7473 (error "Not in an item"))))
7475 (defun org-next-item ()
7476 "Move to the beginning of the next item in the current plain list.
7477 Error if not at a plain list, or if this is the last item in the list."
7478 (interactive)
7479 (let (ind ind1 (pos (point)))
7480 (org-beginning-of-item)
7481 (setq ind (org-get-indentation))
7482 (org-end-of-item)
7483 (setq ind1 (org-get-indentation))
7484 (unless (and (org-at-item-p) (= ind ind1))
7485 (goto-char pos)
7486 (error "On last item"))))
7488 (defun org-previous-item ()
7489 "Move to the beginning of the previous item in the current plain list.
7490 Error if not at a plain list, or if this is the first item in the list."
7491 (interactive)
7492 (let (beg ind ind1 (pos (point)))
7493 (org-beginning-of-item)
7494 (setq beg (point))
7495 (setq ind (org-get-indentation))
7496 (goto-char beg)
7497 (catch 'exit
7498 (while t
7499 (beginning-of-line 0)
7500 (if (looking-at "[ \t]*$")
7502 (if (<= (setq ind1 (org-get-indentation)) ind)
7503 (throw 'exit t)))))
7504 (condition-case nil
7505 (if (or (not (org-at-item-p))
7506 (< ind1 (1- ind)))
7507 (error "")
7508 (org-beginning-of-item))
7509 (error (goto-char pos)
7510 (error "On first item")))))
7512 (defun org-first-list-item-p ()
7513 "Is this heading the item in a plain list?"
7514 (unless (org-at-item-p)
7515 (error "Not at a plain list item"))
7516 (org-beginning-of-item)
7517 (= (point) (save-excursion (org-beginning-of-item-list))))
7519 (defun org-move-item-down ()
7520 "Move the plain list item at point down, i.e. swap with following item.
7521 Subitems (items with larger indentation) are considered part of the item,
7522 so this really moves item trees."
7523 (interactive)
7524 (let (beg beg0 end end0 ind ind1 (pos (point)) txt ne-end ne-beg)
7525 (org-beginning-of-item)
7526 (setq beg0 (point))
7527 (save-excursion
7528 (setq ne-beg (org-back-over-empty-lines))
7529 (setq beg (point)))
7530 (goto-char beg0)
7531 (setq ind (org-get-indentation))
7532 (org-end-of-item)
7533 (setq end0 (point))
7534 (setq ind1 (org-get-indentation))
7535 (setq ne-end (org-back-over-empty-lines))
7536 (setq end (point))
7537 (goto-char beg0)
7538 (when (and (org-first-list-item-p) (< ne-end ne-beg))
7539 ;; include less whitespace
7540 (save-excursion
7541 (goto-char beg)
7542 (forward-line (- ne-beg ne-end))
7543 (setq beg (point))))
7544 (goto-char end0)
7545 (if (and (org-at-item-p) (= ind ind1))
7546 (progn
7547 (org-end-of-item)
7548 (org-back-over-empty-lines)
7549 (setq txt (buffer-substring beg end))
7550 (save-excursion
7551 (delete-region beg end))
7552 (setq pos (point))
7553 (insert txt)
7554 (goto-char pos) (org-skip-whitespace)
7555 (org-maybe-renumber-ordered-list))
7556 (goto-char pos)
7557 (error "Cannot move this item further down"))))
7559 (defun org-move-item-up (arg)
7560 "Move the plain list item at point up, i.e. swap with previous item.
7561 Subitems (items with larger indentation) are considered part of the item,
7562 so this really moves item trees."
7563 (interactive "p")
7564 (let (beg beg0 end ind ind1 (pos (point)) txt
7565 ne-beg ne-ins ins-end)
7566 (org-beginning-of-item)
7567 (setq beg0 (point))
7568 (setq ind (org-get-indentation))
7569 (save-excursion
7570 (setq ne-beg (org-back-over-empty-lines))
7571 (setq beg (point)))
7572 (goto-char beg0)
7573 (org-end-of-item)
7574 (setq end (point))
7575 (goto-char beg0)
7576 (catch 'exit
7577 (while t
7578 (beginning-of-line 0)
7579 (if (looking-at "[ \t]*$")
7580 (if org-empty-line-terminates-plain-lists
7581 (progn
7582 (goto-char pos)
7583 (error "Cannot move this item further up"))
7584 nil)
7585 (if (<= (setq ind1 (org-get-indentation)) ind)
7586 (throw 'exit t)))))
7587 (condition-case nil
7588 (org-beginning-of-item)
7589 (error (goto-char beg)
7590 (error "Cannot move this item further up")))
7591 (setq ind1 (org-get-indentation))
7592 (if (and (org-at-item-p) (= ind ind1))
7593 (progn
7594 (setq ne-ins (org-back-over-empty-lines))
7595 (setq txt (buffer-substring beg end))
7596 (save-excursion
7597 (delete-region beg end))
7598 (setq pos (point))
7599 (insert txt)
7600 (setq ins-end (point))
7601 (goto-char pos) (org-skip-whitespace)
7603 (when (and (org-first-list-item-p) (> ne-ins ne-beg))
7604 ;; Move whitespace back to beginning
7605 (save-excursion
7606 (goto-char ins-end)
7607 (let ((kill-whole-line t))
7608 (kill-line (- ne-ins ne-beg)) (point)))
7609 (insert (make-string (- ne-ins ne-beg) ?\n)))
7611 (org-maybe-renumber-ordered-list))
7612 (goto-char pos)
7613 (error "Cannot move this item further up"))))
7615 (defun org-maybe-renumber-ordered-list ()
7616 "Renumber the ordered list at point if setup allows it.
7617 This tests the user option `org-auto-renumber-ordered-lists' before
7618 doing the renumbering."
7619 (interactive)
7620 (when (and org-auto-renumber-ordered-lists
7621 (org-at-item-p))
7622 (if (match-beginning 3)
7623 (org-renumber-ordered-list 1)
7624 (org-fix-bullet-type))))
7626 (defun org-maybe-renumber-ordered-list-safe ()
7627 (condition-case nil
7628 (save-excursion
7629 (org-maybe-renumber-ordered-list))
7630 (error nil)))
7632 (defun org-cycle-list-bullet (&optional which)
7633 "Cycle through the different itemize/enumerate bullets.
7634 This cycle the entire list level through the sequence:
7636 `-' -> `+' -> `*' -> `1.' -> `1)'
7638 If WHICH is a string, use that as the new bullet. If WHICH is an integer,
7639 0 meand `-', 1 means `+' etc."
7640 (interactive "P")
7641 (org-preserve-lc
7642 (org-beginning-of-item-list)
7643 (org-at-item-p)
7644 (beginning-of-line 1)
7645 (let ((current (match-string 0))
7646 (prevp (eq which 'previous))
7647 new)
7648 (setq new (cond
7649 ((and (numberp which)
7650 (nth (1- which) '("-" "+" "*" "1." "1)"))))
7651 ((string-match "-" current) (if prevp "1)" "+"))
7652 ((string-match "\\+" current)
7653 (if prevp "-" (if (looking-at "\\S-") "1." "*")))
7654 ((string-match "\\*" current) (if prevp "+" "1."))
7655 ((string-match "\\." current) (if prevp "*" "1)"))
7656 ((string-match ")" current) (if prevp "1." "-"))
7657 (t (error "This should not happen"))))
7658 (and (looking-at "\\([ \t]*\\)\\S-+") (replace-match (concat "\\1" new)))
7659 (org-fix-bullet-type)
7660 (org-maybe-renumber-ordered-list))))
7662 (defun org-get-string-indentation (s)
7663 "What indentation has S due to SPACE and TAB at the beginning of the string?"
7664 (let ((n -1) (i 0) (w tab-width) c)
7665 (catch 'exit
7666 (while (< (setq n (1+ n)) (length s))
7667 (setq c (aref s n))
7668 (cond ((= c ?\ ) (setq i (1+ i)))
7669 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
7670 (t (throw 'exit t)))))
7673 (defun org-renumber-ordered-list (arg)
7674 "Renumber an ordered plain list.
7675 Cursor needs to be in the first line of an item, the line that starts
7676 with something like \"1.\" or \"2)\"."
7677 (interactive "p")
7678 (unless (and (org-at-item-p)
7679 (match-beginning 3))
7680 (error "This is not an ordered list"))
7681 (let ((line (org-current-line))
7682 (col (current-column))
7683 (ind (org-get-string-indentation
7684 (buffer-substring (point-at-bol) (match-beginning 3))))
7685 ;; (term (substring (match-string 3) -1))
7686 ind1 (n (1- arg))
7687 fmt)
7688 ;; find where this list begins
7689 (org-beginning-of-item-list)
7690 (looking-at "[ \t]*[0-9]+\\([.)]\\)")
7691 (setq fmt (concat "%d" (match-string 1)))
7692 (beginning-of-line 0)
7693 ;; walk forward and replace these numbers
7694 (catch 'exit
7695 (while t
7696 (catch 'next
7697 (beginning-of-line 2)
7698 (if (eobp) (throw 'exit nil))
7699 (if (looking-at "[ \t]*$") (throw 'next nil))
7700 (skip-chars-forward " \t") (setq ind1 (current-column))
7701 (if (> ind1 ind) (throw 'next t))
7702 (if (< ind1 ind) (throw 'exit t))
7703 (if (not (org-at-item-p)) (throw 'exit nil))
7704 (delete-region (match-beginning 2) (match-end 2))
7705 (goto-char (match-beginning 2))
7706 (insert (format fmt (setq n (1+ n)))))))
7707 (goto-line line)
7708 (move-to-column col)))
7710 (defun org-fix-bullet-type ()
7711 "Make sure all items in this list have the same bullet as the firsst item."
7712 (interactive)
7713 (unless (org-at-item-p) (error "This is not a list"))
7714 (let ((line (org-current-line))
7715 (col (current-column))
7716 (ind (current-indentation))
7717 ind1 bullet)
7718 ;; find where this list begins
7719 (org-beginning-of-item-list)
7720 (beginning-of-line 1)
7721 ;; find out what the bullet type is
7722 (looking-at "[ \t]*\\(\\S-+\\)")
7723 (setq bullet (match-string 1))
7724 ;; walk forward and replace these numbers
7725 (beginning-of-line 0)
7726 (catch 'exit
7727 (while t
7728 (catch 'next
7729 (beginning-of-line 2)
7730 (if (eobp) (throw 'exit nil))
7731 (if (looking-at "[ \t]*$") (throw 'next nil))
7732 (skip-chars-forward " \t") (setq ind1 (current-column))
7733 (if (> ind1 ind) (throw 'next t))
7734 (if (< ind1 ind) (throw 'exit t))
7735 (if (not (org-at-item-p)) (throw 'exit nil))
7736 (skip-chars-forward " \t")
7737 (looking-at "\\S-+")
7738 (replace-match bullet))))
7739 (goto-line line)
7740 (move-to-column col)
7741 (if (string-match "[0-9]" bullet)
7742 (org-renumber-ordered-list 1))))
7744 (defun org-beginning-of-item-list ()
7745 "Go to the beginning of the current item list.
7746 I.e. to the first item in this list."
7747 (interactive)
7748 (org-beginning-of-item)
7749 (let ((pos (point-at-bol))
7750 (ind (org-get-indentation))
7751 ind1)
7752 ;; find where this list begins
7753 (catch 'exit
7754 (while t
7755 (catch 'next
7756 (beginning-of-line 0)
7757 (if (looking-at "[ \t]*$")
7758 (throw (if (bobp) 'exit 'next) t))
7759 (skip-chars-forward " \t") (setq ind1 (current-column))
7760 (if (or (< ind1 ind)
7761 (and (= ind1 ind)
7762 (not (org-at-item-p)))
7763 (bobp))
7764 (throw 'exit t)
7765 (when (org-at-item-p) (setq pos (point-at-bol)))))))
7766 (goto-char pos)))
7769 (defun org-end-of-item-list ()
7770 "Go to the end of the current item list.
7771 I.e. to the text after the last item."
7772 (interactive)
7773 (org-beginning-of-item)
7774 (let ((pos (point-at-bol))
7775 (ind (org-get-indentation))
7776 ind1)
7777 ;; find where this list begins
7778 (catch 'exit
7779 (while t
7780 (catch 'next
7781 (beginning-of-line 2)
7782 (if (looking-at "[ \t]*$")
7783 (throw (if (eobp) 'exit 'next) t))
7784 (skip-chars-forward " \t") (setq ind1 (current-column))
7785 (if (or (< ind1 ind)
7786 (and (= ind1 ind)
7787 (not (org-at-item-p)))
7788 (eobp))
7789 (progn
7790 (setq pos (point-at-bol))
7791 (throw 'exit t))))))
7792 (goto-char pos)))
7795 (defvar org-last-indent-begin-marker (make-marker))
7796 (defvar org-last-indent-end-marker (make-marker))
7798 (defun org-outdent-item (arg)
7799 "Outdent a local list item."
7800 (interactive "p")
7801 (org-indent-item (- arg)))
7803 (defun org-indent-item (arg)
7804 "Indent a local list item."
7805 (interactive "p")
7806 (unless (org-at-item-p)
7807 (error "Not on an item"))
7808 (save-excursion
7809 (let (beg end ind ind1 tmp delta ind-down ind-up)
7810 (if (memq last-command '(org-shiftmetaright org-shiftmetaleft))
7811 (setq beg org-last-indent-begin-marker
7812 end org-last-indent-end-marker)
7813 (org-beginning-of-item)
7814 (setq beg (move-marker org-last-indent-begin-marker (point)))
7815 (org-end-of-item)
7816 (setq end (move-marker org-last-indent-end-marker (point))))
7817 (goto-char beg)
7818 (setq tmp (org-item-indent-positions)
7819 ind (car tmp)
7820 ind-down (nth 2 tmp)
7821 ind-up (nth 1 tmp)
7822 delta (if (> arg 0)
7823 (if ind-down (- ind-down ind) 2)
7824 (if ind-up (- ind-up ind) -2)))
7825 (if (< (+ delta ind) 0) (error "Cannot outdent beyond margin"))
7826 (while (< (point) end)
7827 (beginning-of-line 1)
7828 (skip-chars-forward " \t") (setq ind1 (current-column))
7829 (delete-region (point-at-bol) (point))
7830 (or (eolp) (indent-to-column (+ ind1 delta)))
7831 (beginning-of-line 2))))
7832 (org-fix-bullet-type)
7833 (org-maybe-renumber-ordered-list-safe)
7834 (save-excursion
7835 (beginning-of-line 0)
7836 (condition-case nil (org-beginning-of-item) (error nil))
7837 (org-maybe-renumber-ordered-list-safe)))
7839 (defun org-item-indent-positions ()
7840 "Return indentation for plain list items.
7841 This returns a list with three values: The current indentation, the
7842 parent indentation and the indentation a child should habe.
7843 Assumes cursor in item line."
7844 (let* ((bolpos (point-at-bol))
7845 (ind (org-get-indentation))
7846 ind-down ind-up pos)
7847 (save-excursion
7848 (org-beginning-of-item-list)
7849 (skip-chars-backward "\n\r \t")
7850 (when (org-in-item-p)
7851 (org-beginning-of-item)
7852 (setq ind-up (org-get-indentation))))
7853 (setq pos (point))
7854 (save-excursion
7855 (cond
7856 ((and (condition-case nil (progn (org-previous-item) t)
7857 (error nil))
7858 (or (forward-char 1) t)
7859 (re-search-forward "^\\([ \t]*\\([-+]\\|\\([0-9]+[.)]\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)" bolpos t))
7860 (setq ind-down (org-get-indentation)))
7861 ((and (goto-char pos)
7862 (org-at-item-p))
7863 (goto-char (match-end 0))
7864 (skip-chars-forward " \t")
7865 (setq ind-down (current-column)))))
7866 (list ind ind-up ind-down)))
7868 ;;; The orgstruct minor mode
7870 ;; Define a minor mode which can be used in other modes in order to
7871 ;; integrate the org-mode structure editing commands.
7873 ;; This is really a hack, because the org-mode structure commands use
7874 ;; keys which normally belong to the major mode. Here is how it
7875 ;; works: The minor mode defines all the keys necessary to operate the
7876 ;; structure commands, but wraps the commands into a function which
7877 ;; tests if the cursor is currently at a headline or a plain list
7878 ;; item. If that is the case, the structure command is used,
7879 ;; temporarily setting many Org-mode variables like regular
7880 ;; expressions for filling etc. However, when any of those keys is
7881 ;; used at a different location, function uses `key-binding' to look
7882 ;; up if the key has an associated command in another currently active
7883 ;; keymap (minor modes, major mode, global), and executes that
7884 ;; command. There might be problems if any of the keys is otherwise
7885 ;; used as a prefix key.
7887 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
7888 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
7889 ;; addresses this by checking explicitly for both bindings.
7891 (defvar orgstruct-mode-map (make-sparse-keymap)
7892 "Keymap for the minor `orgstruct-mode'.")
7894 (defvar org-local-vars nil
7895 "List of local variables, for use by `orgstruct-mode'")
7897 ;;;###autoload
7898 (define-minor-mode orgstruct-mode
7899 "Toggle the minor more `orgstruct-mode'.
7900 This mode is for using Org-mode structure commands in other modes.
7901 The following key behave as if Org-mode was active, if the cursor
7902 is on a headline, or on a plain list item (both in the definition
7903 of Org-mode).
7905 M-up Move entry/item up
7906 M-down Move entry/item down
7907 M-left Promote
7908 M-right Demote
7909 M-S-up Move entry/item up
7910 M-S-down Move entry/item down
7911 M-S-left Promote subtree
7912 M-S-right Demote subtree
7913 M-q Fill paragraph and items like in Org-mode
7914 C-c ^ Sort entries
7915 C-c - Cycle list bullet
7916 TAB Cycle item visibility
7917 M-RET Insert new heading/item
7918 S-M-RET Insert new TODO heading / Chekbox item
7919 C-c C-c Set tags / toggle checkbox"
7920 nil " OrgStruct" nil
7921 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
7923 ;;;###autoload
7924 (defun turn-on-orgstruct ()
7925 "Unconditionally turn on `orgstruct-mode'."
7926 (orgstruct-mode 1))
7928 ;;;###autoload
7929 (defun turn-on-orgstruct++ ()
7930 "Unconditionally turn on `orgstruct-mode', and force org-mode indentations.
7931 In addition to setting orgstruct-mode, this also exports all indentation and
7932 autofilling variables from org-mode into the buffer. Note that turning
7933 off orgstruct-mode will *not* remove these additional settings."
7934 (orgstruct-mode 1)
7935 (let (var val)
7936 (mapc
7937 (lambda (x)
7938 (when (string-match
7939 "^\\(paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
7940 (symbol-name (car x)))
7941 (setq var (car x) val (nth 1 x))
7942 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
7943 org-local-vars)))
7945 (defun orgstruct-error ()
7946 "Error when there is no default binding for a structure key."
7947 (interactive)
7948 (error "This key has no function outside structure elements"))
7950 (defun orgstruct-setup ()
7951 "Setup orgstruct keymaps."
7952 (let ((nfunc 0)
7953 (bindings
7954 (list
7955 '([(meta up)] org-metaup)
7956 '([(meta down)] org-metadown)
7957 '([(meta left)] org-metaleft)
7958 '([(meta right)] org-metaright)
7959 '([(meta shift up)] org-shiftmetaup)
7960 '([(meta shift down)] org-shiftmetadown)
7961 '([(meta shift left)] org-shiftmetaleft)
7962 '([(meta shift right)] org-shiftmetaright)
7963 '([(shift up)] org-shiftup)
7964 '([(shift down)] org-shiftdown)
7965 '("\C-c\C-c" org-ctrl-c-ctrl-c)
7966 '("\M-q" fill-paragraph)
7967 '("\C-c^" org-sort)
7968 '("\C-c-" org-cycle-list-bullet)))
7969 elt key fun cmd)
7970 (while (setq elt (pop bindings))
7971 (setq nfunc (1+ nfunc))
7972 (setq key (org-key (car elt))
7973 fun (nth 1 elt)
7974 cmd (orgstruct-make-binding fun nfunc key))
7975 (org-defkey orgstruct-mode-map key cmd))
7977 ;; Special treatment needed for TAB and RET
7978 (org-defkey orgstruct-mode-map [(tab)]
7979 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
7980 (org-defkey orgstruct-mode-map "\C-i"
7981 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
7983 (org-defkey orgstruct-mode-map "\M-\C-m"
7984 (orgstruct-make-binding 'org-insert-heading 105
7985 "\M-\C-m" [(meta return)]))
7986 (org-defkey orgstruct-mode-map [(meta return)]
7987 (orgstruct-make-binding 'org-insert-heading 106
7988 [(meta return)] "\M-\C-m"))
7990 (org-defkey orgstruct-mode-map [(shift meta return)]
7991 (orgstruct-make-binding 'org-insert-todo-heading 107
7992 [(meta return)] "\M-\C-m"))
7994 (unless org-local-vars
7995 (setq org-local-vars (org-get-local-variables)))
7999 (defun orgstruct-make-binding (fun n &rest keys)
8000 "Create a function for binding in the structure minor mode.
8001 FUN is the command to call inside a table. N is used to create a unique
8002 command name. KEYS are keys that should be checked in for a command
8003 to execute outside of tables."
8004 (eval
8005 (list 'defun
8006 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
8007 '(arg)
8008 (concat "In Structure, run `" (symbol-name fun) "'.\n"
8009 "Outside of structure, run the binding of `"
8010 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
8011 "'.")
8012 '(interactive "p")
8013 (list 'if
8014 '(org-context-p 'headline 'item)
8015 (list 'org-run-like-in-org-mode (list 'quote fun))
8016 (list 'let '(orgstruct-mode)
8017 (list 'call-interactively
8018 (append '(or)
8019 (mapcar (lambda (k)
8020 (list 'key-binding k))
8021 keys)
8022 '('orgstruct-error))))))))
8024 (defun org-context-p (&rest contexts)
8025 "Check if local context is and of CONTEXTS.
8026 Possible values in the list of contexts are `table', `headline', and `item'."
8027 (let ((pos (point)))
8028 (goto-char (point-at-bol))
8029 (prog1 (or (and (memq 'table contexts)
8030 (looking-at "[ \t]*|"))
8031 (and (memq 'headline contexts)
8032 (looking-at "\\*+"))
8033 (and (memq 'item contexts)
8034 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)")))
8035 (goto-char pos))))
8037 (defun org-get-local-variables ()
8038 "Return a list of all local variables in an org-mode buffer."
8039 (let (varlist)
8040 (with-current-buffer (get-buffer-create "*Org tmp*")
8041 (erase-buffer)
8042 (org-mode)
8043 (setq varlist (buffer-local-variables)))
8044 (kill-buffer "*Org tmp*")
8045 (delq nil
8046 (mapcar
8047 (lambda (x)
8048 (setq x
8049 (if (symbolp x)
8050 (list x)
8051 (list (car x) (list 'quote (cdr x)))))
8052 (if (string-match
8053 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
8054 (symbol-name (car x)))
8055 x nil))
8056 varlist))))
8058 ;;;###autoload
8059 (defun org-run-like-in-org-mode (cmd)
8060 (unless org-local-vars
8061 (setq org-local-vars (org-get-local-variables)))
8062 (eval (list 'let org-local-vars
8063 (list 'call-interactively (list 'quote cmd)))))
8065 ;;;; Archiving
8067 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
8069 (defun org-archive-subtree (&optional find-done)
8070 "Move the current subtree to the archive.
8071 The archive can be a certain top-level heading in the current file, or in
8072 a different file. The tree will be moved to that location, the subtree
8073 heading be marked DONE, and the current time will be added.
8075 When called with prefix argument FIND-DONE, find whole trees without any
8076 open TODO items and archive them (after getting confirmation from the user).
8077 If the cursor is not at a headline when this comand is called, try all level
8078 1 trees. If the cursor is on a headline, only try the direct children of
8079 this heading."
8080 (interactive "P")
8081 (if find-done
8082 (org-archive-all-done)
8083 ;; Save all relevant TODO keyword-relatex variables
8085 (let ((tr-org-todo-line-regexp org-todo-line-regexp) ; keep despite compiler
8086 (tr-org-todo-keywords-1 org-todo-keywords-1)
8087 (tr-org-todo-kwd-alist org-todo-kwd-alist)
8088 (tr-org-done-keywords org-done-keywords)
8089 (tr-org-todo-regexp org-todo-regexp)
8090 (tr-org-todo-line-regexp org-todo-line-regexp)
8091 (tr-org-odd-levels-only org-odd-levels-only)
8092 (this-buffer (current-buffer))
8093 (org-archive-location org-archive-location)
8094 (re "^#\\+ARCHIVE:[ \t]+\\(\\S-.*\\S-\\)[ \t]*$")
8095 ;; start of variables that will be used for saving context
8096 ;; The compiler complains about them - keep them anyway!
8097 (file (abbreviate-file-name (buffer-file-name)))
8098 (olpath (mapconcat 'identity (org-get-outline-path) "/"))
8099 (time (format-time-string
8100 (substring (cdr org-time-stamp-formats) 1 -1)
8101 (current-time)))
8102 afile heading buffer level newfile-p
8103 category todo priority
8104 ;; start of variables that will be used for savind context
8105 ltags itags prop)
8107 ;; Try to find a local archive location
8108 (save-excursion
8109 (save-restriction
8110 (widen)
8111 (setq prop (org-entry-get nil "ARCHIVE" 'inherit))
8112 (if (and prop (string-match "\\S-" prop))
8113 (setq org-archive-location prop)
8114 (if (or (re-search-backward re nil t)
8115 (re-search-forward re nil t))
8116 (setq org-archive-location (match-string 1))))))
8118 (if (string-match "\\(.*\\)::\\(.*\\)" org-archive-location)
8119 (progn
8120 (setq afile (format (match-string 1 org-archive-location)
8121 (file-name-nondirectory buffer-file-name))
8122 heading (match-string 2 org-archive-location)))
8123 (error "Invalid `org-archive-location'"))
8124 (if (> (length afile) 0)
8125 (setq newfile-p (not (file-exists-p afile))
8126 buffer (find-file-noselect afile))
8127 (setq buffer (current-buffer)))
8128 (unless buffer
8129 (error "Cannot access file \"%s\"" afile))
8130 (if (and (> (length heading) 0)
8131 (string-match "^\\*+" heading))
8132 (setq level (match-end 0))
8133 (setq heading nil level 0))
8134 (save-excursion
8135 (org-back-to-heading t)
8136 ;; Get context information that will be lost by moving the tree
8137 (org-refresh-category-properties)
8138 (setq category (org-get-category)
8139 todo (and (looking-at org-todo-line-regexp)
8140 (match-string 2))
8141 priority (org-get-priority (if (match-end 3) (match-string 3) ""))
8142 ltags (org-get-tags)
8143 itags (org-delete-all ltags (org-get-tags-at)))
8144 (setq ltags (mapconcat 'identity ltags " ")
8145 itags (mapconcat 'identity itags " "))
8146 ;; We first only copy, in case something goes wrong
8147 ;; we need to protect this-command, to avoid kill-region sets it,
8148 ;; which would lead to duplication of subtrees
8149 (let (this-command) (org-copy-subtree))
8150 (set-buffer buffer)
8151 ;; Enforce org-mode for the archive buffer
8152 (if (not (org-mode-p))
8153 ;; Force the mode for future visits.
8154 (let ((org-insert-mode-line-in-empty-file t)
8155 (org-inhibit-startup t))
8156 (call-interactively 'org-mode)))
8157 (when newfile-p
8158 (goto-char (point-max))
8159 (insert (format "\nArchived entries from file %s\n\n"
8160 (buffer-file-name this-buffer))))
8161 ;; Force the TODO keywords of the original buffer
8162 (let ((org-todo-line-regexp tr-org-todo-line-regexp)
8163 (org-todo-keywords-1 tr-org-todo-keywords-1)
8164 (org-todo-kwd-alist tr-org-todo-kwd-alist)
8165 (org-done-keywords tr-org-done-keywords)
8166 (org-todo-regexp tr-org-todo-regexp)
8167 (org-todo-line-regexp tr-org-todo-line-regexp)
8168 (org-odd-levels-only
8169 (if (local-variable-p 'org-odd-levels-only (current-buffer))
8170 org-odd-levels-only
8171 tr-org-odd-levels-only)))
8172 (goto-char (point-min))
8173 (show-all)
8174 (if heading
8175 (progn
8176 (if (re-search-forward
8177 (concat "^" (regexp-quote heading)
8178 (org-re "[ \t]*\\(:[[:alnum:]_@:]+:\\)?[ \t]*\\($\\|\r\\)"))
8179 nil t)
8180 (goto-char (match-end 0))
8181 ;; Heading not found, just insert it at the end
8182 (goto-char (point-max))
8183 (or (bolp) (insert "\n"))
8184 (insert "\n" heading "\n")
8185 (end-of-line 0))
8186 ;; Make the subtree visible
8187 (show-subtree)
8188 (org-end-of-subtree t)
8189 (skip-chars-backward " \t\r\n")
8190 (and (looking-at "[ \t\r\n]*")
8191 (replace-match "\n\n")))
8192 ;; No specific heading, just go to end of file.
8193 (goto-char (point-max)) (insert "\n"))
8194 ;; Paste
8195 (org-paste-subtree (org-get-valid-level level 1))
8197 ;; Mark the entry as done
8198 (when (and org-archive-mark-done
8199 (looking-at org-todo-line-regexp)
8200 (or (not (match-end 2))
8201 (not (member (match-string 2) org-done-keywords))))
8202 (let (org-log-done org-todo-log-states)
8203 (org-todo
8204 (car (or (member org-archive-mark-done org-done-keywords)
8205 org-done-keywords)))))
8207 ;; Add the context info
8208 (when org-archive-save-context-info
8209 (let ((l org-archive-save-context-info) e n v)
8210 (while (setq e (pop l))
8211 (when (and (setq v (symbol-value e))
8212 (stringp v) (string-match "\\S-" v))
8213 (setq n (concat "ARCHIVE_" (upcase (symbol-name e))))
8214 (org-entry-put (point) n v)))))
8216 ;; Save and kill the buffer, if it is not the same buffer.
8217 (if (not (eq this-buffer buffer))
8218 (progn (save-buffer) (kill-buffer buffer)))))
8219 ;; Here we are back in the original buffer. Everything seems to have
8220 ;; worked. So now cut the tree and finish up.
8221 (let (this-command) (org-cut-subtree))
8222 (if (and (not (eobp)) (looking-at "[ \t]*$")) (kill-line))
8223 (message "Subtree archived %s"
8224 (if (eq this-buffer buffer)
8225 (concat "under heading: " heading)
8226 (concat "in file: " (abbreviate-file-name afile)))))))
8228 (defun org-refresh-category-properties ()
8229 "Refresh category text properties in teh buffer."
8230 (let ((def-cat (cond
8231 ((null org-category)
8232 (if buffer-file-name
8233 (file-name-sans-extension
8234 (file-name-nondirectory buffer-file-name))
8235 "???"))
8236 ((symbolp org-category) (symbol-name org-category))
8237 (t org-category)))
8238 beg end cat pos optionp)
8239 (org-unmodified
8240 (save-excursion
8241 (save-restriction
8242 (widen)
8243 (goto-char (point-min))
8244 (put-text-property (point) (point-max) 'org-category def-cat)
8245 (while (re-search-forward
8246 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
8247 (setq pos (match-end 0)
8248 optionp (equal (char-after (match-beginning 0)) ?#)
8249 cat (org-trim (match-string 2)))
8250 (if optionp
8251 (setq beg (point-at-bol) end (point-max))
8252 (org-back-to-heading t)
8253 (setq beg (point) end (org-end-of-subtree t t)))
8254 (put-text-property beg end 'org-category cat)
8255 (goto-char pos)))))))
8257 (defun org-archive-all-done (&optional tag)
8258 "Archive sublevels of the current tree without open TODO items.
8259 If the cursor is not on a headline, try all level 1 trees. If
8260 it is on a headline, try all direct children.
8261 When TAG is non-nil, don't move trees, but mark them with the ARCHIVE tag."
8262 (let ((re (concat "^\\*+ +" org-not-done-regexp)) re1
8263 (rea (concat ".*:" org-archive-tag ":"))
8264 (begm (make-marker))
8265 (endm (make-marker))
8266 (question (if tag "Set ARCHIVE tag (no open TODO items)? "
8267 "Move subtree to archive (no open TODO items)? "))
8268 beg end (cntarch 0))
8269 (if (org-on-heading-p)
8270 (progn
8271 (setq re1 (concat "^" (regexp-quote
8272 (make-string
8273 (1+ (- (match-end 0) (match-beginning 0) 1))
8274 ?*))
8275 " "))
8276 (move-marker begm (point))
8277 (move-marker endm (org-end-of-subtree t)))
8278 (setq re1 "^* ")
8279 (move-marker begm (point-min))
8280 (move-marker endm (point-max)))
8281 (save-excursion
8282 (goto-char begm)
8283 (while (re-search-forward re1 endm t)
8284 (setq beg (match-beginning 0)
8285 end (save-excursion (org-end-of-subtree t) (point)))
8286 (goto-char beg)
8287 (if (re-search-forward re end t)
8288 (goto-char end)
8289 (goto-char beg)
8290 (if (and (or (not tag) (not (looking-at rea)))
8291 (y-or-n-p question))
8292 (progn
8293 (if tag
8294 (org-toggle-tag org-archive-tag 'on)
8295 (org-archive-subtree))
8296 (setq cntarch (1+ cntarch)))
8297 (goto-char end)))))
8298 (message "%d trees archived" cntarch)))
8300 (defun org-cycle-hide-drawers (state)
8301 "Re-hide all drawers after a visibility state change."
8302 (when (and (org-mode-p)
8303 (not (memq state '(overview folded))))
8304 (save-excursion
8305 (let* ((globalp (memq state '(contents all)))
8306 (beg (if globalp (point-min) (point)))
8307 (end (if globalp (point-max) (org-end-of-subtree t))))
8308 (goto-char beg)
8309 (while (re-search-forward org-drawer-regexp end t)
8310 (org-flag-drawer t))))))
8312 (defun org-flag-drawer (flag)
8313 (save-excursion
8314 (beginning-of-line 1)
8315 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
8316 (let ((b (match-end 0))
8317 (outline-regexp org-outline-regexp))
8318 (if (re-search-forward
8319 "^[ \t]*:END:"
8320 (save-excursion (outline-next-heading) (point)) t)
8321 (outline-flag-region b (point-at-eol) flag)
8322 (error ":END: line missing"))))))
8324 (defun org-cycle-hide-archived-subtrees (state)
8325 "Re-hide all archived subtrees after a visibility state change."
8326 (when (and (not org-cycle-open-archived-trees)
8327 (not (memq state '(overview folded))))
8328 (save-excursion
8329 (let* ((globalp (memq state '(contents all)))
8330 (beg (if globalp (point-min) (point)))
8331 (end (if globalp (point-max) (org-end-of-subtree t))))
8332 (org-hide-archived-subtrees beg end)
8333 (goto-char beg)
8334 (if (looking-at (concat ".*:" org-archive-tag ":"))
8335 (message "%s" (substitute-command-keys
8336 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
8338 (defun org-force-cycle-archived ()
8339 "Cycle subtree even if it is archived."
8340 (interactive)
8341 (setq this-command 'org-cycle)
8342 (let ((org-cycle-open-archived-trees t))
8343 (call-interactively 'org-cycle)))
8345 (defun org-hide-archived-subtrees (beg end)
8346 "Re-hide all archived subtrees after a visibility state change."
8347 (save-excursion
8348 (let* ((re (concat ":" org-archive-tag ":")))
8349 (goto-char beg)
8350 (while (re-search-forward re end t)
8351 (and (org-on-heading-p) (hide-subtree))
8352 (org-end-of-subtree t)))))
8354 (defun org-toggle-tag (tag &optional onoff)
8355 "Toggle the tag TAG for the current line.
8356 If ONOFF is `on' or `off', don't toggle but set to this state."
8357 (unless (org-on-heading-p t) (error "Not on headling"))
8358 (let (res current)
8359 (save-excursion
8360 (beginning-of-line)
8361 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t]*$")
8362 (point-at-eol) t)
8363 (progn
8364 (setq current (match-string 1))
8365 (replace-match ""))
8366 (setq current ""))
8367 (setq current (nreverse (org-split-string current ":")))
8368 (cond
8369 ((eq onoff 'on)
8370 (setq res t)
8371 (or (member tag current) (push tag current)))
8372 ((eq onoff 'off)
8373 (or (not (member tag current)) (setq current (delete tag current))))
8374 (t (if (member tag current)
8375 (setq current (delete tag current))
8376 (setq res t)
8377 (push tag current))))
8378 (end-of-line 1)
8379 (if current
8380 (progn
8381 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
8382 (org-set-tags nil t))
8383 (delete-horizontal-space))
8384 (run-hooks 'org-after-tags-change-hook))
8385 res))
8387 (defun org-toggle-archive-tag (&optional arg)
8388 "Toggle the archive tag for the current headline.
8389 With prefix ARG, check all children of current headline and offer tagging
8390 the children that do not contain any open TODO items."
8391 (interactive "P")
8392 (if arg
8393 (org-archive-all-done 'tag)
8394 (let (set)
8395 (save-excursion
8396 (org-back-to-heading t)
8397 (setq set (org-toggle-tag org-archive-tag))
8398 (when set (hide-subtree)))
8399 (and set (beginning-of-line 1))
8400 (message "Subtree %s" (if set "archived" "unarchived")))))
8403 ;;;; Tables
8405 ;;; The table editor
8407 ;; Watch out: Here we are talking about two different kind of tables.
8408 ;; Most of the code is for the tables created with the Org-mode table editor.
8409 ;; Sometimes, we talk about tables created and edited with the table.el
8410 ;; Emacs package. We call the former org-type tables, and the latter
8411 ;; table.el-type tables.
8413 (defun org-before-change-function (beg end)
8414 "Every change indicates that a table might need an update."
8415 (setq org-table-may-need-update t))
8417 (defconst org-table-line-regexp "^[ \t]*|"
8418 "Detects an org-type table line.")
8419 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
8420 "Detects an org-type table line.")
8421 (defconst org-table-auto-recalculate-regexp "^[ \t]*| *# *\\(|\\|$\\)"
8422 "Detects a table line marked for automatic recalculation.")
8423 (defconst org-table-recalculate-regexp "^[ \t]*| *[#*] *\\(|\\|$\\)"
8424 "Detects a table line marked for automatic recalculation.")
8425 (defconst org-table-calculate-mark-regexp "^[ \t]*| *[!$^_#*] *\\(|\\|$\\)"
8426 "Detects a table line marked for automatic recalculation.")
8427 (defconst org-table-hline-regexp "^[ \t]*|-"
8428 "Detects an org-type table hline.")
8429 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
8430 "Detects a table-type table hline.")
8431 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
8432 "Detects an org-type or table-type table.")
8433 (defconst org-table-border-regexp "^[ \t]*[^| \t]"
8434 "Searching from within a table (any type) this finds the first line
8435 outside the table.")
8436 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
8437 "Searching from within a table (any type) this finds the first line
8438 outside the table.")
8440 (defvar org-table-last-highlighted-reference nil)
8441 (defvar org-table-formula-history nil)
8443 (defvar org-table-column-names nil
8444 "Alist with column names, derived from the `!' line.")
8445 (defvar org-table-column-name-regexp nil
8446 "Regular expression matching the current column names.")
8447 (defvar org-table-local-parameters nil
8448 "Alist with parameter names, derived from the `$' line.")
8449 (defvar org-table-named-field-locations nil
8450 "Alist with locations of named fields.")
8452 (defvar org-table-current-line-types nil
8453 "Table row types, non-nil only for the duration of a comand.")
8454 (defvar org-table-current-begin-line nil
8455 "Table begin line, non-nil only for the duration of a comand.")
8456 (defvar org-table-current-begin-pos nil
8457 "Table begin position, non-nil only for the duration of a comand.")
8458 (defvar org-table-dlines nil
8459 "Vector of data line line numbers in the current table.")
8460 (defvar org-table-hlines nil
8461 "Vector of hline line numbers in the current table.")
8463 (defconst org-table-range-regexp
8464 "@\\([-+]?I*[-+]?[0-9]*\\)?\\(\\$[-+]?[0-9]+\\)?\\(\\.\\.@?\\([-+]?I*[-+]?[0-9]*\\)?\\(\\$[-+]?[0-9]+\\)?\\)?"
8465 ;; 1 2 3 4 5
8466 "Regular expression for matching ranges in formulas.")
8468 (defconst org-table-range-regexp2
8469 (concat
8470 "\\(" "@[-0-9I$&]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\|" "\\$[a-zA-Z0-9]+" "\\)"
8471 "\\.\\."
8472 "\\(" "@?[-0-9I$&]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\|" "\\$[a-zA-Z0-9]+" "\\)")
8473 "Match a range for reference display.")
8475 (defconst org-table-translate-regexp
8476 (concat "\\(" "@[-0-9I$]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\)")
8477 "Match a reference that needs translation, for reference display.")
8479 (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
8481 (defun org-table-create-with-table.el ()
8482 "Use the table.el package to insert a new table.
8483 If there is already a table at point, convert between Org-mode tables
8484 and table.el tables."
8485 (interactive)
8486 (require 'table)
8487 (cond
8488 ((org-at-table.el-p)
8489 (if (y-or-n-p "Convert table to Org-mode table? ")
8490 (org-table-convert)))
8491 ((org-at-table-p)
8492 (if (y-or-n-p "Convert table to table.el table? ")
8493 (org-table-convert)))
8494 (t (call-interactively 'table-insert))))
8496 (defun org-table-create-or-convert-from-region (arg)
8497 "Convert region to table, or create an empty table.
8498 If there is an active region, convert it to a table, using the function
8499 `org-table-convert-region'. See the documentation of that function
8500 to learn how the prefix argument is interpreted to determine the field
8501 separator.
8502 If there is no such region, create an empty table with `org-table-create'."
8503 (interactive "P")
8504 (if (org-region-active-p)
8505 (org-table-convert-region (region-beginning) (region-end) arg)
8506 (org-table-create arg)))
8508 (defun org-table-create (&optional size)
8509 "Query for a size and insert a table skeleton.
8510 SIZE is a string Columns x Rows like for example \"3x2\"."
8511 (interactive "P")
8512 (unless size
8513 (setq size (read-string
8514 (concat "Table size Columns x Rows [e.g. "
8515 org-table-default-size "]: ")
8516 "" nil org-table-default-size)))
8518 (let* ((pos (point))
8519 (indent (make-string (current-column) ?\ ))
8520 (split (org-split-string size " *x *"))
8521 (rows (string-to-number (nth 1 split)))
8522 (columns (string-to-number (car split)))
8523 (line (concat (apply 'concat indent "|" (make-list columns " |"))
8524 "\n")))
8525 (if (string-match "^[ \t]*$" (buffer-substring-no-properties
8526 (point-at-bol) (point)))
8527 (beginning-of-line 1)
8528 (newline))
8529 ;; (mapcar (lambda (x) (insert line)) (make-list rows t))
8530 (dotimes (i rows) (insert line))
8531 (goto-char pos)
8532 (if (> rows 1)
8533 ;; Insert a hline after the first row.
8534 (progn
8535 (end-of-line 1)
8536 (insert "\n|-")
8537 (goto-char pos)))
8538 (org-table-align)))
8540 (defun org-table-convert-region (beg0 end0 &optional separator)
8541 "Convert region to a table.
8542 The region goes from BEG0 to END0, but these borders will be moved
8543 slightly, to make sure a beginning of line in the first line is included.
8545 SEPARATOR specifies the field separator in the lines. It can have the
8546 following values:
8548 '(4) Use the comma as a field separator
8549 '(16) Use a TAB as field separator
8550 integer When a number, use that many spaces as field separator
8551 nil When nil, the command tries to be smart and figure out the
8552 separator in the following way:
8553 - when each line contains a TAB, assume TAB-separated material
8554 - when each line contains a comme, assume CSV material
8555 - else, assume one or more SPACE charcters as separator."
8556 (interactive "rP")
8557 (let* ((beg (min beg0 end0))
8558 (end (max beg0 end0))
8560 (goto-char beg)
8561 (beginning-of-line 1)
8562 (setq beg (move-marker (make-marker) (point)))
8563 (goto-char end)
8564 (if (bolp) (backward-char 1) (end-of-line 1))
8565 (setq end (move-marker (make-marker) (point)))
8566 ;; Get the right field separator
8567 (unless separator
8568 (goto-char beg)
8569 (setq separator
8570 (cond
8571 ((not (re-search-forward "^[^\n\t]+$" end t)) '(16))
8572 ((not (re-search-forward "^[^\n,]+$" end t)) '(4))
8573 (t 1))))
8574 (setq re (cond
8575 ((equal separator '(4)) "^\\|\"?[ \t]*,[ \t]*\"?")
8576 ((equal separator '(16)) "^\\|\t")
8577 ((integerp separator)
8578 (format "^ *\\| *\t *\\| \\{%d,\\}" separator))
8579 (t (error "This should not happen"))))
8580 (goto-char beg)
8581 (while (re-search-forward re end t)
8582 (replace-match "| " t t))
8583 (goto-char beg)
8584 (insert " ")
8585 (org-table-align)))
8587 (defun org-table-import (file arg)
8588 "Import FILE as a table.
8589 The file is assumed to be tab-separated. Such files can be produced by most
8590 spreadsheet and database applications. If no tabs (at least one per line)
8591 are found, lines will be split on whitespace into fields."
8592 (interactive "f\nP")
8593 (or (bolp) (newline))
8594 (let ((beg (point))
8595 (pm (point-max)))
8596 (insert-file-contents file)
8597 (org-table-convert-region beg (+ (point) (- (point-max) pm)) arg)))
8599 (defun org-table-export ()
8600 "Export table as a tab-separated file.
8601 Such a file can be imported into a spreadsheet program like Excel."
8602 (interactive)
8603 (let* ((beg (org-table-begin))
8604 (end (org-table-end))
8605 (table (buffer-substring beg end))
8606 (file (read-file-name "Export table to: "))
8607 buf)
8608 (unless (or (not (file-exists-p file))
8609 (y-or-n-p (format "Overwrite file %s? " file)))
8610 (error "Abort"))
8611 (with-current-buffer (find-file-noselect file)
8612 (setq buf (current-buffer))
8613 (erase-buffer)
8614 (fundamental-mode)
8615 (insert table)
8616 (goto-char (point-min))
8617 (while (re-search-forward "^[ \t]*|[ \t]*" nil t)
8618 (replace-match "" t t)
8619 (end-of-line 1))
8620 (goto-char (point-min))
8621 (while (re-search-forward "[ \t]*|[ \t]*$" nil t)
8622 (replace-match "" t t)
8623 (goto-char (min (1+ (point)) (point-max))))
8624 (goto-char (point-min))
8625 (while (re-search-forward "^-[-+]*$" nil t)
8626 (replace-match "")
8627 (if (looking-at "\n")
8628 (delete-char 1)))
8629 (goto-char (point-min))
8630 (while (re-search-forward "[ \t]*|[ \t]*" nil t)
8631 (replace-match "\t" t t))
8632 (save-buffer))
8633 (kill-buffer buf)))
8635 (defvar org-table-aligned-begin-marker (make-marker)
8636 "Marker at the beginning of the table last aligned.
8637 Used to check if cursor still is in that table, to minimize realignment.")
8638 (defvar org-table-aligned-end-marker (make-marker)
8639 "Marker at the end of the table last aligned.
8640 Used to check if cursor still is in that table, to minimize realignment.")
8641 (defvar org-table-last-alignment nil
8642 "List of flags for flushright alignment, from the last re-alignment.
8643 This is being used to correctly align a single field after TAB or RET.")
8644 (defvar org-table-last-column-widths nil
8645 "List of max width of fields in each column.
8646 This is being used to correctly align a single field after TAB or RET.")
8647 (defvar org-table-overlay-coordinates nil
8648 "Overlay coordinates after each align of a table.")
8649 (make-variable-buffer-local 'org-table-overlay-coordinates)
8651 (defvar org-last-recalc-line nil)
8652 (defconst org-narrow-column-arrow "=>"
8653 "Used as display property in narrowed table columns.")
8655 (defun org-table-align ()
8656 "Align the table at point by aligning all vertical bars."
8657 (interactive)
8658 (let* (
8659 ;; Limits of table
8660 (beg (org-table-begin))
8661 (end (org-table-end))
8662 ;; Current cursor position
8663 (linepos (org-current-line))
8664 (colpos (org-table-current-column))
8665 (winstart (window-start))
8666 (winstartline (org-current-line (min winstart (1- (point-max)))))
8667 lines (new "") lengths l typenums ty fields maxfields i
8668 column
8669 (indent "") cnt frac
8670 rfmt hfmt
8671 (spaces '(1 . 1))
8672 (sp1 (car spaces))
8673 (sp2 (cdr spaces))
8674 (rfmt1 (concat
8675 (make-string sp2 ?\ ) "%%%s%ds" (make-string sp1 ?\ ) "|"))
8676 (hfmt1 (concat
8677 (make-string sp2 ?-) "%s" (make-string sp1 ?-) "+"))
8678 emptystrings links dates emph narrow fmax f1 len c e)
8679 (untabify beg end)
8680 (remove-text-properties beg end '(org-cwidth t org-dwidth t display t))
8681 ;; Check if we have links or dates
8682 (goto-char beg)
8683 (setq links (re-search-forward org-bracket-link-regexp end t))
8684 (goto-char beg)
8685 (setq emph (and org-hide-emphasis-markers
8686 (re-search-forward org-emph-re end t)))
8687 (goto-char beg)
8688 (setq dates (and org-display-custom-times
8689 (re-search-forward org-ts-regexp-both end t)))
8690 ;; Make sure the link properties are right
8691 (when links (goto-char beg) (while (org-activate-bracket-links end)))
8692 ;; Make sure the date properties are right
8693 (when dates (goto-char beg) (while (org-activate-dates end)))
8694 (when emph (goto-char beg) (while (org-do-emphasis-faces end)))
8696 ;; Check if we are narrowing any columns
8697 (goto-char beg)
8698 (setq narrow (and org-format-transports-properties-p
8699 (re-search-forward "<[0-9]+>" end t)))
8700 ;; Get the rows
8701 (setq lines (org-split-string
8702 (buffer-substring beg end) "\n"))
8703 ;; Store the indentation of the first line
8704 (if (string-match "^ *" (car lines))
8705 (setq indent (make-string (- (match-end 0) (match-beginning 0)) ?\ )))
8706 ;; Mark the hlines by setting the corresponding element to nil
8707 ;; At the same time, we remove trailing space.
8708 (setq lines (mapcar (lambda (l)
8709 (if (string-match "^ *|-" l)
8711 (if (string-match "[ \t]+$" l)
8712 (substring l 0 (match-beginning 0))
8713 l)))
8714 lines))
8715 ;; Get the data fields by splitting the lines.
8716 (setq fields (mapcar
8717 (lambda (l)
8718 (org-split-string l " *| *"))
8719 (delq nil (copy-sequence lines))))
8720 ;; How many fields in the longest line?
8721 (condition-case nil
8722 (setq maxfields (apply 'max (mapcar 'length fields)))
8723 (error
8724 (kill-region beg end)
8725 (org-table-create org-table-default-size)
8726 (error "Empty table - created default table")))
8727 ;; A list of empty strings to fill any short rows on output
8728 (setq emptystrings (make-list maxfields ""))
8729 ;; Check for special formatting.
8730 (setq i -1)
8731 (while (< (setq i (1+ i)) maxfields) ;; Loop over all columns
8732 (setq column (mapcar (lambda (x) (or (nth i x) "")) fields))
8733 ;; Check if there is an explicit width specified
8734 (when narrow
8735 (setq c column fmax nil)
8736 (while c
8737 (setq e (pop c))
8738 (if (and (stringp e) (string-match "^<\\([0-9]+\\)>$" e))
8739 (setq fmax (string-to-number (match-string 1 e)) c nil)))
8740 ;; Find fields that are wider than fmax, and shorten them
8741 (when fmax
8742 (loop for xx in column do
8743 (when (and (stringp xx)
8744 (> (org-string-width xx) fmax))
8745 (org-add-props xx nil
8746 'help-echo
8747 (concat "Clipped table field, use C-c ` to edit. Full value is:\n" (org-no-properties (copy-sequence xx))))
8748 (setq f1 (min fmax (or (string-match org-bracket-link-regexp xx) fmax)))
8749 (unless (> f1 1)
8750 (error "Cannot narrow field starting with wide link \"%s\""
8751 (match-string 0 xx)))
8752 (add-text-properties f1 (length xx) (list 'org-cwidth t) xx)
8753 (add-text-properties (- f1 2) f1
8754 (list 'display org-narrow-column-arrow)
8755 xx)))))
8756 ;; Get the maximum width for each column
8757 (push (apply 'max 1 (mapcar 'org-string-width column)) lengths)
8758 ;; Get the fraction of numbers, to decide about alignment of the column
8759 (setq cnt 0 frac 0.0)
8760 (loop for x in column do
8761 (if (equal x "")
8763 (setq frac ( / (+ (* frac cnt)
8764 (if (string-match org-table-number-regexp x) 1 0))
8765 (setq cnt (1+ cnt))))))
8766 (push (>= frac org-table-number-fraction) typenums))
8767 (setq lengths (nreverse lengths) typenums (nreverse typenums))
8769 ;; Store the alignment of this table, for later editing of single fields
8770 (setq org-table-last-alignment typenums
8771 org-table-last-column-widths lengths)
8773 ;; With invisible characters, `format' does not get the field width right
8774 ;; So we need to make these fields wide by hand.
8775 (when (or links emph)
8776 (loop for i from 0 upto (1- maxfields) do
8777 (setq len (nth i lengths))
8778 (loop for j from 0 upto (1- (length fields)) do
8779 (setq c (nthcdr i (car (nthcdr j fields))))
8780 (if (and (stringp (car c))
8781 (text-property-any 0 (length (car c)) 'invisible 'org-link (car c))
8782 ; (string-match org-bracket-link-regexp (car c))
8783 (< (org-string-width (car c)) len))
8784 (setcar c (concat (car c) (make-string (- len (org-string-width (car c))) ?\ )))))))
8786 ;; Compute the formats needed for output of the table
8787 (setq rfmt (concat indent "|") hfmt (concat indent "|"))
8788 (while (setq l (pop lengths))
8789 (setq ty (if (pop typenums) "" "-")) ; number types flushright
8790 (setq rfmt (concat rfmt (format rfmt1 ty l))
8791 hfmt (concat hfmt (format hfmt1 (make-string l ?-)))))
8792 (setq rfmt (concat rfmt "\n")
8793 hfmt (concat (substring hfmt 0 -1) "|\n"))
8795 (setq new (mapconcat
8796 (lambda (l)
8797 (if l (apply 'format rfmt
8798 (append (pop fields) emptystrings))
8799 hfmt))
8800 lines ""))
8801 ;; Replace the old one
8802 (delete-region beg end)
8803 (move-marker end nil)
8804 (move-marker org-table-aligned-begin-marker (point))
8805 (insert new)
8806 (move-marker org-table-aligned-end-marker (point))
8807 (when (and orgtbl-mode (not (org-mode-p)))
8808 (goto-char org-table-aligned-begin-marker)
8809 (while (org-hide-wide-columns org-table-aligned-end-marker)))
8810 ;; Try to move to the old location
8811 (goto-line winstartline)
8812 (setq winstart (point-at-bol))
8813 (goto-line linepos)
8814 (set-window-start (selected-window) winstart 'noforce)
8815 (org-table-goto-column colpos)
8816 (and org-table-overlay-coordinates (org-table-overlay-coordinates))
8817 (setq org-table-may-need-update nil)
8820 (defun org-string-width (s)
8821 "Compute width of string, ignoring invisible characters.
8822 This ignores character with invisibility property `org-link', and also
8823 characters with property `org-cwidth', because these will become invisible
8824 upon the next fontification round."
8825 (let (b l)
8826 (when (or (eq t buffer-invisibility-spec)
8827 (assq 'org-link buffer-invisibility-spec))
8828 (while (setq b (text-property-any 0 (length s)
8829 'invisible 'org-link s))
8830 (setq s (concat (substring s 0 b)
8831 (substring s (or (next-single-property-change
8832 b 'invisible s) (length s)))))))
8833 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
8834 (setq s (concat (substring s 0 b)
8835 (substring s (or (next-single-property-change
8836 b 'org-cwidth s) (length s))))))
8837 (setq l (string-width s) b -1)
8838 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
8839 (setq l (- l (get-text-property b 'org-dwidth-n s))))
8842 (defun org-table-begin (&optional table-type)
8843 "Find the beginning of the table and return its position.
8844 With argument TABLE-TYPE, go to the beginning of a table.el-type table."
8845 (save-excursion
8846 (if (not (re-search-backward
8847 (if table-type org-table-any-border-regexp
8848 org-table-border-regexp)
8849 nil t))
8850 (progn (goto-char (point-min)) (point))
8851 (goto-char (match-beginning 0))
8852 (beginning-of-line 2)
8853 (point))))
8855 (defun org-table-end (&optional table-type)
8856 "Find the end of the table and return its position.
8857 With argument TABLE-TYPE, go to the end of a table.el-type table."
8858 (save-excursion
8859 (if (not (re-search-forward
8860 (if table-type org-table-any-border-regexp
8861 org-table-border-regexp)
8862 nil t))
8863 (goto-char (point-max))
8864 (goto-char (match-beginning 0)))
8865 (point-marker)))
8867 (defun org-table-justify-field-maybe (&optional new)
8868 "Justify the current field, text to left, number to right.
8869 Optional argument NEW may specify text to replace the current field content."
8870 (cond
8871 ((and (not new) org-table-may-need-update)) ; Realignment will happen anyway
8872 ((org-at-table-hline-p))
8873 ((and (not new)
8874 (or (not (equal (marker-buffer org-table-aligned-begin-marker)
8875 (current-buffer)))
8876 (< (point) org-table-aligned-begin-marker)
8877 (>= (point) org-table-aligned-end-marker)))
8878 ;; This is not the same table, force a full re-align
8879 (setq org-table-may-need-update t))
8880 (t ;; realign the current field, based on previous full realign
8881 (let* ((pos (point)) s
8882 (col (org-table-current-column))
8883 (num (if (> col 0) (nth (1- col) org-table-last-alignment)))
8884 l f n o e)
8885 (when (> col 0)
8886 (skip-chars-backward "^|\n")
8887 (if (looking-at " *\\([^|\n]*?\\) *\\(|\\|$\\)")
8888 (progn
8889 (setq s (match-string 1)
8890 o (match-string 0)
8891 l (max 1 (- (match-end 0) (match-beginning 0) 3))
8892 e (not (= (match-beginning 2) (match-end 2))))
8893 (setq f (format (if num " %%%ds %s" " %%-%ds %s")
8894 l (if e "|" (setq org-table-may-need-update t) ""))
8895 n (format f s))
8896 (if new
8897 (if (<= (length new) l) ;; FIXME: length -> str-width?
8898 (setq n (format f new))
8899 (setq n (concat new "|") org-table-may-need-update t)))
8900 (or (equal n o)
8901 (let (org-table-may-need-update)
8902 (replace-match n t t))))
8903 (setq org-table-may-need-update t))
8904 (goto-char pos))))))
8906 (defun org-table-next-field ()
8907 "Go to the next field in the current table, creating new lines as needed.
8908 Before doing so, re-align the table if necessary."
8909 (interactive)
8910 (org-table-maybe-eval-formula)
8911 (org-table-maybe-recalculate-line)
8912 (if (and org-table-automatic-realign
8913 org-table-may-need-update)
8914 (org-table-align))
8915 (let ((end (org-table-end)))
8916 (if (org-at-table-hline-p)
8917 (end-of-line 1))
8918 (condition-case nil
8919 (progn
8920 (re-search-forward "|" end)
8921 (if (looking-at "[ \t]*$")
8922 (re-search-forward "|" end))
8923 (if (and (looking-at "-")
8924 org-table-tab-jumps-over-hlines
8925 (re-search-forward "^[ \t]*|\\([^-]\\)" end t))
8926 (goto-char (match-beginning 1)))
8927 (if (looking-at "-")
8928 (progn
8929 (beginning-of-line 0)
8930 (org-table-insert-row 'below))
8931 (if (looking-at " ") (forward-char 1))))
8932 (error
8933 (org-table-insert-row 'below)))))
8935 (defun org-table-previous-field ()
8936 "Go to the previous field in the table.
8937 Before doing so, re-align the table if necessary."
8938 (interactive)
8939 (org-table-justify-field-maybe)
8940 (org-table-maybe-recalculate-line)
8941 (if (and org-table-automatic-realign
8942 org-table-may-need-update)
8943 (org-table-align))
8944 (if (org-at-table-hline-p)
8945 (end-of-line 1))
8946 (re-search-backward "|" (org-table-begin))
8947 (re-search-backward "|" (org-table-begin))
8948 (while (looking-at "|\\(-\\|[ \t]*$\\)")
8949 (re-search-backward "|" (org-table-begin)))
8950 (if (looking-at "| ?")
8951 (goto-char (match-end 0))))
8953 (defun org-table-next-row ()
8954 "Go to the next row (same column) in the current table.
8955 Before doing so, re-align the table if necessary."
8956 (interactive)
8957 (org-table-maybe-eval-formula)
8958 (org-table-maybe-recalculate-line)
8959 (if (or (looking-at "[ \t]*$")
8960 (save-excursion (skip-chars-backward " \t") (bolp)))
8961 (newline)
8962 (if (and org-table-automatic-realign
8963 org-table-may-need-update)
8964 (org-table-align))
8965 (let ((col (org-table-current-column)))
8966 (beginning-of-line 2)
8967 (if (or (not (org-at-table-p))
8968 (org-at-table-hline-p))
8969 (progn
8970 (beginning-of-line 0)
8971 (org-table-insert-row 'below)))
8972 (org-table-goto-column col)
8973 (skip-chars-backward "^|\n\r")
8974 (if (looking-at " ") (forward-char 1)))))
8976 (defun org-table-copy-down (n)
8977 "Copy a field down in the current column.
8978 If the field at the cursor is empty, copy into it the content of the nearest
8979 non-empty field above. With argument N, use the Nth non-empty field.
8980 If the current field is not empty, it is copied down to the next row, and
8981 the cursor is moved with it. Therefore, repeating this command causes the
8982 column to be filled row-by-row.
8983 If the variable `org-table-copy-increment' is non-nil and the field is an
8984 integer or a timestamp, it will be incremented while copying. In the case of
8985 a timestamp, if the cursor is on the year, change the year. If it is on the
8986 month or the day, change that. Point will stay on the current date field
8987 in order to easily repeat the interval."
8988 (interactive "p")
8989 (let* ((colpos (org-table-current-column))
8990 (col (current-column))
8991 (field (org-table-get-field))
8992 (non-empty (string-match "[^ \t]" field))
8993 (beg (org-table-begin))
8994 txt)
8995 (org-table-check-inside-data-field)
8996 (if non-empty
8997 (progn
8998 (setq txt (org-trim field))
8999 (org-table-next-row)
9000 (org-table-blank-field))
9001 (save-excursion
9002 (setq txt
9003 (catch 'exit
9004 (while (progn (beginning-of-line 1)
9005 (re-search-backward org-table-dataline-regexp
9006 beg t))
9007 (org-table-goto-column colpos t)
9008 (if (and (looking-at
9009 "|[ \t]*\\([^| \t][^|]*?\\)[ \t]*|")
9010 (= (setq n (1- n)) 0))
9011 (throw 'exit (match-string 1))))))))
9012 (if txt
9013 (progn
9014 (if (and org-table-copy-increment
9015 (string-match "^[0-9]+$" txt))
9016 (setq txt (format "%d" (+ (string-to-number txt) 1))))
9017 (insert txt)
9018 (move-to-column col)
9019 (if (and org-table-copy-increment (org-at-timestamp-p t))
9020 (org-timestamp-up 1)
9021 (org-table-maybe-recalculate-line))
9022 (org-table-align)
9023 (move-to-column col))
9024 (error "No non-empty field found"))))
9026 (defun org-table-check-inside-data-field ()
9027 "Is point inside a table data field?
9028 I.e. not on a hline or before the first or after the last column?
9029 This actually throws an error, so it aborts the current command."
9030 (if (or (not (org-at-table-p))
9031 (= (org-table-current-column) 0)
9032 (org-at-table-hline-p)
9033 (looking-at "[ \t]*$"))
9034 (error "Not in table data field")))
9036 (defvar org-table-clip nil
9037 "Clipboard for table regions.")
9039 (defun org-table-blank-field ()
9040 "Blank the current table field or active region."
9041 (interactive)
9042 (org-table-check-inside-data-field)
9043 (if (and (interactive-p) (org-region-active-p))
9044 (let (org-table-clip)
9045 (org-table-cut-region (region-beginning) (region-end)))
9046 (skip-chars-backward "^|")
9047 (backward-char 1)
9048 (if (looking-at "|[^|\n]+")
9049 (let* ((pos (match-beginning 0))
9050 (match (match-string 0))
9051 (len (org-string-width match)))
9052 (replace-match (concat "|" (make-string (1- len) ?\ )))
9053 (goto-char (+ 2 pos))
9054 (substring match 1)))))
9056 (defun org-table-get-field (&optional n replace)
9057 "Return the value of the field in column N of current row.
9058 N defaults to current field.
9059 If REPLACE is a string, replace field with this value. The return value
9060 is always the old value."
9061 (and n (org-table-goto-column n))
9062 (skip-chars-backward "^|\n")
9063 (backward-char 1)
9064 (if (looking-at "|[^|\r\n]*")
9065 (let* ((pos (match-beginning 0))
9066 (val (buffer-substring (1+ pos) (match-end 0))))
9067 (if replace
9068 (replace-match (concat "|" replace) t t))
9069 (goto-char (min (point-at-eol) (+ 2 pos)))
9070 val)
9071 (forward-char 1) ""))
9073 (defun org-table-field-info (arg)
9074 "Show info about the current field, and highlight any reference at point."
9075 (interactive "P")
9076 (org-table-get-specials)
9077 (save-excursion
9078 (let* ((pos (point))
9079 (col (org-table-current-column))
9080 (cname (car (rassoc (int-to-string col) org-table-column-names)))
9081 (name (car (rassoc (list (org-current-line) col)
9082 org-table-named-field-locations)))
9083 (eql (org-table-get-stored-formulas))
9084 (dline (org-table-current-dline))
9085 (ref (format "@%d$%d" dline col))
9086 (ref1 (org-table-convert-refs-to-an ref))
9087 (fequation (or (assoc name eql) (assoc ref eql)))
9088 (cequation (assoc (int-to-string col) eql))
9089 (eqn (or fequation cequation)))
9090 (goto-char pos)
9091 (condition-case nil
9092 (org-table-show-reference 'local)
9093 (error nil))
9094 (message "line @%d, col $%s%s, ref @%d$%d or %s%s%s"
9095 dline col
9096 (if cname (concat " or $" cname) "")
9097 dline col ref1
9098 (if name (concat " or $" name) "")
9099 ;; FIXME: formula info not correct if special table line
9100 (if eqn
9101 (concat ", formula: "
9102 (org-table-formula-to-user
9103 (concat
9104 (if (string-match "^[$@]"(car eqn)) "" "$")
9105 (car eqn) "=" (cdr eqn))))
9106 "")))))
9108 (defun org-table-current-column ()
9109 "Find out which column we are in.
9110 When called interactively, column is also displayed in echo area."
9111 (interactive)
9112 (if (interactive-p) (org-table-check-inside-data-field))
9113 (save-excursion
9114 (let ((cnt 0) (pos (point)))
9115 (beginning-of-line 1)
9116 (while (search-forward "|" pos t)
9117 (setq cnt (1+ cnt)))
9118 (if (interactive-p) (message "This is table column %d" cnt))
9119 cnt)))
9121 (defun org-table-current-dline ()
9122 "Find out what table data line we are in.
9123 Only datalins count for this."
9124 (interactive)
9125 (if (interactive-p) (org-table-check-inside-data-field))
9126 (save-excursion
9127 (let ((cnt 0) (pos (point)))
9128 (goto-char (org-table-begin))
9129 (while (<= (point) pos)
9130 (if (looking-at org-table-dataline-regexp) (setq cnt (1+ cnt)))
9131 (beginning-of-line 2))
9132 (if (interactive-p) (message "This is table line %d" cnt))
9133 cnt)))
9135 (defun org-table-goto-column (n &optional on-delim force)
9136 "Move the cursor to the Nth column in the current table line.
9137 With optional argument ON-DELIM, stop with point before the left delimiter
9138 of the field.
9139 If there are less than N fields, just go to after the last delimiter.
9140 However, when FORCE is non-nil, create new columns if necessary."
9141 (interactive "p")
9142 (let ((pos (point-at-eol)))
9143 (beginning-of-line 1)
9144 (when (> n 0)
9145 (while (and (> (setq n (1- n)) -1)
9146 (or (search-forward "|" pos t)
9147 (and force
9148 (progn (end-of-line 1)
9149 (skip-chars-backward "^|")
9150 (insert " | "))))))
9151 ; (backward-char 2) t)))))
9152 (when (and force (not (looking-at ".*|")))
9153 (save-excursion (end-of-line 1) (insert " | ")))
9154 (if on-delim
9155 (backward-char 1)
9156 (if (looking-at " ") (forward-char 1))))))
9158 (defun org-at-table-p (&optional table-type)
9159 "Return t if the cursor is inside an org-type table.
9160 If TABLE-TYPE is non-nil, also check for table.el-type tables."
9161 (if org-enable-table-editor
9162 (save-excursion
9163 (beginning-of-line 1)
9164 (looking-at (if table-type org-table-any-line-regexp
9165 org-table-line-regexp)))
9166 nil))
9168 (defun org-at-table.el-p ()
9169 "Return t if and only if we are at a table.el table."
9170 (and (org-at-table-p 'any)
9171 (save-excursion
9172 (goto-char (org-table-begin 'any))
9173 (looking-at org-table1-hline-regexp))))
9175 (defun org-table-recognize-table.el ()
9176 "If there is a table.el table nearby, recognize it and move into it."
9177 (if org-table-tab-recognizes-table.el
9178 (if (org-at-table.el-p)
9179 (progn
9180 (beginning-of-line 1)
9181 (if (looking-at org-table-dataline-regexp)
9183 (if (looking-at org-table1-hline-regexp)
9184 (progn
9185 (beginning-of-line 2)
9186 (if (looking-at org-table-any-border-regexp)
9187 (beginning-of-line -1)))))
9188 (if (re-search-forward "|" (org-table-end t) t)
9189 (progn
9190 (require 'table)
9191 (if (table--at-cell-p (point))
9193 (message "recognizing table.el table...")
9194 (table-recognize-table)
9195 (message "recognizing table.el table...done")))
9196 (error "This should not happen..."))
9198 nil)
9199 nil))
9201 (defun org-at-table-hline-p ()
9202 "Return t if the cursor is inside a hline in a table."
9203 (if org-enable-table-editor
9204 (save-excursion
9205 (beginning-of-line 1)
9206 (looking-at org-table-hline-regexp))
9207 nil))
9209 (defun org-table-insert-column ()
9210 "Insert a new column into the table."
9211 (interactive)
9212 (if (not (org-at-table-p))
9213 (error "Not at a table"))
9214 (org-table-find-dataline)
9215 (let* ((col (max 1 (org-table-current-column)))
9216 (beg (org-table-begin))
9217 (end (org-table-end))
9218 ;; Current cursor position
9219 (linepos (org-current-line))
9220 (colpos col))
9221 (goto-char beg)
9222 (while (< (point) end)
9223 (if (org-at-table-hline-p)
9225 (org-table-goto-column col t)
9226 (insert "| "))
9227 (beginning-of-line 2))
9228 (move-marker end nil)
9229 (goto-line linepos)
9230 (org-table-goto-column colpos)
9231 (org-table-align)
9232 (org-table-fix-formulas "$" nil (1- col) 1)))
9234 (defun org-table-find-dataline ()
9235 "Find a dataline in the current table, which is needed for column commands."
9236 (if (and (org-at-table-p)
9237 (not (org-at-table-hline-p)))
9239 (let ((col (current-column))
9240 (end (org-table-end)))
9241 (move-to-column col)
9242 (while (and (< (point) end)
9243 (or (not (= (current-column) col))
9244 (org-at-table-hline-p)))
9245 (beginning-of-line 2)
9246 (move-to-column col))
9247 (if (and (org-at-table-p)
9248 (not (org-at-table-hline-p)))
9250 (error
9251 "Please position cursor in a data line for column operations")))))
9253 (defun org-table-delete-column ()
9254 "Delete a column from the table."
9255 (interactive)
9256 (if (not (org-at-table-p))
9257 (error "Not at a table"))
9258 (org-table-find-dataline)
9259 (org-table-check-inside-data-field)
9260 (let* ((col (org-table-current-column))
9261 (beg (org-table-begin))
9262 (end (org-table-end))
9263 ;; Current cursor position
9264 (linepos (org-current-line))
9265 (colpos col))
9266 (goto-char beg)
9267 (while (< (point) end)
9268 (if (org-at-table-hline-p)
9270 (org-table-goto-column col t)
9271 (and (looking-at "|[^|\n]+|")
9272 (replace-match "|")))
9273 (beginning-of-line 2))
9274 (move-marker end nil)
9275 (goto-line linepos)
9276 (org-table-goto-column colpos)
9277 (org-table-align)
9278 (org-table-fix-formulas "$" (list (cons (number-to-string col) "INVALID"))
9279 col -1 col)))
9281 (defun org-table-move-column-right ()
9282 "Move column to the right."
9283 (interactive)
9284 (org-table-move-column nil))
9285 (defun org-table-move-column-left ()
9286 "Move column to the left."
9287 (interactive)
9288 (org-table-move-column 'left))
9290 (defun org-table-move-column (&optional left)
9291 "Move the current column to the right. With arg LEFT, move to the left."
9292 (interactive "P")
9293 (if (not (org-at-table-p))
9294 (error "Not at a table"))
9295 (org-table-find-dataline)
9296 (org-table-check-inside-data-field)
9297 (let* ((col (org-table-current-column))
9298 (col1 (if left (1- col) col))
9299 (beg (org-table-begin))
9300 (end (org-table-end))
9301 ;; Current cursor position
9302 (linepos (org-current-line))
9303 (colpos (if left (1- col) (1+ col))))
9304 (if (and left (= col 1))
9305 (error "Cannot move column further left"))
9306 (if (and (not left) (looking-at "[^|\n]*|[^|\n]*$"))
9307 (error "Cannot move column further right"))
9308 (goto-char beg)
9309 (while (< (point) end)
9310 (if (org-at-table-hline-p)
9312 (org-table-goto-column col1 t)
9313 (and (looking-at "|\\([^|\n]+\\)|\\([^|\n]+\\)|")
9314 (replace-match "|\\2|\\1|")))
9315 (beginning-of-line 2))
9316 (move-marker end nil)
9317 (goto-line linepos)
9318 (org-table-goto-column colpos)
9319 (org-table-align)
9320 (org-table-fix-formulas
9321 "$" (list (cons (number-to-string col) (number-to-string colpos))
9322 (cons (number-to-string colpos) (number-to-string col))))))
9324 (defun org-table-move-row-down ()
9325 "Move table row down."
9326 (interactive)
9327 (org-table-move-row nil))
9328 (defun org-table-move-row-up ()
9329 "Move table row up."
9330 (interactive)
9331 (org-table-move-row 'up))
9333 (defun org-table-move-row (&optional up)
9334 "Move the current table line down. With arg UP, move it up."
9335 (interactive "P")
9336 (let* ((col (current-column))
9337 (pos (point))
9338 (hline1p (save-excursion (beginning-of-line 1)
9339 (looking-at org-table-hline-regexp)))
9340 (dline1 (org-table-current-dline))
9341 (dline2 (+ dline1 (if up -1 1)))
9342 (tonew (if up 0 2))
9343 txt hline2p)
9344 (beginning-of-line tonew)
9345 (unless (org-at-table-p)
9346 (goto-char pos)
9347 (error "Cannot move row further"))
9348 (setq hline2p (looking-at org-table-hline-regexp))
9349 (goto-char pos)
9350 (beginning-of-line 1)
9351 (setq pos (point))
9352 (setq txt (buffer-substring (point) (1+ (point-at-eol))))
9353 (delete-region (point) (1+ (point-at-eol)))
9354 (beginning-of-line tonew)
9355 (insert txt)
9356 (beginning-of-line 0)
9357 (move-to-column col)
9358 (unless (or hline1p hline2p)
9359 (org-table-fix-formulas
9360 "@" (list (cons (number-to-string dline1) (number-to-string dline2))
9361 (cons (number-to-string dline2) (number-to-string dline1)))))))
9363 (defun org-table-insert-row (&optional arg)
9364 "Insert a new row above the current line into the table.
9365 With prefix ARG, insert below the current line."
9366 (interactive "P")
9367 (if (not (org-at-table-p))
9368 (error "Not at a table"))
9369 (let* ((line (buffer-substring (point-at-bol) (point-at-eol)))
9370 (new (org-table-clean-line line)))
9371 ;; Fix the first field if necessary
9372 (if (string-match "^[ \t]*| *[#$] *|" line)
9373 (setq new (replace-match (match-string 0 line) t t new)))
9374 (beginning-of-line (if arg 2 1))
9375 (let (org-table-may-need-update) (insert-before-markers new "\n"))
9376 (beginning-of-line 0)
9377 (re-search-forward "| ?" (point-at-eol) t)
9378 (and (or org-table-may-need-update org-table-overlay-coordinates)
9379 (org-table-align))
9380 (org-table-fix-formulas "@" nil (1- (org-table-current-dline)) 1)))
9382 (defun org-table-insert-hline (&optional above)
9383 "Insert a horizontal-line below the current line into the table.
9384 With prefix ABOVE, insert above the current line."
9385 (interactive "P")
9386 (if (not (org-at-table-p))
9387 (error "Not at a table"))
9388 (let ((line (org-table-clean-line
9389 (buffer-substring (point-at-bol) (point-at-eol))))
9390 (col (current-column)))
9391 (while (string-match "|\\( +\\)|" line)
9392 (setq line (replace-match
9393 (concat "+" (make-string (- (match-end 1) (match-beginning 1))
9394 ?-) "|") t t line)))
9395 (and (string-match "\\+" line) (setq line (replace-match "|" t t line)))
9396 (beginning-of-line (if above 1 2))
9397 (insert line "\n")
9398 (beginning-of-line (if above 1 -1))
9399 (move-to-column col)
9400 (and org-table-overlay-coordinates (org-table-align))))
9402 (defun org-table-hline-and-move (&optional same-column)
9403 "Insert a hline and move to the row below that line."
9404 (interactive "P")
9405 (let ((col (org-table-current-column)))
9406 (org-table-maybe-eval-formula)
9407 (org-table-maybe-recalculate-line)
9408 (org-table-insert-hline)
9409 (end-of-line 2)
9410 (if (looking-at "\n[ \t]*|-")
9411 (progn (insert "\n|") (org-table-align))
9412 (org-table-next-field))
9413 (if same-column (org-table-goto-column col))))
9415 (defun org-table-clean-line (s)
9416 "Convert a table line S into a string with only \"|\" and space.
9417 In particular, this does handle wide and invisible characters."
9418 (if (string-match "^[ \t]*|-" s)
9419 ;; It's a hline, just map the characters
9420 (setq s (mapconcat (lambda (x) (if (member x '(?| ?+)) "|" " ")) s ""))
9421 (while (string-match "|\\([ \t]*?[^ \t\r\n|][^\r\n|]*\\)|" s)
9422 (setq s (replace-match
9423 (concat "|" (make-string (org-string-width (match-string 1 s))
9424 ?\ ) "|")
9425 t t s)))
9428 (defun org-table-kill-row ()
9429 "Delete the current row or horizontal line from the table."
9430 (interactive)
9431 (if (not (org-at-table-p))
9432 (error "Not at a table"))
9433 (let ((col (current-column))
9434 (dline (org-table-current-dline)))
9435 (kill-region (point-at-bol) (min (1+ (point-at-eol)) (point-max)))
9436 (if (not (org-at-table-p)) (beginning-of-line 0))
9437 (move-to-column col)
9438 (org-table-fix-formulas "@" (list (cons (number-to-string dline) "INVALID"))
9439 dline -1 dline)))
9441 (defun org-table-sort-lines (with-case &optional sorting-type)
9442 "Sort table lines according to the column at point.
9444 The position of point indicates the column to be used for
9445 sorting, and the range of lines is the range between the nearest
9446 horizontal separator lines, or the entire table of no such lines
9447 exist. If point is before the first column, you will be prompted
9448 for the sorting column. If there is an active region, the mark
9449 specifies the first line and the sorting column, while point
9450 should be in the last line to be included into the sorting.
9452 The command then prompts for the sorting type which can be
9453 alphabetically, numerically, or by time (as given in a time stamp
9454 in the field). Sorting in reverse order is also possible.
9456 With prefix argument WITH-CASE, alphabetic sorting will be case-sensitive.
9458 If SORTING-TYPE is specified when this function is called from a Lisp
9459 program, no prompting will take place. SORTING-TYPE must be a character,
9460 any of (?a ?A ?n ?N ?t ?T) where the capital letter indicate that sorting
9461 should be done in reverse order."
9462 (interactive "P")
9463 (let* ((thisline (org-current-line))
9464 (thiscol (org-table-current-column))
9465 beg end bcol ecol tend tbeg column lns pos)
9466 (when (equal thiscol 0)
9467 (if (interactive-p)
9468 (setq thiscol
9469 (string-to-number
9470 (read-string "Use column N for sorting: ")))
9471 (setq thiscol 1))
9472 (org-table-goto-column thiscol))
9473 (org-table-check-inside-data-field)
9474 (if (org-region-active-p)
9475 (progn
9476 (setq beg (region-beginning) end (region-end))
9477 (goto-char beg)
9478 (setq column (org-table-current-column)
9479 beg (point-at-bol))
9480 (goto-char end)
9481 (setq end (point-at-bol 2)))
9482 (setq column (org-table-current-column)
9483 pos (point)
9484 tbeg (org-table-begin)
9485 tend (org-table-end))
9486 (if (re-search-backward org-table-hline-regexp tbeg t)
9487 (setq beg (point-at-bol 2))
9488 (goto-char tbeg)
9489 (setq beg (point-at-bol 1)))
9490 (goto-char pos)
9491 (if (re-search-forward org-table-hline-regexp tend t)
9492 (setq end (point-at-bol 1))
9493 (goto-char tend)
9494 (setq end (point-at-bol))))
9495 (setq beg (move-marker (make-marker) beg)
9496 end (move-marker (make-marker) end))
9497 (untabify beg end)
9498 (goto-char beg)
9499 (org-table-goto-column column)
9500 (skip-chars-backward "^|")
9501 (setq bcol (current-column))
9502 (org-table-goto-column (1+ column))
9503 (skip-chars-backward "^|")
9504 (setq ecol (1- (current-column)))
9505 (org-table-goto-column column)
9506 (setq lns (mapcar (lambda(x) (cons
9507 (org-sort-remove-invisible
9508 (nth (1- column)
9509 (org-split-string x "[ \t]*|[ \t]*")))
9511 (org-split-string (buffer-substring beg end) "\n")))
9512 (setq lns (org-do-sort lns "Table" with-case sorting-type))
9513 (delete-region beg end)
9514 (move-marker beg nil)
9515 (move-marker end nil)
9516 (insert (mapconcat 'cdr lns "\n") "\n")
9517 (goto-line thisline)
9518 (org-table-goto-column thiscol)
9519 (message "%d lines sorted, based on column %d" (length lns) column)))
9521 ;; FIXME: maybe we will not need this? Table sorting is broken....
9522 (defun org-sort-remove-invisible (s)
9523 (remove-text-properties 0 (length s) org-rm-props s)
9524 (while (string-match org-bracket-link-regexp s)
9525 (setq s (replace-match (if (match-end 2)
9526 (match-string 3 s)
9527 (match-string 1 s)) t t s)))
9530 (defun org-table-cut-region (beg end)
9531 "Copy region in table to the clipboard and blank all relevant fields."
9532 (interactive "r")
9533 (org-table-copy-region beg end 'cut))
9535 (defun org-table-copy-region (beg end &optional cut)
9536 "Copy rectangular region in table to clipboard.
9537 A special clipboard is used which can only be accessed
9538 with `org-table-paste-rectangle'."
9539 (interactive "rP")
9540 (let* (l01 c01 l02 c02 l1 c1 l2 c2 ic1 ic2
9541 region cols
9542 (rpl (if cut " " nil)))
9543 (goto-char beg)
9544 (org-table-check-inside-data-field)
9545 (setq l01 (org-current-line)
9546 c01 (org-table-current-column))
9547 (goto-char end)
9548 (org-table-check-inside-data-field)
9549 (setq l02 (org-current-line)
9550 c02 (org-table-current-column))
9551 (setq l1 (min l01 l02) l2 (max l01 l02)
9552 c1 (min c01 c02) c2 (max c01 c02))
9553 (catch 'exit
9554 (while t
9555 (catch 'nextline
9556 (if (> l1 l2) (throw 'exit t))
9557 (goto-line l1)
9558 (if (org-at-table-hline-p) (throw 'nextline (setq l1 (1+ l1))))
9559 (setq cols nil ic1 c1 ic2 c2)
9560 (while (< ic1 (1+ ic2))
9561 (push (org-table-get-field ic1 rpl) cols)
9562 (setq ic1 (1+ ic1)))
9563 (push (nreverse cols) region)
9564 (setq l1 (1+ l1)))))
9565 (setq org-table-clip (nreverse region))
9566 (if cut (org-table-align))
9567 org-table-clip))
9569 (defun org-table-paste-rectangle ()
9570 "Paste a rectangular region into a table.
9571 The upper right corner ends up in the current field. All involved fields
9572 will be overwritten. If the rectangle does not fit into the present table,
9573 the table is enlarged as needed. The process ignores horizontal separator
9574 lines."
9575 (interactive)
9576 (unless (and org-table-clip (listp org-table-clip))
9577 (error "First cut/copy a region to paste!"))
9578 (org-table-check-inside-data-field)
9579 (let* ((clip org-table-clip)
9580 (line (org-current-line))
9581 (col (org-table-current-column))
9582 (org-enable-table-editor t)
9583 (org-table-automatic-realign nil)
9584 c cols field)
9585 (while (setq cols (pop clip))
9586 (while (org-at-table-hline-p) (beginning-of-line 2))
9587 (if (not (org-at-table-p))
9588 (progn (end-of-line 0) (org-table-next-field)))
9589 (setq c col)
9590 (while (setq field (pop cols))
9591 (org-table-goto-column c nil 'force)
9592 (org-table-get-field nil field)
9593 (setq c (1+ c)))
9594 (beginning-of-line 2))
9595 (goto-line line)
9596 (org-table-goto-column col)
9597 (org-table-align)))
9599 (defun org-table-convert ()
9600 "Convert from `org-mode' table to table.el and back.
9601 Obviously, this only works within limits. When an Org-mode table is
9602 converted to table.el, all horizontal separator lines get lost, because
9603 table.el uses these as cell boundaries and has no notion of horizontal lines.
9604 A table.el table can be converted to an Org-mode table only if it does not
9605 do row or column spanning. Multiline cells will become multiple cells.
9606 Beware, Org-mode does not test if the table can be successfully converted - it
9607 blindly applies a recipe that works for simple tables."
9608 (interactive)
9609 (require 'table)
9610 (if (org-at-table.el-p)
9611 ;; convert to Org-mode table
9612 (let ((beg (move-marker (make-marker) (org-table-begin t)))
9613 (end (move-marker (make-marker) (org-table-end t))))
9614 (table-unrecognize-region beg end)
9615 (goto-char beg)
9616 (while (re-search-forward "^\\([ \t]*\\)\\+-.*\n" end t)
9617 (replace-match ""))
9618 (goto-char beg))
9619 (if (org-at-table-p)
9620 ;; convert to table.el table
9621 (let ((beg (move-marker (make-marker) (org-table-begin)))
9622 (end (move-marker (make-marker) (org-table-end))))
9623 ;; first, get rid of all horizontal lines
9624 (goto-char beg)
9625 (while (re-search-forward "^\\([ \t]*\\)|-.*\n" end t)
9626 (replace-match ""))
9627 ;; insert a hline before first
9628 (goto-char beg)
9629 (org-table-insert-hline 'above)
9630 (beginning-of-line -1)
9631 ;; insert a hline after each line
9632 (while (progn (beginning-of-line 3) (< (point) end))
9633 (org-table-insert-hline))
9634 (goto-char beg)
9635 (setq end (move-marker end (org-table-end)))
9636 ;; replace "+" at beginning and ending of hlines
9637 (while (re-search-forward "^\\([ \t]*\\)|-" end t)
9638 (replace-match "\\1+-"))
9639 (goto-char beg)
9640 (while (re-search-forward "-|[ \t]*$" end t)
9641 (replace-match "-+"))
9642 (goto-char beg)))))
9644 (defun org-table-wrap-region (arg)
9645 "Wrap several fields in a column like a paragraph.
9646 This is useful if you'd like to spread the contents of a field over several
9647 lines, in order to keep the table compact.
9649 If there is an active region, and both point and mark are in the same column,
9650 the text in the column is wrapped to minimum width for the given number of
9651 lines. Generally, this makes the table more compact. A prefix ARG may be
9652 used to change the number of desired lines. For example, `C-2 \\[org-table-wrap]'
9653 formats the selected text to two lines. If the region was longer than two
9654 lines, the remaining lines remain empty. A negative prefix argument reduces
9655 the current number of lines by that amount. The wrapped text is pasted back
9656 into the table. If you formatted it to more lines than it was before, fields
9657 further down in the table get overwritten - so you might need to make space in
9658 the table first.
9660 If there is no region, the current field is split at the cursor position and
9661 the text fragment to the right of the cursor is prepended to the field one
9662 line down.
9664 If there is no region, but you specify a prefix ARG, the current field gets
9665 blank, and the content is appended to the field above."
9666 (interactive "P")
9667 (org-table-check-inside-data-field)
9668 (if (org-region-active-p)
9669 ;; There is a region: fill as a paragraph
9670 (let* ((beg (region-beginning))
9671 (cline (save-excursion (goto-char beg) (org-current-line)))
9672 (ccol (save-excursion (goto-char beg) (org-table-current-column)))
9673 nlines)
9674 (org-table-cut-region (region-beginning) (region-end))
9675 (if (> (length (car org-table-clip)) 1)
9676 (error "Region must be limited to single column"))
9677 (setq nlines (if arg
9678 (if (< arg 1)
9679 (+ (length org-table-clip) arg)
9680 arg)
9681 (length org-table-clip)))
9682 (setq org-table-clip
9683 (mapcar 'list (org-wrap (mapconcat 'car org-table-clip " ")
9684 nil nlines)))
9685 (goto-line cline)
9686 (org-table-goto-column ccol)
9687 (org-table-paste-rectangle))
9688 ;; No region, split the current field at point
9689 (unless (org-get-alist-option org-M-RET-may-split-line 'table)
9690 (skip-chars-forward "^\r\n|"))
9691 (if arg
9692 ;; combine with field above
9693 (let ((s (org-table-blank-field))
9694 (col (org-table-current-column)))
9695 (beginning-of-line 0)
9696 (while (org-at-table-hline-p) (beginning-of-line 0))
9697 (org-table-goto-column col)
9698 (skip-chars-forward "^|")
9699 (skip-chars-backward " ")
9700 (insert " " (org-trim s))
9701 (org-table-align))
9702 ;; split field
9703 (if (looking-at "\\([^|]+\\)+|")
9704 (let ((s (match-string 1)))
9705 (replace-match " |")
9706 (goto-char (match-beginning 0))
9707 (org-table-next-row)
9708 (insert (org-trim s) " ")
9709 (org-table-align))
9710 (org-table-next-row)))))
9712 (defvar org-field-marker nil)
9714 (defun org-table-edit-field (arg)
9715 "Edit table field in a different window.
9716 This is mainly useful for fields that contain hidden parts.
9717 When called with a \\[universal-argument] prefix, just make the full field visible so that
9718 it can be edited in place."
9719 (interactive "P")
9720 (if arg
9721 (let ((b (save-excursion (skip-chars-backward "^|") (point)))
9722 (e (save-excursion (skip-chars-forward "^|\r\n") (point))))
9723 (remove-text-properties b e '(org-cwidth t invisible t
9724 display t intangible t))
9725 (if (and (boundp 'font-lock-mode) font-lock-mode)
9726 (font-lock-fontify-block)))
9727 (let ((pos (move-marker (make-marker) (point)))
9728 (field (org-table-get-field))
9729 (cw (current-window-configuration))
9731 (org-switch-to-buffer-other-window "*Org tmp*")
9732 (erase-buffer)
9733 (insert "#\n# Edit field and finish with C-c C-c\n#\n")
9734 (let ((org-inhibit-startup t)) (org-mode))
9735 (goto-char (setq p (point-max)))
9736 (insert (org-trim field))
9737 (remove-text-properties p (point-max)
9738 '(invisible t org-cwidth t display t
9739 intangible t))
9740 (goto-char p)
9741 (org-set-local 'org-finish-function 'org-table-finish-edit-field)
9742 (org-set-local 'org-window-configuration cw)
9743 (org-set-local 'org-field-marker pos)
9744 (message "Edit and finish with C-c C-c"))))
9746 (defun org-table-finish-edit-field ()
9747 "Finish editing a table data field.
9748 Remove all newline characters, insert the result into the table, realign
9749 the table and kill the editing buffer."
9750 (let ((pos org-field-marker)
9751 (cw org-window-configuration)
9752 (cb (current-buffer))
9753 text)
9754 (goto-char (point-min))
9755 (while (re-search-forward "^#.*\n?" nil t) (replace-match ""))
9756 (while (re-search-forward "\\([ \t]*\n[ \t]*\\)+" nil t)
9757 (replace-match " "))
9758 (setq text (org-trim (buffer-string)))
9759 (set-window-configuration cw)
9760 (kill-buffer cb)
9761 (select-window (get-buffer-window (marker-buffer pos)))
9762 (goto-char pos)
9763 (move-marker pos nil)
9764 (org-table-check-inside-data-field)
9765 (org-table-get-field nil text)
9766 (org-table-align)
9767 (message "New field value inserted")))
9769 (defun org-trim (s)
9770 "Remove whitespace at beginning and end of string."
9771 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
9772 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
9775 (defun org-wrap (string &optional width lines)
9776 "Wrap string to either a number of lines, or a width in characters.
9777 If WIDTH is non-nil, the string is wrapped to that width, however many lines
9778 that costs. If there is a word longer than WIDTH, the text is actually
9779 wrapped to the length of that word.
9780 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
9781 many lines, whatever width that takes.
9782 The return value is a list of lines, without newlines at the end."
9783 (let* ((words (org-split-string string "[ \t\n]+"))
9784 (maxword (apply 'max (mapcar 'org-string-width words)))
9785 w ll)
9786 (cond (width
9787 (org-do-wrap words (max maxword width)))
9788 (lines
9789 (setq w maxword)
9790 (setq ll (org-do-wrap words maxword))
9791 (if (<= (length ll) lines)
9793 (setq ll words)
9794 (while (> (length ll) lines)
9795 (setq w (1+ w))
9796 (setq ll (org-do-wrap words w)))
9797 ll))
9798 (t (error "Cannot wrap this")))))
9801 (defun org-do-wrap (words width)
9802 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
9803 (let (lines line)
9804 (while words
9805 (setq line (pop words))
9806 (while (and words (< (+ (length line) (length (car words))) width))
9807 (setq line (concat line " " (pop words))))
9808 (setq lines (push line lines)))
9809 (nreverse lines)))
9811 (defun org-split-string (string &optional separators)
9812 "Splits STRING into substrings at SEPARATORS.
9813 No empty strings are returned if there are matches at the beginning
9814 and end of string."
9815 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
9816 (start 0)
9817 notfirst
9818 (list nil))
9819 (while (and (string-match rexp string
9820 (if (and notfirst
9821 (= start (match-beginning 0))
9822 (< start (length string)))
9823 (1+ start) start))
9824 (< (match-beginning 0) (length string)))
9825 (setq notfirst t)
9826 (or (eq (match-beginning 0) 0)
9827 (and (eq (match-beginning 0) (match-end 0))
9828 (eq (match-beginning 0) start))
9829 (setq list
9830 (cons (substring string start (match-beginning 0))
9831 list)))
9832 (setq start (match-end 0)))
9833 (or (eq start (length string))
9834 (setq list
9835 (cons (substring string start)
9836 list)))
9837 (nreverse list)))
9839 (defun org-table-map-tables (function)
9840 "Apply FUNCTION to the start of all tables in the buffer."
9841 (save-excursion
9842 (save-restriction
9843 (widen)
9844 (goto-char (point-min))
9845 (while (re-search-forward org-table-any-line-regexp nil t)
9846 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
9847 (beginning-of-line 1)
9848 (if (looking-at org-table-line-regexp)
9849 (save-excursion (funcall function)))
9850 (re-search-forward org-table-any-border-regexp nil 1))))
9851 (message "Mapping tables: done"))
9853 (defvar org-timecnt) ; dynamically scoped parameter
9855 (defun org-table-sum (&optional beg end nlast)
9856 "Sum numbers in region of current table column.
9857 The result will be displayed in the echo area, and will be available
9858 as kill to be inserted with \\[yank].
9860 If there is an active region, it is interpreted as a rectangle and all
9861 numbers in that rectangle will be summed. If there is no active
9862 region and point is located in a table column, sum all numbers in that
9863 column.
9865 If at least one number looks like a time HH:MM or HH:MM:SS, all other
9866 numbers are assumed to be times as well (in decimal hours) and the
9867 numbers are added as such.
9869 If NLAST is a number, only the NLAST fields will actually be summed."
9870 (interactive)
9871 (save-excursion
9872 (let (col (org-timecnt 0) diff h m s org-table-clip)
9873 (cond
9874 ((and beg end)) ; beg and end given explicitly
9875 ((org-region-active-p)
9876 (setq beg (region-beginning) end (region-end)))
9878 (setq col (org-table-current-column))
9879 (goto-char (org-table-begin))
9880 (unless (re-search-forward "^[ \t]*|[^-]" nil t)
9881 (error "No table data"))
9882 (org-table-goto-column col)
9883 (setq beg (point))
9884 (goto-char (org-table-end))
9885 (unless (re-search-backward "^[ \t]*|[^-]" nil t)
9886 (error "No table data"))
9887 (org-table-goto-column col)
9888 (setq end (point))))
9889 (let* ((items (apply 'append (org-table-copy-region beg end)))
9890 (items1 (cond ((not nlast) items)
9891 ((>= nlast (length items)) items)
9892 (t (setq items (reverse items))
9893 (setcdr (nthcdr (1- nlast) items) nil)
9894 (nreverse items))))
9895 (numbers (delq nil (mapcar 'org-table-get-number-for-summing
9896 items1)))
9897 (res (apply '+ numbers))
9898 (sres (if (= org-timecnt 0)
9899 (format "%g" res)
9900 (setq diff (* 3600 res)
9901 h (floor (/ diff 3600)) diff (mod diff 3600)
9902 m (floor (/ diff 60)) diff (mod diff 60)
9903 s diff)
9904 (format "%d:%02d:%02d" h m s))))
9905 (kill-new sres)
9906 (if (interactive-p)
9907 (message "%s"
9908 (substitute-command-keys
9909 (format "Sum of %d items: %-20s (\\[yank] will insert result into buffer)"
9910 (length numbers) sres))))
9911 sres))))
9913 (defun org-table-get-number-for-summing (s)
9914 (let (n)
9915 (if (string-match "^ *|? *" s)
9916 (setq s (replace-match "" nil nil s)))
9917 (if (string-match " *|? *$" s)
9918 (setq s (replace-match "" nil nil s)))
9919 (setq n (string-to-number s))
9920 (cond
9921 ((and (string-match "0" s)
9922 (string-match "\\`[-+ \t0.edED]+\\'" s)) 0)
9923 ((string-match "\\`[ \t]+\\'" s) nil)
9924 ((string-match "\\`\\([0-9]+\\):\\([0-9]+\\)\\(:\\([0-9]+\\)\\)?\\'" s)
9925 (let ((h (string-to-number (or (match-string 1 s) "0")))
9926 (m (string-to-number (or (match-string 2 s) "0")))
9927 (s (string-to-number (or (match-string 4 s) "0"))))
9928 (if (boundp 'org-timecnt) (setq org-timecnt (1+ org-timecnt)))
9929 (* 1.0 (+ h (/ m 60.0) (/ s 3600.0)))))
9930 ((equal n 0) nil)
9931 (t n))))
9933 (defun org-table-current-field-formula (&optional key noerror)
9934 "Return the formula active for the current field.
9935 Assumes that specials are in place.
9936 If KEY is given, return the key to this formula.
9937 Otherwise return the formula preceeded with \"=\" or \":=\"."
9938 (let* ((name (car (rassoc (list (org-current-line)
9939 (org-table-current-column))
9940 org-table-named-field-locations)))
9941 (col (org-table-current-column))
9942 (scol (int-to-string col))
9943 (ref (format "@%d$%d" (org-table-current-dline) col))
9944 (stored-list (org-table-get-stored-formulas noerror))
9945 (ass (or (assoc name stored-list)
9946 (assoc ref stored-list)
9947 (assoc scol stored-list))))
9948 (if key
9949 (car ass)
9950 (if ass (concat (if (string-match "^[0-9]+$" (car ass)) "=" ":=")
9951 (cdr ass))))))
9953 (defun org-table-get-formula (&optional equation named)
9954 "Read a formula from the minibuffer, offer stored formula as default.
9955 When NAMED is non-nil, look for a named equation."
9956 (let* ((stored-list (org-table-get-stored-formulas))
9957 (name (car (rassoc (list (org-current-line)
9958 (org-table-current-column))
9959 org-table-named-field-locations)))
9960 (ref (format "@%d$%d" (org-table-current-dline)
9961 (org-table-current-column)))
9962 (refass (assoc ref stored-list))
9963 (scol (if named
9964 (if name name ref)
9965 (int-to-string (org-table-current-column))))
9966 (dummy (and (or name refass) (not named)
9967 (not (y-or-n-p "Replace field formula with column formula? " ))
9968 (error "Abort")))
9969 (name (or name ref))
9970 (org-table-may-need-update nil)
9971 (stored (cdr (assoc scol stored-list)))
9972 (eq (cond
9973 ((and stored equation (string-match "^ *=? *$" equation))
9974 stored)
9975 ((stringp equation)
9976 equation)
9977 (t (org-table-formula-from-user
9978 (read-string
9979 (org-table-formula-to-user
9980 (format "%s formula %s%s="
9981 (if named "Field" "Column")
9982 (if (member (string-to-char scol) '(?$ ?@)) "" "$")
9983 scol))
9984 (if stored (org-table-formula-to-user stored) "")
9985 'org-table-formula-history
9986 )))))
9987 mustsave)
9988 (when (not (string-match "\\S-" eq))
9989 ;; remove formula
9990 (setq stored-list (delq (assoc scol stored-list) stored-list))
9991 (org-table-store-formulas stored-list)
9992 (error "Formula removed"))
9993 (if (string-match "^ *=?" eq) (setq eq (replace-match "" t t eq)))
9994 (if (string-match " *$" eq) (setq eq (replace-match "" t t eq)))
9995 (if (and name (not named))
9996 ;; We set the column equation, delete the named one.
9997 (setq stored-list (delq (assoc name stored-list) stored-list)
9998 mustsave t))
9999 (if stored
10000 (setcdr (assoc scol stored-list) eq)
10001 (setq stored-list (cons (cons scol eq) stored-list)))
10002 (if (or mustsave (not (equal stored eq)))
10003 (org-table-store-formulas stored-list))
10004 eq))
10006 (defun org-table-store-formulas (alist)
10007 "Store the list of formulas below the current table."
10008 (setq alist (sort alist 'org-table-formula-less-p))
10009 (save-excursion
10010 (goto-char (org-table-end))
10011 (if (looking-at "\\([ \t]*\n\\)*#\\+TBLFM:\\(.*\n?\\)")
10012 (progn
10013 ;; don't overwrite TBLFM, we might use text properties to store stuff
10014 (goto-char (match-beginning 2))
10015 (delete-region (match-beginning 2) (match-end 0)))
10016 (insert "#+TBLFM:"))
10017 (insert " "
10018 (mapconcat (lambda (x)
10019 (concat
10020 (if (equal (string-to-char (car x)) ?@) "" "$")
10021 (car x) "=" (cdr x)))
10022 alist "::")
10023 "\n")))
10025 (defsubst org-table-formula-make-cmp-string (a)
10026 (when (string-match "^\\(@\\([0-9]+\\)\\)?\\(\\$?\\([0-9]+\\)\\)?\\(\\$?[a-zA-Z0-9]+\\)?" a)
10027 (concat
10028 (if (match-end 2) (format "@%05d" (string-to-number (match-string 2 a))) "")
10029 (if (match-end 4) (format "$%05d" (string-to-number (match-string 4 a))) "")
10030 (if (match-end 5) (concat "@@" (match-string 5 a))))))
10032 (defun org-table-formula-less-p (a b)
10033 "Compare two formulas for sorting."
10034 (let ((as (org-table-formula-make-cmp-string (car a)))
10035 (bs (org-table-formula-make-cmp-string (car b))))
10036 (and as bs (string< as bs))))
10038 (defun org-table-get-stored-formulas (&optional noerror)
10039 "Return an alist with the stored formulas directly after current table."
10040 (interactive)
10041 (let (scol eq eq-alist strings string seen)
10042 (save-excursion
10043 (goto-char (org-table-end))
10044 (when (looking-at "\\([ \t]*\n\\)*#\\+TBLFM: *\\(.*\\)")
10045 (setq strings (org-split-string (match-string 2) " *:: *"))
10046 (while (setq string (pop strings))
10047 (when (string-match "\\(@[0-9]+\\$[0-9]+\\|\\$\\([a-zA-Z0-9]+\\)\\) *= *\\(.*[^ \t]\\)" string)
10048 (setq scol (if (match-end 2)
10049 (match-string 2 string)
10050 (match-string 1 string))
10051 eq (match-string 3 string)
10052 eq-alist (cons (cons scol eq) eq-alist))
10053 (if (member scol seen)
10054 (if noerror
10055 (progn
10056 (message "Double definition `$%s=' in TBLFM line, please fix by hand" scol)
10057 (ding)
10058 (sit-for 2))
10059 (error "Double definition `$%s=' in TBLFM line, please fix by hand" scol))
10060 (push scol seen))))))
10061 (nreverse eq-alist)))
10063 (defun org-table-fix-formulas (key replace &optional limit delta remove)
10064 "Modify the equations after the table structure has been edited.
10065 KEY is \"@\" or \"$\". REPLACE is an alist of numbers to replace.
10066 For all numbers larger than LIMIT, shift them by DELTA."
10067 (save-excursion
10068 (goto-char (org-table-end))
10069 (when (looking-at "#\\+TBLFM:")
10070 (let ((re (concat key "\\([0-9]+\\)"))
10071 (re2
10072 (when remove
10073 (if (equal key "$")
10074 (format "\\(@[0-9]+\\)?\\$%d=.*?\\(::\\|$\\)" remove)
10075 (format "@%d\\$[0-9]+=.*?\\(::\\|$\\)" remove))))
10076 s n a)
10077 (when remove
10078 (while (re-search-forward re2 (point-at-eol) t)
10079 (replace-match "")))
10080 (while (re-search-forward re (point-at-eol) t)
10081 (setq s (match-string 1) n (string-to-number s))
10082 (cond
10083 ((setq a (assoc s replace))
10084 (replace-match (concat key (cdr a)) t t))
10085 ((and limit (> n limit))
10086 (replace-match (concat key (int-to-string (+ n delta))) t t))))))))
10088 (defun org-table-get-specials ()
10089 "Get the column names and local parameters for this table."
10090 (save-excursion
10091 (let ((beg (org-table-begin)) (end (org-table-end))
10092 names name fields fields1 field cnt
10093 c v l line col types dlines hlines)
10094 (setq org-table-column-names nil
10095 org-table-local-parameters nil
10096 org-table-named-field-locations nil
10097 org-table-current-begin-line nil
10098 org-table-current-begin-pos nil
10099 org-table-current-line-types nil)
10100 (goto-char beg)
10101 (when (re-search-forward "^[ \t]*| *! *\\(|.*\\)" end t)
10102 (setq names (org-split-string (match-string 1) " *| *")
10103 cnt 1)
10104 (while (setq name (pop names))
10105 (setq cnt (1+ cnt))
10106 (if (string-match "^[a-zA-Z][a-zA-Z0-9]*$" name)
10107 (push (cons name (int-to-string cnt)) org-table-column-names))))
10108 (setq org-table-column-names (nreverse org-table-column-names))
10109 (setq org-table-column-name-regexp
10110 (concat "\\$\\(" (mapconcat 'car org-table-column-names "\\|") "\\)\\>"))
10111 (goto-char beg)
10112 (while (re-search-forward "^[ \t]*| *\\$ *\\(|.*\\)" end t)
10113 (setq fields (org-split-string (match-string 1) " *| *"))
10114 (while (setq field (pop fields))
10115 (if (string-match "^\\([a-zA-Z][_a-zA-Z0-9]*\\|%\\) *= *\\(.*\\)" field)
10116 (push (cons (match-string 1 field) (match-string 2 field))
10117 org-table-local-parameters))))
10118 (goto-char beg)
10119 (while (re-search-forward "^[ \t]*| *\\([_^]\\) *\\(|.*\\)" end t)
10120 (setq c (match-string 1)
10121 fields (org-split-string (match-string 2) " *| *"))
10122 (save-excursion
10123 (beginning-of-line (if (equal c "_") 2 0))
10124 (setq line (org-current-line) col 1)
10125 (and (looking-at "^[ \t]*|[^|]*\\(|.*\\)")
10126 (setq fields1 (org-split-string (match-string 1) " *| *"))))
10127 (while (and fields1 (setq field (pop fields)))
10128 (setq v (pop fields1) col (1+ col))
10129 (when (and (stringp field) (stringp v)
10130 (string-match "^[a-zA-Z][a-zA-Z0-9]*$" field))
10131 (push (cons field v) org-table-local-parameters)
10132 (push (list field line col) org-table-named-field-locations))))
10133 ;; Analyse the line types
10134 (goto-char beg)
10135 (setq org-table-current-begin-line (org-current-line)
10136 org-table-current-begin-pos (point)
10137 l org-table-current-begin-line)
10138 (while (looking-at "[ \t]*|\\(-\\)?")
10139 (push (if (match-end 1) 'hline 'dline) types)
10140 (if (match-end 1) (push l hlines) (push l dlines))
10141 (beginning-of-line 2)
10142 (setq l (1+ l)))
10143 (setq org-table-current-line-types (apply 'vector (nreverse types))
10144 org-table-dlines (apply 'vector (cons nil (nreverse dlines)))
10145 org-table-hlines (apply 'vector (cons nil (nreverse hlines)))))))
10147 (defun org-table-maybe-eval-formula ()
10148 "Check if the current field starts with \"=\" or \":=\".
10149 If yes, store the formula and apply it."
10150 ;; We already know we are in a table. Get field will only return a formula
10151 ;; when appropriate. It might return a separator line, but no problem.
10152 (when org-table-formula-evaluate-inline
10153 (let* ((field (org-trim (or (org-table-get-field) "")))
10154 named eq)
10155 (when (string-match "^:?=\\(.*\\)" field)
10156 (setq named (equal (string-to-char field) ?:)
10157 eq (match-string 1 field))
10158 (if (or (fboundp 'calc-eval)
10159 (equal (substring eq 0 (min 2 (length eq))) "'("))
10160 (org-table-eval-formula (if named '(4) nil)
10161 (org-table-formula-from-user eq))
10162 (error "Calc does not seem to be installed, and is needed to evaluate the formula"))))))
10164 (defvar org-recalc-commands nil
10165 "List of commands triggering the recalculation of a line.
10166 Will be filled automatically during use.")
10168 (defvar org-recalc-marks
10169 '((" " . "Unmarked: no special line, no automatic recalculation")
10170 ("#" . "Automatically recalculate this line upon TAB, RET, and C-c C-c in the line")
10171 ("*" . "Recalculate only when entire table is recalculated with `C-u C-c *'")
10172 ("!" . "Column name definition line. Reference in formula as $name.")
10173 ("$" . "Parameter definition line name=value. Reference in formula as $name.")
10174 ("_" . "Names for values in row below this one.")
10175 ("^" . "Names for values in row above this one.")))
10177 (defun org-table-rotate-recalc-marks (&optional newchar)
10178 "Rotate the recalculation mark in the first column.
10179 If in any row, the first field is not consistent with a mark,
10180 insert a new column for the markers.
10181 When there is an active region, change all the lines in the region,
10182 after prompting for the marking character.
10183 After each change, a message will be displayed indicating the meaning
10184 of the new mark."
10185 (interactive)
10186 (unless (org-at-table-p) (error "Not at a table"))
10187 (let* ((marks (append (mapcar 'car org-recalc-marks) '(" ")))
10188 (beg (org-table-begin))
10189 (end (org-table-end))
10190 (l (org-current-line))
10191 (l1 (if (org-region-active-p) (org-current-line (region-beginning))))
10192 (l2 (if (org-region-active-p) (org-current-line (region-end))))
10193 (have-col
10194 (save-excursion
10195 (goto-char beg)
10196 (not (re-search-forward "^[ \t]*|[^-|][^|]*[^#!$*_^| \t][^|]*|" end t))))
10197 (col (org-table-current-column))
10198 (forcenew (car (assoc newchar org-recalc-marks)))
10199 epos new)
10200 (when l1
10201 (message "Change region to what mark? Type # * ! $ or SPC: ")
10202 (setq newchar (char-to-string (read-char-exclusive))
10203 forcenew (car (assoc newchar org-recalc-marks))))
10204 (if (and newchar (not forcenew))
10205 (error "Invalid NEWCHAR `%s' in `org-table-rotate-recalc-marks'"
10206 newchar))
10207 (if l1 (goto-line l1))
10208 (save-excursion
10209 (beginning-of-line 1)
10210 (unless (looking-at org-table-dataline-regexp)
10211 (error "Not at a table data line")))
10212 (unless have-col
10213 (org-table-goto-column 1)
10214 (org-table-insert-column)
10215 (org-table-goto-column (1+ col)))
10216 (setq epos (point-at-eol))
10217 (save-excursion
10218 (beginning-of-line 1)
10219 (org-table-get-field
10220 1 (if (looking-at "^[ \t]*| *\\([#!$*^_ ]\\) *|")
10221 (concat " "
10222 (setq new (or forcenew
10223 (cadr (member (match-string 1) marks))))
10224 " ")
10225 " # ")))
10226 (if (and l1 l2)
10227 (progn
10228 (goto-line l1)
10229 (while (progn (beginning-of-line 2) (not (= (org-current-line) l2)))
10230 (and (looking-at org-table-dataline-regexp)
10231 (org-table-get-field 1 (concat " " new " "))))
10232 (goto-line l1)))
10233 (if (not (= epos (point-at-eol))) (org-table-align))
10234 (goto-line l)
10235 (and (interactive-p) (message "%s" (cdr (assoc new org-recalc-marks))))))
10237 (defun org-table-maybe-recalculate-line ()
10238 "Recompute the current line if marked for it, and if we haven't just done it."
10239 (interactive)
10240 (and org-table-allow-automatic-line-recalculation
10241 (not (and (memq last-command org-recalc-commands)
10242 (equal org-last-recalc-line (org-current-line))))
10243 (save-excursion (beginning-of-line 1)
10244 (looking-at org-table-auto-recalculate-regexp))
10245 (org-table-recalculate) t))
10247 (defvar org-table-formula-debug nil
10248 "Non-nil means, debug table formulas.
10249 When nil, simply write \"#ERROR\" in corrupted fields.")
10250 (make-variable-buffer-local 'org-table-formula-debug)
10252 (defvar modes)
10253 (defsubst org-set-calc-mode (var &optional value)
10254 (if (stringp var)
10255 (setq var (assoc var '(("D" calc-angle-mode deg)
10256 ("R" calc-angle-mode rad)
10257 ("F" calc-prefer-frac t)
10258 ("S" calc-symbolic-mode t)))
10259 value (nth 2 var) var (nth 1 var)))
10260 (if (memq var modes)
10261 (setcar (cdr (memq var modes)) value)
10262 (cons var (cons value modes)))
10263 modes)
10265 (defun org-table-eval-formula (&optional arg equation
10266 suppress-align suppress-const
10267 suppress-store suppress-analysis)
10268 "Replace the table field value at the cursor by the result of a calculation.
10270 This function makes use of Dave Gillespie's Calc package, in my view the
10271 most exciting program ever written for GNU Emacs. So you need to have Calc
10272 installed in order to use this function.
10274 In a table, this command replaces the value in the current field with the
10275 result of a formula. It also installs the formula as the \"current\" column
10276 formula, by storing it in a special line below the table. When called
10277 with a `C-u' prefix, the current field must ba a named field, and the
10278 formula is installed as valid in only this specific field.
10280 When called with two `C-u' prefixes, insert the active equation
10281 for the field back into the current field, so that it can be
10282 edited there. This is useful in order to use \\[org-table-show-reference]
10283 to check the referenced fields.
10285 When called, the command first prompts for a formula, which is read in
10286 the minibuffer. Previously entered formulas are available through the
10287 history list, and the last used formula is offered as a default.
10288 These stored formulas are adapted correctly when moving, inserting, or
10289 deleting columns with the corresponding commands.
10291 The formula can be any algebraic expression understood by the Calc package.
10292 For details, see the Org-mode manual.
10294 This function can also be called from Lisp programs and offers
10295 additional arguments: EQUATION can be the formula to apply. If this
10296 argument is given, the user will not be prompted. SUPPRESS-ALIGN is
10297 used to speed-up recursive calls by by-passing unnecessary aligns.
10298 SUPPRESS-CONST suppresses the interpretation of constants in the
10299 formula, assuming that this has been done already outside the function.
10300 SUPPRESS-STORE means the formula should not be stored, either because
10301 it is already stored, or because it is a modified equation that should
10302 not overwrite the stored one."
10303 (interactive "P")
10304 (org-table-check-inside-data-field)
10305 (or suppress-analysis (org-table-get-specials))
10306 (if (equal arg '(16))
10307 (let ((eq (org-table-current-field-formula)))
10308 (or eq (error "No equation active for current field"))
10309 (org-table-get-field nil eq)
10310 (org-table-align)
10311 (setq org-table-may-need-update t))
10312 (let* (fields
10313 (ndown (if (integerp arg) arg 1))
10314 (org-table-automatic-realign nil)
10315 (case-fold-search nil)
10316 (down (> ndown 1))
10317 (formula (if (and equation suppress-store)
10318 equation
10319 (org-table-get-formula equation (equal arg '(4)))))
10320 (n0 (org-table-current-column))
10321 (modes (copy-sequence org-calc-default-modes))
10322 (numbers nil) ; was a variable, now fixed default
10323 (keep-empty nil)
10324 n form form0 bw fmt x ev orig c lispp literal)
10325 ;; Parse the format string. Since we have a lot of modes, this is
10326 ;; a lot of work. However, I think calc still uses most of the time.
10327 (if (string-match ";" formula)
10328 (let ((tmp (org-split-string formula ";")))
10329 (setq formula (car tmp)
10330 fmt (concat (cdr (assoc "%" org-table-local-parameters))
10331 (nth 1 tmp)))
10332 (while (string-match "\\([pnfse]\\)\\(-?[0-9]+\\)" fmt)
10333 (setq c (string-to-char (match-string 1 fmt))
10334 n (string-to-number (match-string 2 fmt)))
10335 (if (= c ?p)
10336 (setq modes (org-set-calc-mode 'calc-internal-prec n))
10337 (setq modes (org-set-calc-mode
10338 'calc-float-format
10339 (list (cdr (assoc c '((?n . float) (?f . fix)
10340 (?s . sci) (?e . eng))))
10341 n))))
10342 (setq fmt (replace-match "" t t fmt)))
10343 (if (string-match "[NT]" fmt)
10344 (setq numbers (equal (match-string 0 fmt) "N")
10345 fmt (replace-match "" t t fmt)))
10346 (if (string-match "L" fmt)
10347 (setq literal t
10348 fmt (replace-match "" t t fmt)))
10349 (if (string-match "E" fmt)
10350 (setq keep-empty t
10351 fmt (replace-match "" t t fmt)))
10352 (while (string-match "[DRFS]" fmt)
10353 (setq modes (org-set-calc-mode (match-string 0 fmt)))
10354 (setq fmt (replace-match "" t t fmt)))
10355 (unless (string-match "\\S-" fmt)
10356 (setq fmt nil))))
10357 (if (and (not suppress-const) org-table-formula-use-constants)
10358 (setq formula (org-table-formula-substitute-names formula)))
10359 (setq orig (or (get-text-property 1 :orig-formula formula) "?"))
10360 (while (> ndown 0)
10361 (setq fields (org-split-string
10362 (org-no-properties
10363 (buffer-substring (point-at-bol) (point-at-eol)))
10364 " *| *"))
10365 (if (eq numbers t)
10366 (setq fields (mapcar
10367 (lambda (x) (number-to-string (string-to-number x)))
10368 fields)))
10369 (setq ndown (1- ndown))
10370 (setq form (copy-sequence formula)
10371 lispp (and (> (length form) 2)(equal (substring form 0 2) "'(")))
10372 (if (and lispp literal) (setq lispp 'literal))
10373 ;; Check for old vertical references
10374 (setq form (org-rewrite-old-row-references form))
10375 ;; Insert complex ranges
10376 (while (string-match org-table-range-regexp form)
10377 (setq form
10378 (replace-match
10379 (save-match-data
10380 (org-table-make-reference
10381 (org-table-get-range (match-string 0 form) nil n0)
10382 keep-empty numbers lispp))
10383 t t form)))
10384 ;; Insert simple ranges
10385 (while (string-match "\\$\\([0-9]+\\)\\.\\.\\$\\([0-9]+\\)" form)
10386 (setq form
10387 (replace-match
10388 (save-match-data
10389 (org-table-make-reference
10390 (org-sublist
10391 fields (string-to-number (match-string 1 form))
10392 (string-to-number (match-string 2 form)))
10393 keep-empty numbers lispp))
10394 t t form)))
10395 (setq form0 form)
10396 ;; Insert the references to fields in same row
10397 (while (string-match "\\$\\([0-9]+\\)" form)
10398 (setq n (string-to-number (match-string 1 form))
10399 x (nth (1- (if (= n 0) n0 n)) fields))
10400 (unless x (error "Invalid field specifier \"%s\""
10401 (match-string 0 form)))
10402 (setq form (replace-match
10403 (save-match-data
10404 (org-table-make-reference x nil numbers lispp))
10405 t t form)))
10407 (if lispp
10408 (setq ev (condition-case nil
10409 (eval (eval (read form)))
10410 (error "#ERROR"))
10411 ev (if (numberp ev) (number-to-string ev) ev))
10412 (or (fboundp 'calc-eval)
10413 (error "Calc does not seem to be installed, and is needed to evaluate the formula"))
10414 (setq ev (calc-eval (cons form modes)
10415 (if numbers 'num))))
10417 (when org-table-formula-debug
10418 (with-output-to-temp-buffer "*Substitution History*"
10419 (princ (format "Substitution history of formula
10420 Orig: %s
10421 $xyz-> %s
10422 @r$c-> %s
10423 $1-> %s\n" orig formula form0 form))
10424 (if (listp ev)
10425 (princ (format " %s^\nError: %s"
10426 (make-string (car ev) ?\-) (nth 1 ev)))
10427 (princ (format "Result: %s\nFormat: %s\nFinal: %s"
10428 ev (or fmt "NONE")
10429 (if fmt (format fmt (string-to-number ev)) ev)))))
10430 (setq bw (get-buffer-window "*Substitution History*"))
10431 (shrink-window-if-larger-than-buffer bw)
10432 (unless (and (interactive-p) (not ndown))
10433 (unless (let (inhibit-redisplay)
10434 (y-or-n-p "Debugging Formula. Continue to next? "))
10435 (org-table-align)
10436 (error "Abort"))
10437 (delete-window bw)
10438 (message "")))
10439 (if (listp ev) (setq fmt nil ev "#ERROR"))
10440 (org-table-justify-field-maybe
10441 (if fmt (format fmt (string-to-number ev)) ev))
10442 (if (and down (> ndown 0) (looking-at ".*\n[ \t]*|[^-]"))
10443 (call-interactively 'org-return)
10444 (setq ndown 0)))
10445 (and down (org-table-maybe-recalculate-line))
10446 (or suppress-align (and org-table-may-need-update
10447 (org-table-align))))))
10449 (defun org-table-put-field-property (prop value)
10450 (save-excursion
10451 (put-text-property (progn (skip-chars-backward "^|") (point))
10452 (progn (skip-chars-forward "^|") (point))
10453 prop value)))
10455 (defun org-table-get-range (desc &optional tbeg col highlight)
10456 "Get a calc vector from a column, accorting to descriptor DESC.
10457 Optional arguments TBEG and COL can give the beginning of the table and
10458 the current column, to avoid unnecessary parsing.
10459 HIGHLIGHT means, just highlight the range."
10460 (if (not (equal (string-to-char desc) ?@))
10461 (setq desc (concat "@" desc)))
10462 (save-excursion
10463 (or tbeg (setq tbeg (org-table-begin)))
10464 (or col (setq col (org-table-current-column)))
10465 (let ((thisline (org-current-line))
10466 beg end c1 c2 r1 r2 rangep tmp)
10467 (unless (string-match org-table-range-regexp desc)
10468 (error "Invalid table range specifier `%s'" desc))
10469 (setq rangep (match-end 3)
10470 r1 (and (match-end 1) (match-string 1 desc))
10471 r2 (and (match-end 4) (match-string 4 desc))
10472 c1 (and (match-end 2) (substring (match-string 2 desc) 1))
10473 c2 (and (match-end 5) (substring (match-string 5 desc) 1)))
10475 (and c1 (setq c1 (+ (string-to-number c1)
10476 (if (memq (string-to-char c1) '(?- ?+)) col 0))))
10477 (and c2 (setq c2 (+ (string-to-number c2)
10478 (if (memq (string-to-char c2) '(?- ?+)) col 0))))
10479 (if (equal r1 "") (setq r1 nil))
10480 (if (equal r2 "") (setq r2 nil))
10481 (if r1 (setq r1 (org-table-get-descriptor-line r1)))
10482 (if r2 (setq r2 (org-table-get-descriptor-line r2)))
10483 ; (setq r2 (or r2 r1) c2 (or c2 c1))
10484 (if (not r1) (setq r1 thisline))
10485 (if (not r2) (setq r2 thisline))
10486 (if (not c1) (setq c1 col))
10487 (if (not c2) (setq c2 col))
10488 (if (or (not rangep) (and (= r1 r2) (= c1 c2)))
10489 ;; just one field
10490 (progn
10491 (goto-line r1)
10492 (while (not (looking-at org-table-dataline-regexp))
10493 (beginning-of-line 2))
10494 (prog1 (org-trim (org-table-get-field c1))
10495 (if highlight (org-table-highlight-rectangle (point) (point)))))
10496 ;; A range, return a vector
10497 ;; First sort the numbers to get a regular ractangle
10498 (if (< r2 r1) (setq tmp r1 r1 r2 r2 tmp))
10499 (if (< c2 c1) (setq tmp c1 c1 c2 c2 tmp))
10500 (goto-line r1)
10501 (while (not (looking-at org-table-dataline-regexp))
10502 (beginning-of-line 2))
10503 (org-table-goto-column c1)
10504 (setq beg (point))
10505 (goto-line r2)
10506 (while (not (looking-at org-table-dataline-regexp))
10507 (beginning-of-line 0))
10508 (org-table-goto-column c2)
10509 (setq end (point))
10510 (if highlight
10511 (org-table-highlight-rectangle
10512 beg (progn (skip-chars-forward "^|\n") (point))))
10513 ;; return string representation of calc vector
10514 (mapcar 'org-trim
10515 (apply 'append (org-table-copy-region beg end)))))))
10517 (defun org-table-get-descriptor-line (desc &optional cline bline table)
10518 "Analyze descriptor DESC and retrieve the corresponding line number.
10519 The cursor is currently in line CLINE, the table begins in line BLINE,
10520 and TABLE is a vector with line types."
10521 (if (string-match "^[0-9]+$" desc)
10522 (aref org-table-dlines (string-to-number desc))
10523 (setq cline (or cline (org-current-line))
10524 bline (or bline org-table-current-begin-line)
10525 table (or table org-table-current-line-types))
10526 (if (or
10527 (not (string-match "^\\(\\([-+]\\)?\\(I+\\)\\)?\\(\\([-+]\\)?\\([0-9]+\\)\\)?" desc))
10528 ;; 1 2 3 4 5 6
10529 (and (not (match-end 3)) (not (match-end 6)))
10530 (and (match-end 3) (match-end 6) (not (match-end 5))))
10531 (error "invalid row descriptor `%s'" desc))
10532 (let* ((hdir (and (match-end 2) (match-string 2 desc)))
10533 (hn (if (match-end 3) (- (match-end 3) (match-beginning 3)) nil))
10534 (odir (and (match-end 5) (match-string 5 desc)))
10535 (on (if (match-end 6) (string-to-number (match-string 6 desc))))
10536 (i (- cline bline))
10537 (rel (and (match-end 6)
10538 (or (and (match-end 1) (not (match-end 3)))
10539 (match-end 5)))))
10540 (if (and hn (not hdir))
10541 (progn
10542 (setq i 0 hdir "+")
10543 (if (eq (aref table 0) 'hline) (setq hn (1- hn)))))
10544 (if (and (not hn) on (not odir))
10545 (error "should never happen");;(aref org-table-dlines on)
10546 (if (and hn (> hn 0))
10547 (setq i (org-find-row-type table i 'hline (equal hdir "-") nil hn)))
10548 (if on
10549 (setq i (org-find-row-type table i 'dline (equal odir "-") rel on)))
10550 (+ bline i)))))
10552 (defun org-find-row-type (table i type backwards relative n)
10553 (let ((l (length table)))
10554 (while (> n 0)
10555 (while (and (setq i (+ i (if backwards -1 1)))
10556 (>= i 0) (< i l)
10557 (not (eq (aref table i) type))
10558 (if (and relative (eq (aref table i) 'hline))
10559 (progn (setq i (- i (if backwards -1 1)) n 1) nil)
10560 t)))
10561 (setq n (1- n)))
10562 (if (or (< i 0) (>= i l))
10563 (error "Row descriptior leads outside table")
10564 i)))
10566 (defun org-rewrite-old-row-references (s)
10567 (if (string-match "&[-+0-9I]" s)
10568 (error "Formula contains old &row reference, please rewrite using @-syntax")
10571 (defun org-table-make-reference (elements keep-empty numbers lispp)
10572 "Convert list ELEMENTS to something appropriate to insert into formula.
10573 KEEP-EMPTY indicated to keep empty fields, default is to skip them.
10574 NUMBERS indicates that everything should be converted to numbers.
10575 LISPP means to return something appropriate for a Lisp list."
10576 (if (stringp elements) ; just a single val
10577 (if lispp
10578 (if (eq lispp 'literal)
10579 elements
10580 (prin1-to-string (if numbers (string-to-number elements) elements)))
10581 (if (equal elements "") (setq elements "0"))
10582 (if numbers (number-to-string (string-to-number elements)) elements))
10583 (unless keep-empty
10584 (setq elements
10585 (delq nil
10586 (mapcar (lambda (x) (if (string-match "\\S-" x) x nil))
10587 elements))))
10588 (setq elements (or elements '("0")))
10589 (if lispp
10590 (mapconcat
10591 (lambda (x)
10592 (if (eq lispp 'literal)
10594 (prin1-to-string (if numbers (string-to-number x) x))))
10595 elements " ")
10596 (concat "[" (mapconcat
10597 (lambda (x)
10598 (if numbers (number-to-string (string-to-number x)) x))
10599 elements
10600 ",") "]"))))
10602 (defun org-table-recalculate (&optional all noalign)
10603 "Recalculate the current table line by applying all stored formulas.
10604 With prefix arg ALL, do this for all lines in the table."
10605 (interactive "P")
10606 (or (memq this-command org-recalc-commands)
10607 (setq org-recalc-commands (cons this-command org-recalc-commands)))
10608 (unless (org-at-table-p) (error "Not at a table"))
10609 (if (equal all '(16))
10610 (org-table-iterate)
10611 (org-table-get-specials)
10612 (let* ((eqlist (sort (org-table-get-stored-formulas)
10613 (lambda (a b) (string< (car a) (car b)))))
10614 (inhibit-redisplay (not debug-on-error))
10615 (line-re org-table-dataline-regexp)
10616 (thisline (org-current-line))
10617 (thiscol (org-table-current-column))
10618 beg end entry eqlnum eqlname eqlname1 eql (cnt 0) eq a name)
10619 ;; Insert constants in all formulas
10620 (setq eqlist
10621 (mapcar (lambda (x)
10622 (setcdr x (org-table-formula-substitute-names (cdr x)))
10624 eqlist))
10625 ;; Split the equation list
10626 (while (setq eq (pop eqlist))
10627 (if (<= (string-to-char (car eq)) ?9)
10628 (push eq eqlnum)
10629 (push eq eqlname)))
10630 (setq eqlnum (nreverse eqlnum) eqlname (nreverse eqlname))
10631 (if all
10632 (progn
10633 (setq end (move-marker (make-marker) (1+ (org-table-end))))
10634 (goto-char (setq beg (org-table-begin)))
10635 (if (re-search-forward org-table-calculate-mark-regexp end t)
10636 ;; This is a table with marked lines, compute selected lines
10637 (setq line-re org-table-recalculate-regexp)
10638 ;; Move forward to the first non-header line
10639 (if (and (re-search-forward org-table-dataline-regexp end t)
10640 (re-search-forward org-table-hline-regexp end t)
10641 (re-search-forward org-table-dataline-regexp end t))
10642 (setq beg (match-beginning 0))
10643 nil))) ;; just leave beg where it is
10644 (setq beg (point-at-bol)
10645 end (move-marker (make-marker) (1+ (point-at-eol)))))
10646 (goto-char beg)
10647 (and all (message "Re-applying formulas to full table..."))
10649 ;; First find the named fields, and mark them untouchanble
10650 (remove-text-properties beg end '(org-untouchable t))
10651 (while (setq eq (pop eqlname))
10652 (setq name (car eq)
10653 a (assoc name org-table-named-field-locations))
10654 (and (not a)
10655 (string-match "@\\([0-9]+\\)\\$\\([0-9]+\\)" name)
10656 (setq a (list name
10657 (aref org-table-dlines
10658 (string-to-number (match-string 1 name)))
10659 (string-to-number (match-string 2 name)))))
10660 (when (and a (or all (equal (nth 1 a) thisline)))
10661 (message "Re-applying formula to field: %s" name)
10662 (goto-line (nth 1 a))
10663 (org-table-goto-column (nth 2 a))
10664 (push (append a (list (cdr eq))) eqlname1)
10665 (org-table-put-field-property :org-untouchable t)))
10667 ;; Now evauluate the column formulas, but skip fields covered by
10668 ;; field formulas
10669 (goto-char beg)
10670 (while (re-search-forward line-re end t)
10671 (unless (string-match "^ *[_^!$/] *$" (org-table-get-field 1))
10672 ;; Unprotected line, recalculate
10673 (and all (message "Re-applying formulas to full table...(line %d)"
10674 (setq cnt (1+ cnt))))
10675 (setq org-last-recalc-line (org-current-line))
10676 (setq eql eqlnum)
10677 (while (setq entry (pop eql))
10678 (goto-line org-last-recalc-line)
10679 (org-table-goto-column (string-to-number (car entry)) nil 'force)
10680 (unless (get-text-property (point) :org-untouchable)
10681 (org-table-eval-formula nil (cdr entry)
10682 'noalign 'nocst 'nostore 'noanalysis)))))
10684 ;; Now evaluate the field formulas
10685 (while (setq eq (pop eqlname1))
10686 (message "Re-applying formula to field: %s" (car eq))
10687 (goto-line (nth 1 eq))
10688 (org-table-goto-column (nth 2 eq))
10689 (org-table-eval-formula nil (nth 3 eq) 'noalign 'nocst
10690 'nostore 'noanalysis))
10692 (goto-line thisline)
10693 (org-table-goto-column thiscol)
10694 (remove-text-properties (point-min) (point-max) '(org-untouchable t))
10695 (or noalign (and org-table-may-need-update (org-table-align))
10696 (and all (message "Re-applying formulas to %d lines...done" cnt)))
10698 ;; back to initial position
10699 (message "Re-applying formulas...done")
10700 (goto-line thisline)
10701 (org-table-goto-column thiscol)
10702 (or noalign (and org-table-may-need-update (org-table-align))
10703 (and all (message "Re-applying formulas...done"))))))
10705 (defun org-table-iterate (&optional arg)
10706 "Recalculate the table until it does not change anymore."
10707 (interactive "P")
10708 (let ((imax (if arg (prefix-numeric-value arg) 10))
10709 (i 0)
10710 (lasttbl (buffer-substring (org-table-begin) (org-table-end)))
10711 thistbl)
10712 (catch 'exit
10713 (while (< i imax)
10714 (setq i (1+ i))
10715 (org-table-recalculate 'all)
10716 (setq thistbl (buffer-substring (org-table-begin) (org-table-end)))
10717 (if (not (string= lasttbl thistbl))
10718 (setq lasttbl thistbl)
10719 (if (> i 1)
10720 (message "Convergence after %d iterations" i)
10721 (message "Table was already stable"))
10722 (throw 'exit t)))
10723 (error "No convergence after %d iterations" i))))
10725 (defun org-table-formula-substitute-names (f)
10726 "Replace $const with values in string F."
10727 (let ((start 0) a (f1 f) (pp (/= (string-to-char f) ?')))
10728 ;; First, check for column names
10729 (while (setq start (string-match org-table-column-name-regexp f start))
10730 (setq start (1+ start))
10731 (setq a (assoc (match-string 1 f) org-table-column-names))
10732 (setq f (replace-match (concat "$" (cdr a)) t t f)))
10733 ;; Parameters and constants
10734 (setq start 0)
10735 (while (setq start (string-match "\\$\\([a-zA-Z][_a-zA-Z0-9]*\\)" f start))
10736 (setq start (1+ start))
10737 (if (setq a (save-match-data
10738 (org-table-get-constant (match-string 1 f))))
10739 (setq f (replace-match
10740 (concat (if pp "(") a (if pp ")")) t t f))))
10741 (if org-table-formula-debug
10742 (put-text-property 0 (length f) :orig-formula f1 f))
10745 (defun org-table-get-constant (const)
10746 "Find the value for a parameter or constant in a formula.
10747 Parameters get priority."
10748 (or (cdr (assoc const org-table-local-parameters))
10749 (cdr (assoc const org-table-formula-constants-local))
10750 (cdr (assoc const org-table-formula-constants))
10751 (and (fboundp 'constants-get) (constants-get const))
10752 (and (string= (substring const 0 (min 5 (length const))) "PROP_")
10753 (org-entry-get nil (substring const 5) 'inherit))
10754 "#UNDEFINED_NAME"))
10756 (defvar org-table-fedit-map
10757 (let ((map (make-sparse-keymap)))
10758 (org-defkey map "\C-x\C-s" 'org-table-fedit-finish)
10759 (org-defkey map "\C-c\C-s" 'org-table-fedit-finish)
10760 (org-defkey map "\C-c\C-c" 'org-table-fedit-finish)
10761 (org-defkey map "\C-c\C-q" 'org-table-fedit-abort)
10762 (org-defkey map "\C-c?" 'org-table-show-reference)
10763 (org-defkey map [(meta shift up)] 'org-table-fedit-line-up)
10764 (org-defkey map [(meta shift down)] 'org-table-fedit-line-down)
10765 (org-defkey map [(shift up)] 'org-table-fedit-ref-up)
10766 (org-defkey map [(shift down)] 'org-table-fedit-ref-down)
10767 (org-defkey map [(shift left)] 'org-table-fedit-ref-left)
10768 (org-defkey map [(shift right)] 'org-table-fedit-ref-right)
10769 (org-defkey map [(meta up)] 'org-table-fedit-scroll-down)
10770 (org-defkey map [(meta down)] 'org-table-fedit-scroll)
10771 (org-defkey map [(meta tab)] 'lisp-complete-symbol)
10772 (org-defkey map "\M-\C-i" 'lisp-complete-symbol)
10773 (org-defkey map [(tab)] 'org-table-fedit-lisp-indent)
10774 (org-defkey map "\C-i" 'org-table-fedit-lisp-indent)
10775 (org-defkey map "\C-c\C-r" 'org-table-fedit-toggle-ref-type)
10776 (org-defkey map "\C-c}" 'org-table-fedit-toggle-coordinates)
10777 map))
10779 (easy-menu-define org-table-fedit-menu org-table-fedit-map "Org Edit Formulas Menu"
10780 '("Edit-Formulas"
10781 ["Finish and Install" org-table-fedit-finish t]
10782 ["Finish, Install, and Apply" (org-table-fedit-finish t) :keys "C-u C-c C-c"]
10783 ["Abort" org-table-fedit-abort t]
10784 "--"
10785 ["Pretty-Print Lisp Formula" org-table-fedit-lisp-indent t]
10786 ["Complete Lisp Symbol" lisp-complete-symbol t]
10787 "--"
10788 "Shift Reference at Point"
10789 ["Up" org-table-fedit-ref-up t]
10790 ["Down" org-table-fedit-ref-down t]
10791 ["Left" org-table-fedit-ref-left t]
10792 ["Right" org-table-fedit-ref-right t]
10794 "Change Test Row for Column Formulas"
10795 ["Up" org-table-fedit-line-up t]
10796 ["Down" org-table-fedit-line-down t]
10797 "--"
10798 ["Scroll Table Window" org-table-fedit-scroll t]
10799 ["Scroll Table Window down" org-table-fedit-scroll-down t]
10800 ["Show Table Grid" org-table-fedit-toggle-coordinates
10801 :style toggle :selected (with-current-buffer (marker-buffer org-pos)
10802 org-table-overlay-coordinates)]
10803 "--"
10804 ["Standard Refs (B3 instead of @3$2)" org-table-fedit-toggle-ref-type
10805 :style toggle :selected org-table-buffer-is-an]))
10807 (defvar org-pos)
10809 (defun org-table-edit-formulas ()
10810 "Edit the formulas of the current table in a separate buffer."
10811 (interactive)
10812 (when (save-excursion (beginning-of-line 1) (looking-at "#\\+TBLFM"))
10813 (beginning-of-line 0))
10814 (unless (org-at-table-p) (error "Not at a table"))
10815 (org-table-get-specials)
10816 (let ((key (org-table-current-field-formula 'key 'noerror))
10817 (eql (sort (org-table-get-stored-formulas 'noerror)
10818 'org-table-formula-less-p))
10819 (pos (move-marker (make-marker) (point)))
10820 (startline 1)
10821 (wc (current-window-configuration))
10822 (titles '((column . "# Column Formulas\n")
10823 (field . "# Field Formulas\n")
10824 (named . "# Named Field Formulas\n")))
10825 entry s type title)
10826 (org-switch-to-buffer-other-window "*Edit Formulas*")
10827 (erase-buffer)
10828 ;; Keep global-font-lock-mode from turning on font-lock-mode
10829 (let ((font-lock-global-modes '(not fundamental-mode)))
10830 (fundamental-mode))
10831 (org-set-local 'font-lock-global-modes (list 'not major-mode))
10832 (org-set-local 'org-pos pos)
10833 (org-set-local 'org-window-configuration wc)
10834 (use-local-map org-table-fedit-map)
10835 (org-add-hook 'post-command-hook 'org-table-fedit-post-command t t)
10836 (easy-menu-add org-table-fedit-menu)
10837 (setq startline (org-current-line))
10838 (while (setq entry (pop eql))
10839 (setq type (cond
10840 ((equal (string-to-char (car entry)) ?@) 'field)
10841 ((string-match "^[0-9]" (car entry)) 'column)
10842 (t 'named)))
10843 (when (setq title (assq type titles))
10844 (or (bobp) (insert "\n"))
10845 (insert (org-add-props (cdr title) nil 'face font-lock-comment-face))
10846 (setq titles (delq title titles)))
10847 (if (equal key (car entry)) (setq startline (org-current-line)))
10848 (setq s (concat (if (equal (string-to-char (car entry)) ?@) "" "$")
10849 (car entry) " = " (cdr entry) "\n"))
10850 (remove-text-properties 0 (length s) '(face nil) s)
10851 (insert s))
10852 (if (eq org-table-use-standard-references t)
10853 (org-table-fedit-toggle-ref-type))
10854 (goto-line startline)
10855 (message "Edit formulas and finish with `C-c C-c'. See menu for more commands.")))
10857 (defun org-table-fedit-post-command ()
10858 (when (not (memq this-command '(lisp-complete-symbol)))
10859 (let ((win (selected-window)))
10860 (save-excursion
10861 (condition-case nil
10862 (org-table-show-reference)
10863 (error nil))
10864 (select-window win)))))
10866 (defun org-table-formula-to-user (s)
10867 "Convert a formula from internal to user representation."
10868 (if (eq org-table-use-standard-references t)
10869 (org-table-convert-refs-to-an s)
10872 (defun org-table-formula-from-user (s)
10873 "Convert a formula from user to internal representation."
10874 (if org-table-use-standard-references
10875 (org-table-convert-refs-to-rc s)
10878 (defun org-table-convert-refs-to-rc (s)
10879 "Convert spreadsheet references from AB7 to @7$28.
10880 Works for single references, but also for entire formulas and even the
10881 full TBLFM line."
10882 (let ((start 0))
10883 (while (string-match "\\<\\([a-zA-Z]+\\)\\([0-9]+\\>\\|&\\)\\|\\(;[^\r\n:]+\\)" s start)
10884 (cond
10885 ((match-end 3)
10886 ;; format match, just advance
10887 (setq start (match-end 0)))
10888 ((and (> (match-beginning 0) 0)
10889 (equal ?. (aref s (max (1- (match-beginning 0)) 0)))
10890 (not (equal ?. (aref s (max (- (match-beginning 0) 2) 0)))))
10891 ;; 3.e5 or something like this.
10892 (setq start (match-end 0)))
10894 (setq start (match-beginning 0)
10895 s (replace-match
10896 (if (equal (match-string 2 s) "&")
10897 (format "$%d" (org-letters-to-number (match-string 1 s)))
10898 (format "@%d$%d"
10899 (string-to-number (match-string 2 s))
10900 (org-letters-to-number (match-string 1 s))))
10901 t t s)))))
10904 (defun org-table-convert-refs-to-an (s)
10905 "Convert spreadsheet references from to @7$28 to AB7.
10906 Works for single references, but also for entire formulas and even the
10907 full TBLFM line."
10908 (while (string-match "@\\([0-9]+\\)\\$\\([0-9]+\\)" s)
10909 (setq s (replace-match
10910 (format "%s%d"
10911 (org-number-to-letters
10912 (string-to-number (match-string 2 s)))
10913 (string-to-number (match-string 1 s)))
10914 t t s)))
10915 (while (string-match "\\(^\\|[^0-9a-zA-Z]\\)\\$\\([0-9]+\\)" s)
10916 (setq s (replace-match (concat "\\1"
10917 (org-number-to-letters
10918 (string-to-number (match-string 2 s))) "&")
10919 t nil s)))
10922 (defun org-letters-to-number (s)
10923 "Convert a base 26 number represented by letters into an integer.
10924 For example: AB -> 28."
10925 (let ((n 0))
10926 (setq s (upcase s))
10927 (while (> (length s) 0)
10928 (setq n (+ (* n 26) (string-to-char s) (- ?A) 1)
10929 s (substring s 1)))
10932 (defun org-number-to-letters (n)
10933 "Convert an integer into a base 26 number represented by letters.
10934 For example: 28 -> AB."
10935 (let ((s ""))
10936 (while (> n 0)
10937 (setq s (concat (char-to-string (+ (mod (1- n) 26) ?A)) s)
10938 n (/ (1- n) 26)))
10941 (defun org-table-fedit-convert-buffer (function)
10942 "Convert all references in this buffer, using FUNTION."
10943 (let ((line (org-current-line)))
10944 (goto-char (point-min))
10945 (while (not (eobp))
10946 (insert (funcall function (buffer-substring (point) (point-at-eol))))
10947 (delete-region (point) (point-at-eol))
10948 (or (eobp) (forward-char 1)))
10949 (goto-line line)))
10951 (defun org-table-fedit-toggle-ref-type ()
10952 "Convert all references in the buffer from B3 to @3$2 and back."
10953 (interactive)
10954 (org-set-local 'org-table-buffer-is-an (not org-table-buffer-is-an))
10955 (org-table-fedit-convert-buffer
10956 (if org-table-buffer-is-an
10957 'org-table-convert-refs-to-an 'org-table-convert-refs-to-rc))
10958 (message "Reference type switched to %s"
10959 (if org-table-buffer-is-an "A1 etc" "@row$column")))
10961 (defun org-table-fedit-ref-up ()
10962 "Shift the reference at point one row/hline up."
10963 (interactive)
10964 (org-table-fedit-shift-reference 'up))
10965 (defun org-table-fedit-ref-down ()
10966 "Shift the reference at point one row/hline down."
10967 (interactive)
10968 (org-table-fedit-shift-reference 'down))
10969 (defun org-table-fedit-ref-left ()
10970 "Shift the reference at point one field to the left."
10971 (interactive)
10972 (org-table-fedit-shift-reference 'left))
10973 (defun org-table-fedit-ref-right ()
10974 "Shift the reference at point one field to the right."
10975 (interactive)
10976 (org-table-fedit-shift-reference 'right))
10978 (defun org-table-fedit-shift-reference (dir)
10979 (cond
10980 ((org-at-regexp-p "\\(\\<[a-zA-Z]\\)&")
10981 (if (memq dir '(left right))
10982 (org-rematch-and-replace 1 (eq dir 'left))
10983 (error "Cannot shift reference in this direction")))
10984 ((org-at-regexp-p "\\(\\<[a-zA-Z]\\{1,2\\}\\)\\([0-9]+\\)")
10985 ;; A B3-like reference
10986 (if (memq dir '(up down))
10987 (org-rematch-and-replace 2 (eq dir 'up))
10988 (org-rematch-and-replace 1 (eq dir 'left))))
10989 ((org-at-regexp-p
10990 "\\(@\\|\\.\\.\\)\\([-+]?\\(I+\\>\\|[0-9]+\\)\\)\\(\\$\\([-+]?[0-9]+\\)\\)?")
10991 ;; An internal reference
10992 (if (memq dir '(up down))
10993 (org-rematch-and-replace 2 (eq dir 'up) (match-end 3))
10994 (org-rematch-and-replace 5 (eq dir 'left))))))
10996 (defun org-rematch-and-replace (n &optional decr hline)
10997 "Re-match the group N, and replace it with the shifted refrence."
10998 (or (match-end n) (error "Cannot shift reference in this direction"))
10999 (goto-char (match-beginning n))
11000 (and (looking-at (regexp-quote (match-string n)))
11001 (replace-match (org-shift-refpart (match-string 0) decr hline)
11002 t t)))
11004 (defun org-shift-refpart (ref &optional decr hline)
11005 "Shift a refrence part REF.
11006 If DECR is set, decrease the references row/column, else increase.
11007 If HLINE is set, this may be a hline reference, it certainly is not
11008 a translation reference."
11009 (save-match-data
11010 (let* ((sign (string-match "^[-+]" ref)) n)
11012 (if sign (setq sign (substring ref 0 1) ref (substring ref 1)))
11013 (cond
11014 ((and hline (string-match "^I+" ref))
11015 (setq n (string-to-number (concat sign (number-to-string (length ref)))))
11016 (setq n (+ n (if decr -1 1)))
11017 (if (= n 0) (setq n (+ n (if decr -1 1))))
11018 (if sign
11019 (setq sign (if (< n 0) "-" "+") n (abs n))
11020 (setq n (max 1 n)))
11021 (concat sign (make-string n ?I)))
11023 ((string-match "^[0-9]+" ref)
11024 (setq n (string-to-number (concat sign ref)))
11025 (setq n (+ n (if decr -1 1)))
11026 (if sign
11027 (concat (if (< n 0) "-" "+") (number-to-string (abs n)))
11028 (number-to-string (max 1 n))))
11030 ((string-match "^[a-zA-Z]+" ref)
11031 (org-number-to-letters
11032 (max 1 (+ (org-letters-to-number ref) (if decr -1 1)))))
11034 (t (error "Cannot shift reference"))))))
11036 (defun org-table-fedit-toggle-coordinates ()
11037 "Toggle the display of coordinates in the refrenced table."
11038 (interactive)
11039 (let ((pos (marker-position org-pos)))
11040 (with-current-buffer (marker-buffer org-pos)
11041 (save-excursion
11042 (goto-char pos)
11043 (org-table-toggle-coordinate-overlays)))))
11045 (defun org-table-fedit-finish (&optional arg)
11046 "Parse the buffer for formula definitions and install them.
11047 With prefix ARG, apply the new formulas to the table."
11048 (interactive "P")
11049 (org-table-remove-rectangle-highlight)
11050 (if org-table-use-standard-references
11051 (progn
11052 (org-table-fedit-convert-buffer 'org-table-convert-refs-to-rc)
11053 (setq org-table-buffer-is-an nil)))
11054 (let ((pos org-pos) eql var form)
11055 (goto-char (point-min))
11056 (while (re-search-forward
11057 "^\\(@[0-9]+\\$[0-9]+\\|\\$\\([a-zA-Z0-9]+\\)\\) *= *\\(.*\\(\n[ \t]+.*$\\)*\\)"
11058 nil t)
11059 (setq var (if (match-end 2) (match-string 2) (match-string 1))
11060 form (match-string 3))
11061 (setq form (org-trim form))
11062 (when (not (equal form ""))
11063 (while (string-match "[ \t]*\n[ \t]*" form)
11064 (setq form (replace-match " " t t form)))
11065 (when (assoc var eql)
11066 (error "Double formulas for %s" var))
11067 (push (cons var form) eql)))
11068 (setq org-pos nil)
11069 (set-window-configuration org-window-configuration)
11070 (select-window (get-buffer-window (marker-buffer pos)))
11071 (goto-char pos)
11072 (unless (org-at-table-p)
11073 (error "Lost table position - cannot install formulae"))
11074 (org-table-store-formulas eql)
11075 (move-marker pos nil)
11076 (kill-buffer "*Edit Formulas*")
11077 (if arg
11078 (org-table-recalculate 'all)
11079 (message "New formulas installed - press C-u C-c C-c to apply."))))
11081 (defun org-table-fedit-abort ()
11082 "Abort editing formulas, without installing the changes."
11083 (interactive)
11084 (org-table-remove-rectangle-highlight)
11085 (let ((pos org-pos))
11086 (set-window-configuration org-window-configuration)
11087 (select-window (get-buffer-window (marker-buffer pos)))
11088 (goto-char pos)
11089 (move-marker pos nil)
11090 (message "Formula editing aborted without installing changes")))
11092 (defun org-table-fedit-lisp-indent ()
11093 "Pretty-print and re-indent Lisp expressions in the Formula Editor."
11094 (interactive)
11095 (let ((pos (point)) beg end ind)
11096 (beginning-of-line 1)
11097 (cond
11098 ((looking-at "[ \t]")
11099 (goto-char pos)
11100 (call-interactively 'lisp-indent-line))
11101 ((looking-at "[$&@0-9a-zA-Z]+ *= *[^ \t\n']") (goto-char pos))
11102 ((not (fboundp 'pp-buffer))
11103 (error "Cannot pretty-print. Command `pp-buffer' is not available."))
11104 ((looking-at "[$&@0-9a-zA-Z]+ *= *'(")
11105 (goto-char (- (match-end 0) 2))
11106 (setq beg (point))
11107 (setq ind (make-string (current-column) ?\ ))
11108 (condition-case nil (forward-sexp 1)
11109 (error
11110 (error "Cannot pretty-print Lisp expression: Unbalanced parenthesis")))
11111 (setq end (point))
11112 (save-restriction
11113 (narrow-to-region beg end)
11114 (if (eq last-command this-command)
11115 (progn
11116 (goto-char (point-min))
11117 (setq this-command nil)
11118 (while (re-search-forward "[ \t]*\n[ \t]*" nil t)
11119 (replace-match " ")))
11120 (pp-buffer)
11121 (untabify (point-min) (point-max))
11122 (goto-char (1+ (point-min)))
11123 (while (re-search-forward "^." nil t)
11124 (beginning-of-line 1)
11125 (insert ind))
11126 (goto-char (point-max))
11127 (backward-delete-char 1)))
11128 (goto-char beg))
11129 (t nil))))
11131 (defvar org-show-positions nil)
11133 (defun org-table-show-reference (&optional local)
11134 "Show the location/value of the $ expression at point."
11135 (interactive)
11136 (org-table-remove-rectangle-highlight)
11137 (catch 'exit
11138 (let ((pos (if local (point) org-pos))
11139 (face2 'highlight)
11140 (org-inhibit-highlight-removal t)
11141 (win (selected-window))
11142 (org-show-positions nil)
11143 var name e what match dest)
11144 (if local (org-table-get-specials))
11145 (setq what (cond
11146 ((or (org-at-regexp-p org-table-range-regexp2)
11147 (org-at-regexp-p org-table-translate-regexp)
11148 (org-at-regexp-p org-table-range-regexp))
11149 (setq match
11150 (save-match-data
11151 (org-table-convert-refs-to-rc (match-string 0))))
11152 'range)
11153 ((org-at-regexp-p "\\$[a-zA-Z][a-zA-Z0-9]*") 'name)
11154 ((org-at-regexp-p "\\$[0-9]+") 'column)
11155 ((not local) nil)
11156 (t (error "No reference at point")))
11157 match (and what (or match (match-string 0))))
11158 (when (and match (not (equal (match-beginning 0) (point-at-bol))))
11159 (org-table-add-rectangle-overlay (match-beginning 0) (match-end 0)
11160 'secondary-selection))
11161 (org-add-hook 'before-change-functions
11162 'org-table-remove-rectangle-highlight)
11163 (if (eq what 'name) (setq var (substring match 1)))
11164 (when (eq what 'range)
11165 (or (equal (string-to-char match) ?@) (setq match (concat "@" match)))
11166 (setq match (org-table-formula-substitute-names match)))
11167 (unless local
11168 (save-excursion
11169 (end-of-line 1)
11170 (re-search-backward "^\\S-" nil t)
11171 (beginning-of-line 1)
11172 (when (looking-at "\\(\\$[0-9a-zA-Z]+\\|@[0-9]+\\$[0-9]+\\|[a-zA-Z]+\\([0-9]+\\|&\\)\\) *=")
11173 (setq dest
11174 (save-match-data
11175 (org-table-convert-refs-to-rc (match-string 1))))
11176 (org-table-add-rectangle-overlay
11177 (match-beginning 1) (match-end 1) face2))))
11178 (if (and (markerp pos) (marker-buffer pos))
11179 (if (get-buffer-window (marker-buffer pos))
11180 (select-window (get-buffer-window (marker-buffer pos)))
11181 (org-switch-to-buffer-other-window (get-buffer-window
11182 (marker-buffer pos)))))
11183 (goto-char pos)
11184 (org-table-force-dataline)
11185 (when dest
11186 (setq name (substring dest 1))
11187 (cond
11188 ((string-match "^\\$[a-zA-Z][a-zA-Z0-9]*" dest)
11189 (setq e (assoc name org-table-named-field-locations))
11190 (goto-line (nth 1 e))
11191 (org-table-goto-column (nth 2 e)))
11192 ((string-match "^@\\([0-9]+\\)\\$\\([0-9]+\\)" dest)
11193 (let ((l (string-to-number (match-string 1 dest)))
11194 (c (string-to-number (match-string 2 dest))))
11195 (goto-line (aref org-table-dlines l))
11196 (org-table-goto-column c)))
11197 (t (org-table-goto-column (string-to-number name))))
11198 (move-marker pos (point))
11199 (org-table-highlight-rectangle nil nil face2))
11200 (cond
11201 ((equal dest match))
11202 ((not match))
11203 ((eq what 'range)
11204 (condition-case nil
11205 (save-excursion
11206 (org-table-get-range match nil nil 'highlight))
11207 (error nil)))
11208 ((setq e (assoc var org-table-named-field-locations))
11209 (goto-line (nth 1 e))
11210 (org-table-goto-column (nth 2 e))
11211 (org-table-highlight-rectangle (point) (point))
11212 (message "Named field, column %d of line %d" (nth 2 e) (nth 1 e)))
11213 ((setq e (assoc var org-table-column-names))
11214 (org-table-goto-column (string-to-number (cdr e)))
11215 (org-table-highlight-rectangle (point) (point))
11216 (goto-char (org-table-begin))
11217 (if (re-search-forward (concat "^[ \t]*| *! *.*?| *\\(" var "\\) *|")
11218 (org-table-end) t)
11219 (progn
11220 (goto-char (match-beginning 1))
11221 (org-table-highlight-rectangle)
11222 (message "Named column (column %s)" (cdr e)))
11223 (error "Column name not found")))
11224 ((eq what 'column)
11225 ;; column number
11226 (org-table-goto-column (string-to-number (substring match 1)))
11227 (org-table-highlight-rectangle (point) (point))
11228 (message "Column %s" (substring match 1)))
11229 ((setq e (assoc var org-table-local-parameters))
11230 (goto-char (org-table-begin))
11231 (if (re-search-forward (concat "^[ \t]*| *\\$ *.*?| *\\(" var "=\\)") nil t)
11232 (progn
11233 (goto-char (match-beginning 1))
11234 (org-table-highlight-rectangle)
11235 (message "Local parameter."))
11236 (error "Parameter not found")))
11238 (cond
11239 ((not var) (error "No reference at point"))
11240 ((setq e (assoc var org-table-formula-constants-local))
11241 (message "Local Constant: $%s=%s in #+CONSTANTS line."
11242 var (cdr e)))
11243 ((setq e (assoc var org-table-formula-constants))
11244 (message "Constant: $%s=%s in `org-table-formula-constants'."
11245 var (cdr e)))
11246 ((setq e (and (fboundp 'constants-get) (constants-get var)))
11247 (message "Constant: $%s=%s, from `constants.el'%s."
11248 var e (format " (%s units)" constants-unit-system)))
11249 (t (error "Undefined name $%s" var)))))
11250 (goto-char pos)
11251 (when (and org-show-positions
11252 (not (memq this-command '(org-table-fedit-scroll
11253 org-table-fedit-scroll-down))))
11254 (push pos org-show-positions)
11255 (push org-table-current-begin-pos org-show-positions)
11256 (let ((min (apply 'min org-show-positions))
11257 (max (apply 'max org-show-positions)))
11258 (goto-char min) (recenter 0)
11259 (goto-char max)
11260 (or (pos-visible-in-window-p max) (recenter -1))))
11261 (select-window win))))
11263 (defun org-table-force-dataline ()
11264 "Make sure the cursor is in a dataline in a table."
11265 (unless (save-excursion
11266 (beginning-of-line 1)
11267 (looking-at org-table-dataline-regexp))
11268 (let* ((re org-table-dataline-regexp)
11269 (p1 (save-excursion (re-search-forward re nil 'move)))
11270 (p2 (save-excursion (re-search-backward re nil 'move))))
11271 (cond ((and p1 p2)
11272 (goto-char (if (< (abs (- p1 (point))) (abs (- p2 (point))))
11273 p1 p2)))
11274 ((or p1 p2) (goto-char (or p1 p2)))
11275 (t (error "No table dataline around here"))))))
11277 (defun org-table-fedit-line-up ()
11278 "Move cursor one line up in the window showing the table."
11279 (interactive)
11280 (org-table-fedit-move 'previous-line))
11282 (defun org-table-fedit-line-down ()
11283 "Move cursor one line down in the window showing the table."
11284 (interactive)
11285 (org-table-fedit-move 'next-line))
11287 (defun org-table-fedit-move (command)
11288 "Move the cursor in the window shoinw the table.
11289 Use COMMAND to do the motion, repeat if necessary to end up in a data line."
11290 (let ((org-table-allow-automatic-line-recalculation nil)
11291 (pos org-pos) (win (selected-window)) p)
11292 (select-window (get-buffer-window (marker-buffer org-pos)))
11293 (setq p (point))
11294 (call-interactively command)
11295 (while (and (org-at-table-p)
11296 (org-at-table-hline-p))
11297 (call-interactively command))
11298 (or (org-at-table-p) (goto-char p))
11299 (move-marker pos (point))
11300 (select-window win)))
11302 (defun org-table-fedit-scroll (N)
11303 (interactive "p")
11304 (let ((other-window-scroll-buffer (marker-buffer org-pos)))
11305 (scroll-other-window N)))
11307 (defun org-table-fedit-scroll-down (N)
11308 (interactive "p")
11309 (org-table-fedit-scroll (- N)))
11311 (defvar org-table-rectangle-overlays nil)
11313 (defun org-table-add-rectangle-overlay (beg end &optional face)
11314 "Add a new overlay."
11315 (let ((ov (org-make-overlay beg end)))
11316 (org-overlay-put ov 'face (or face 'secondary-selection))
11317 (push ov org-table-rectangle-overlays)))
11319 (defun org-table-highlight-rectangle (&optional beg end face)
11320 "Highlight rectangular region in a table."
11321 (setq beg (or beg (point)) end (or end (point)))
11322 (let ((b (min beg end))
11323 (e (max beg end))
11324 l1 c1 l2 c2 tmp)
11325 (and (boundp 'org-show-positions)
11326 (setq org-show-positions (cons b (cons e org-show-positions))))
11327 (goto-char (min beg end))
11328 (setq l1 (org-current-line)
11329 c1 (org-table-current-column))
11330 (goto-char (max beg end))
11331 (setq l2 (org-current-line)
11332 c2 (org-table-current-column))
11333 (if (> c1 c2) (setq tmp c1 c1 c2 c2 tmp))
11334 (goto-line l1)
11335 (beginning-of-line 1)
11336 (loop for line from l1 to l2 do
11337 (when (looking-at org-table-dataline-regexp)
11338 (org-table-goto-column c1)
11339 (skip-chars-backward "^|\n") (setq beg (point))
11340 (org-table-goto-column c2)
11341 (skip-chars-forward "^|\n") (setq end (point))
11342 (org-table-add-rectangle-overlay beg end face))
11343 (beginning-of-line 2))
11344 (goto-char b))
11345 (add-hook 'before-change-functions 'org-table-remove-rectangle-highlight))
11347 (defun org-table-remove-rectangle-highlight (&rest ignore)
11348 "Remove the rectangle overlays."
11349 (unless org-inhibit-highlight-removal
11350 (remove-hook 'before-change-functions 'org-table-remove-rectangle-highlight)
11351 (mapc 'org-delete-overlay org-table-rectangle-overlays)
11352 (setq org-table-rectangle-overlays nil)))
11354 (defvar org-table-coordinate-overlays nil
11355 "Collects the cooordinate grid overlays, so that they can be removed.")
11356 (make-variable-buffer-local 'org-table-coordinate-overlays)
11358 (defun org-table-overlay-coordinates ()
11359 "Add overlays to the table at point, to show row/column coordinates."
11360 (interactive)
11361 (mapc 'org-delete-overlay org-table-coordinate-overlays)
11362 (setq org-table-coordinate-overlays nil)
11363 (save-excursion
11364 (let ((id 0) (ih 0) hline eol s1 s2 str ic ov beg)
11365 (goto-char (org-table-begin))
11366 (while (org-at-table-p)
11367 (setq eol (point-at-eol))
11368 (setq ov (org-make-overlay (point-at-bol) (1+ (point-at-bol))))
11369 (push ov org-table-coordinate-overlays)
11370 (setq hline (looking-at org-table-hline-regexp))
11371 (setq str (if hline (format "I*%-2d" (setq ih (1+ ih)))
11372 (format "%4d" (setq id (1+ id)))))
11373 (org-overlay-before-string ov str 'org-special-keyword 'evaporate)
11374 (when hline
11375 (setq ic 0)
11376 (while (re-search-forward "[+|]\\(-+\\)" eol t)
11377 (setq beg (1+ (match-beginning 0))
11378 ic (1+ ic)
11379 s1 (concat "$" (int-to-string ic))
11380 s2 (org-number-to-letters ic)
11381 str (if (eq org-table-use-standard-references t) s2 s1))
11382 (setq ov (org-make-overlay beg (+ beg (length str))))
11383 (push ov org-table-coordinate-overlays)
11384 (org-overlay-display ov str 'org-special-keyword 'evaporate)))
11385 (beginning-of-line 2)))))
11387 (defun org-table-toggle-coordinate-overlays ()
11388 "Toggle the display of Row/Column numbers in tables."
11389 (interactive)
11390 (setq org-table-overlay-coordinates (not org-table-overlay-coordinates))
11391 (message "Row/Column number display turned %s"
11392 (if org-table-overlay-coordinates "on" "off"))
11393 (if (and (org-at-table-p) org-table-overlay-coordinates)
11394 (org-table-align))
11395 (unless org-table-overlay-coordinates
11396 (mapc 'org-delete-overlay org-table-coordinate-overlays)
11397 (setq org-table-coordinate-overlays nil)))
11399 (defun org-table-toggle-formula-debugger ()
11400 "Toggle the formula debugger in tables."
11401 (interactive)
11402 (setq org-table-formula-debug (not org-table-formula-debug))
11403 (message "Formula debugging has been turned %s"
11404 (if org-table-formula-debug "on" "off")))
11406 ;;; The orgtbl minor mode
11408 ;; Define a minor mode which can be used in other modes in order to
11409 ;; integrate the org-mode table editor.
11411 ;; This is really a hack, because the org-mode table editor uses several
11412 ;; keys which normally belong to the major mode, for example the TAB and
11413 ;; RET keys. Here is how it works: The minor mode defines all the keys
11414 ;; necessary to operate the table editor, but wraps the commands into a
11415 ;; function which tests if the cursor is currently inside a table. If that
11416 ;; is the case, the table editor command is executed. However, when any of
11417 ;; those keys is used outside a table, the function uses `key-binding' to
11418 ;; look up if the key has an associated command in another currently active
11419 ;; keymap (minor modes, major mode, global), and executes that command.
11420 ;; There might be problems if any of the keys used by the table editor is
11421 ;; otherwise used as a prefix key.
11423 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
11424 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
11425 ;; addresses this by checking explicitly for both bindings.
11427 ;; The optimized version (see variable `orgtbl-optimized') takes over
11428 ;; all keys which are bound to `self-insert-command' in the *global map*.
11429 ;; Some modes bind other commands to simple characters, for example
11430 ;; AUCTeX binds the double quote to `Tex-insert-quote'. With orgtbl-mode
11431 ;; active, this binding is ignored inside tables and replaced with a
11432 ;; modified self-insert.
11434 (defvar orgtbl-mode nil
11435 "Variable controlling `orgtbl-mode', a minor mode enabling the `org-mode'
11436 table editor in arbitrary modes.")
11437 (make-variable-buffer-local 'orgtbl-mode)
11439 (defvar orgtbl-mode-map (make-keymap)
11440 "Keymap for `orgtbl-mode'.")
11442 ;;;###autoload
11443 (defun turn-on-orgtbl ()
11444 "Unconditionally turn on `orgtbl-mode'."
11445 (orgtbl-mode 1))
11447 (defvar org-old-auto-fill-inhibit-regexp nil
11448 "Local variable used by `orgtbl-mode'")
11450 (defconst orgtbl-line-start-regexp "[ \t]*\\(|\\|#\\+\\(TBLFM\\|ORGTBL\\):\\)"
11451 "Matches a line belonging to an orgtbl.")
11453 (defconst orgtbl-extra-font-lock-keywords
11454 (list (list (concat "^" orgtbl-line-start-regexp ".*")
11455 0 (quote 'org-table) 'prepend))
11456 "Extra font-lock-keywords to be added when orgtbl-mode is active.")
11458 ;;;###autoload
11459 (defun orgtbl-mode (&optional arg)
11460 "The `org-mode' table editor as a minor mode for use in other modes."
11461 (interactive)
11462 (if (org-mode-p)
11463 ;; Exit without error, in case some hook functions calls this
11464 ;; by accident in org-mode.
11465 (message "Orgtbl-mode is not useful in org-mode, command ignored")
11466 (setq orgtbl-mode
11467 (if arg (> (prefix-numeric-value arg) 0) (not orgtbl-mode)))
11468 (if orgtbl-mode
11469 (progn
11470 (and (orgtbl-setup) (defun orgtbl-setup () nil))
11471 ;; Make sure we are first in minor-mode-map-alist
11472 (let ((c (assq 'orgtbl-mode minor-mode-map-alist)))
11473 (and c (setq minor-mode-map-alist
11474 (cons c (delq c minor-mode-map-alist)))))
11475 (org-set-local (quote org-table-may-need-update) t)
11476 (org-add-hook 'before-change-functions 'org-before-change-function
11477 nil 'local)
11478 (org-set-local 'org-old-auto-fill-inhibit-regexp
11479 auto-fill-inhibit-regexp)
11480 (org-set-local 'auto-fill-inhibit-regexp
11481 (if auto-fill-inhibit-regexp
11482 (concat orgtbl-line-start-regexp "\\|"
11483 auto-fill-inhibit-regexp)
11484 orgtbl-line-start-regexp))
11485 (org-add-to-invisibility-spec '(org-cwidth))
11486 (when (fboundp 'font-lock-add-keywords)
11487 (font-lock-add-keywords nil orgtbl-extra-font-lock-keywords)
11488 (org-restart-font-lock))
11489 (easy-menu-add orgtbl-mode-menu)
11490 (run-hooks 'orgtbl-mode-hook))
11491 (setq auto-fill-inhibit-regexp org-old-auto-fill-inhibit-regexp)
11492 (org-cleanup-narrow-column-properties)
11493 (org-remove-from-invisibility-spec '(org-cwidth))
11494 (remove-hook 'before-change-functions 'org-before-change-function t)
11495 (when (fboundp 'font-lock-remove-keywords)
11496 (font-lock-remove-keywords nil orgtbl-extra-font-lock-keywords)
11497 (org-restart-font-lock))
11498 (easy-menu-remove orgtbl-mode-menu)
11499 (force-mode-line-update 'all))))
11501 (defun org-cleanup-narrow-column-properties ()
11502 "Remove all properties related to narrow-column invisibility."
11503 (let ((s 1))
11504 (while (setq s (text-property-any s (point-max)
11505 'display org-narrow-column-arrow))
11506 (remove-text-properties s (1+ s) '(display t)))
11507 (setq s 1)
11508 (while (setq s (text-property-any s (point-max) 'org-cwidth 1))
11509 (remove-text-properties s (1+ s) '(org-cwidth t)))
11510 (setq s 1)
11511 (while (setq s (text-property-any s (point-max) 'invisible 'org-cwidth))
11512 (remove-text-properties s (1+ s) '(invisible t)))))
11514 ;; Install it as a minor mode.
11515 (put 'orgtbl-mode :included t)
11516 (put 'orgtbl-mode :menu-tag "Org Table Mode")
11517 (add-minor-mode 'orgtbl-mode " OrgTbl" orgtbl-mode-map)
11519 (defun orgtbl-make-binding (fun n &rest keys)
11520 "Create a function for binding in the table minor mode.
11521 FUN is the command to call inside a table. N is used to create a unique
11522 command name. KEYS are keys that should be checked in for a command
11523 to execute outside of tables."
11524 (eval
11525 (list 'defun
11526 (intern (concat "orgtbl-hijacker-command-" (int-to-string n)))
11527 '(arg)
11528 (concat "In tables, run `" (symbol-name fun) "'.\n"
11529 "Outside of tables, run the binding of `"
11530 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
11531 "'.")
11532 '(interactive "p")
11533 (list 'if
11534 '(org-at-table-p)
11535 (list 'call-interactively (list 'quote fun))
11536 (list 'let '(orgtbl-mode)
11537 (list 'call-interactively
11538 (append '(or)
11539 (mapcar (lambda (k)
11540 (list 'key-binding k))
11541 keys)
11542 '('orgtbl-error))))))))
11544 (defun orgtbl-error ()
11545 "Error when there is no default binding for a table key."
11546 (interactive)
11547 (error "This key has no function outside tables"))
11549 (defun orgtbl-setup ()
11550 "Setup orgtbl keymaps."
11551 (let ((nfunc 0)
11552 (bindings
11553 (list
11554 '([(meta shift left)] org-table-delete-column)
11555 '([(meta left)] org-table-move-column-left)
11556 '([(meta right)] org-table-move-column-right)
11557 '([(meta shift right)] org-table-insert-column)
11558 '([(meta shift up)] org-table-kill-row)
11559 '([(meta shift down)] org-table-insert-row)
11560 '([(meta up)] org-table-move-row-up)
11561 '([(meta down)] org-table-move-row-down)
11562 '("\C-c\C-w" org-table-cut-region)
11563 '("\C-c\M-w" org-table-copy-region)
11564 '("\C-c\C-y" org-table-paste-rectangle)
11565 '("\C-c-" org-table-insert-hline)
11566 '("\C-c}" org-table-toggle-coordinate-overlays)
11567 '("\C-c{" org-table-toggle-formula-debugger)
11568 '("\C-m" org-table-next-row)
11569 '([(shift return)] org-table-copy-down)
11570 '("\C-c\C-q" org-table-wrap-region)
11571 '("\C-c?" org-table-field-info)
11572 '("\C-c " org-table-blank-field)
11573 '("\C-c+" org-table-sum)
11574 '("\C-c=" org-table-eval-formula)
11575 '("\C-c'" org-table-edit-formulas)
11576 '("\C-c`" org-table-edit-field)
11577 '("\C-c*" org-table-recalculate)
11578 '("\C-c|" org-table-create-or-convert-from-region)
11579 '("\C-c^" org-table-sort-lines)
11580 '([(control ?#)] org-table-rotate-recalc-marks)))
11581 elt key fun cmd)
11582 (while (setq elt (pop bindings))
11583 (setq nfunc (1+ nfunc))
11584 (setq key (org-key (car elt))
11585 fun (nth 1 elt)
11586 cmd (orgtbl-make-binding fun nfunc key))
11587 (org-defkey orgtbl-mode-map key cmd))
11589 ;; Special treatment needed for TAB and RET
11590 (org-defkey orgtbl-mode-map [(return)]
11591 (orgtbl-make-binding 'orgtbl-ret 100 [(return)] "\C-m"))
11592 (org-defkey orgtbl-mode-map "\C-m"
11593 (orgtbl-make-binding 'orgtbl-ret 101 "\C-m" [(return)]))
11595 (org-defkey orgtbl-mode-map [(tab)]
11596 (orgtbl-make-binding 'orgtbl-tab 102 [(tab)] "\C-i"))
11597 (org-defkey orgtbl-mode-map "\C-i"
11598 (orgtbl-make-binding 'orgtbl-tab 103 "\C-i" [(tab)]))
11600 (org-defkey orgtbl-mode-map [(shift tab)]
11601 (orgtbl-make-binding 'org-table-previous-field 104
11602 [(shift tab)] [(tab)] "\C-i"))
11604 (org-defkey orgtbl-mode-map "\M-\C-m"
11605 (orgtbl-make-binding 'org-table-wrap-region 105
11606 "\M-\C-m" [(meta return)]))
11607 (org-defkey orgtbl-mode-map [(meta return)]
11608 (orgtbl-make-binding 'org-table-wrap-region 106
11609 [(meta return)] "\M-\C-m"))
11611 (org-defkey orgtbl-mode-map "\C-c\C-c" 'orgtbl-ctrl-c-ctrl-c)
11612 (when orgtbl-optimized
11613 ;; If the user wants maximum table support, we need to hijack
11614 ;; some standard editing functions
11615 (org-remap orgtbl-mode-map
11616 'self-insert-command 'orgtbl-self-insert-command
11617 'delete-char 'org-delete-char
11618 'delete-backward-char 'org-delete-backward-char)
11619 (org-defkey orgtbl-mode-map "|" 'org-force-self-insert))
11620 (easy-menu-define orgtbl-mode-menu orgtbl-mode-map "OrgTbl menu"
11621 '("OrgTbl"
11622 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p) :keys "C-c C-c"]
11623 ["Next Field" org-cycle :active (org-at-table-p) :keys "TAB"]
11624 ["Previous Field" org-shifttab :active (org-at-table-p) :keys "S-TAB"]
11625 ["Next Row" org-return :active (org-at-table-p) :keys "RET"]
11626 "--"
11627 ["Blank Field" org-table-blank-field :active (org-at-table-p) :keys "C-c SPC"]
11628 ["Edit Field" org-table-edit-field :active (org-at-table-p) :keys "C-c ` "]
11629 ["Copy Field from Above"
11630 org-table-copy-down :active (org-at-table-p) :keys "S-RET"]
11631 "--"
11632 ("Column"
11633 ["Move Column Left" org-metaleft :active (org-at-table-p) :keys "M-<left>"]
11634 ["Move Column Right" org-metaright :active (org-at-table-p) :keys "M-<right>"]
11635 ["Delete Column" org-shiftmetaleft :active (org-at-table-p) :keys "M-S-<left>"]
11636 ["Insert Column" org-shiftmetaright :active (org-at-table-p) :keys "M-S-<right>"])
11637 ("Row"
11638 ["Move Row Up" org-metaup :active (org-at-table-p) :keys "M-<up>"]
11639 ["Move Row Down" org-metadown :active (org-at-table-p) :keys "M-<down>"]
11640 ["Delete Row" org-shiftmetaup :active (org-at-table-p) :keys "M-S-<up>"]
11641 ["Insert Row" org-shiftmetadown :active (org-at-table-p) :keys "M-S-<down>"]
11642 ["Sort lines in region" org-table-sort-lines :active (org-at-table-p) :keys "C-c ^"]
11643 "--"
11644 ["Insert Hline" org-table-insert-hline :active (org-at-table-p) :keys "C-c -"])
11645 ("Rectangle"
11646 ["Copy Rectangle" org-copy-special :active (org-at-table-p)]
11647 ["Cut Rectangle" org-cut-special :active (org-at-table-p)]
11648 ["Paste Rectangle" org-paste-special :active (org-at-table-p)]
11649 ["Fill Rectangle" org-table-wrap-region :active (org-at-table-p)])
11650 "--"
11651 ("Radio tables"
11652 ["Insert table template" orgtbl-insert-radio-table
11653 (assq major-mode orgtbl-radio-table-templates)]
11654 ["Comment/uncomment table" orgtbl-toggle-comment t])
11655 "--"
11656 ["Set Column Formula" org-table-eval-formula :active (org-at-table-p) :keys "C-c ="]
11657 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
11658 ["Edit Formulas" org-table-edit-formulas :active (org-at-table-p) :keys "C-c '"]
11659 ["Recalculate line" org-table-recalculate :active (org-at-table-p) :keys "C-c *"]
11660 ["Recalculate all" (org-table-recalculate '(4)) :active (org-at-table-p) :keys "C-u C-c *"]
11661 ["Iterate all" (org-table-recalculate '(16)) :active (org-at-table-p) :keys "C-u C-u C-c *"]
11662 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks :active (org-at-table-p) :keys "C-c #"]
11663 ["Sum Column/Rectangle" org-table-sum
11664 :active (or (org-at-table-p) (org-region-active-p)) :keys "C-c +"]
11665 ["Which Column?" org-table-current-column :active (org-at-table-p) :keys "C-c ?"]
11666 ["Debug Formulas"
11667 org-table-toggle-formula-debugger :active (org-at-table-p)
11668 :keys "C-c {"
11669 :style toggle :selected org-table-formula-debug]
11670 ["Show Col/Row Numbers"
11671 org-table-toggle-coordinate-overlays :active (org-at-table-p)
11672 :keys "C-c }"
11673 :style toggle :selected org-table-overlay-coordinates]
11677 (defun orgtbl-ctrl-c-ctrl-c (arg)
11678 "If the cursor is inside a table, realign the table.
11679 It it is a table to be sent away to a receiver, do it.
11680 With prefix arg, also recompute table."
11681 (interactive "P")
11682 (let ((pos (point)) action)
11683 (save-excursion
11684 (beginning-of-line 1)
11685 (setq action (cond ((looking-at "#\\+ORGTBL:.*\n[ \t]*|") (match-end 0))
11686 ((looking-at "[ \t]*|") pos)
11687 ((looking-at "#\\+TBLFM:") 'recalc))))
11688 (cond
11689 ((integerp action)
11690 (goto-char action)
11691 (org-table-maybe-eval-formula)
11692 (if arg
11693 (call-interactively 'org-table-recalculate)
11694 (org-table-maybe-recalculate-line))
11695 (call-interactively 'org-table-align)
11696 (orgtbl-send-table 'maybe))
11697 ((eq action 'recalc)
11698 (save-excursion
11699 (beginning-of-line 1)
11700 (skip-chars-backward " \r\n\t")
11701 (if (org-at-table-p)
11702 (org-call-with-arg 'org-table-recalculate t))))
11703 (t (let (orgtbl-mode)
11704 (call-interactively (key-binding "\C-c\C-c")))))))
11706 (defun orgtbl-tab (arg)
11707 "Justification and field motion for `orgtbl-mode'."
11708 (interactive "P")
11709 (if arg (org-table-edit-field t)
11710 (org-table-justify-field-maybe)
11711 (org-table-next-field)))
11713 (defun orgtbl-ret ()
11714 "Justification and field motion for `orgtbl-mode'."
11715 (interactive)
11716 (org-table-justify-field-maybe)
11717 (org-table-next-row))
11719 (defun orgtbl-self-insert-command (N)
11720 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
11721 If the cursor is in a table looking at whitespace, the whitespace is
11722 overwritten, and the table is not marked as requiring realignment."
11723 (interactive "p")
11724 (if (and (org-at-table-p)
11726 (and org-table-auto-blank-field
11727 (member last-command
11728 '(orgtbl-hijacker-command-100
11729 orgtbl-hijacker-command-101
11730 orgtbl-hijacker-command-102
11731 orgtbl-hijacker-command-103
11732 orgtbl-hijacker-command-104
11733 orgtbl-hijacker-command-105))
11734 (org-table-blank-field))
11736 (eq N 1)
11737 (looking-at "[^|\n]* +|"))
11738 (let (org-table-may-need-update)
11739 (goto-char (1- (match-end 0)))
11740 (delete-backward-char 1)
11741 (goto-char (match-beginning 0))
11742 (self-insert-command N))
11743 (setq org-table-may-need-update t)
11744 (let (orgtbl-mode)
11745 (call-interactively (key-binding (vector last-input-event))))))
11747 (defun org-force-self-insert (N)
11748 "Needed to enforce self-insert under remapping."
11749 (interactive "p")
11750 (self-insert-command N))
11752 (defvar orgtbl-exp-regexp "^\\([-+]?[0-9][0-9.]*\\)[eE]\\([-+]?[0-9]+\\)$"
11753 "Regula expression matching exponentials as produced by calc.")
11755 (defvar org-table-clean-did-remove-column nil)
11757 (defun orgtbl-export (table target)
11758 (let ((func (intern (concat "orgtbl-to-" (symbol-name target))))
11759 (lines (org-split-string table "[ \t]*\n[ \t]*"))
11760 org-table-last-alignment org-table-last-column-widths
11761 maxcol column)
11762 (if (not (fboundp func))
11763 (error "Cannot export orgtbl table to %s" target))
11764 (setq lines (org-table-clean-before-export lines))
11765 (setq table
11766 (mapcar
11767 (lambda (x)
11768 (if (string-match org-table-hline-regexp x)
11769 'hline
11770 (org-split-string (org-trim x) "\\s-*|\\s-*")))
11771 lines))
11772 (setq maxcol (apply 'max (mapcar (lambda (x) (if (listp x) (length x) 0))
11773 table)))
11774 (loop for i from (1- maxcol) downto 0 do
11775 (setq column (mapcar (lambda (x) (if (listp x) (nth i x) nil)) table))
11776 (setq column (delq nil column))
11777 (push (apply 'max (mapcar 'string-width column)) org-table-last-column-widths)
11778 (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))
11779 (funcall func table nil)))
11781 (defun orgtbl-send-table (&optional maybe)
11782 "Send a tranformed version of this table to the receiver position.
11783 With argument MAYBE, fail quietly if no transformation is defined for
11784 this table."
11785 (interactive)
11786 (catch 'exit
11787 (unless (org-at-table-p) (error "Not at a table"))
11788 ;; when non-interactive, we assume align has just happened.
11789 (when (interactive-p) (org-table-align))
11790 (save-excursion
11791 (goto-char (org-table-begin))
11792 (beginning-of-line 0)
11793 (unless (looking-at "#\\+ORGTBL: *SEND +\\([a-zA-Z0-9_]+\\) +\\([^ \t\r\n]+\\)\\( +.*\\)?")
11794 (if maybe
11795 (throw 'exit nil)
11796 (error "Don't know how to transform this table."))))
11797 (let* ((name (match-string 1))
11799 (transform (intern (match-string 2)))
11800 (params (if (match-end 3) (read (concat "(" (match-string 3) ")"))))
11801 (skip (plist-get params :skip))
11802 (skipcols (plist-get params :skipcols))
11803 (txt (buffer-substring-no-properties
11804 (org-table-begin) (org-table-end)))
11805 (lines (nthcdr (or skip 0) (org-split-string txt "[ \t]*\n[ \t]*")))
11806 (lines (org-table-clean-before-export lines))
11807 (i0 (if org-table-clean-did-remove-column 2 1))
11808 (table (mapcar
11809 (lambda (x)
11810 (if (string-match org-table-hline-regexp x)
11811 'hline
11812 (org-remove-by-index
11813 (org-split-string (org-trim x) "\\s-*|\\s-*")
11814 skipcols i0)))
11815 lines))
11816 (fun (if (= i0 2) 'cdr 'identity))
11817 (org-table-last-alignment
11818 (org-remove-by-index (funcall fun org-table-last-alignment)
11819 skipcols i0))
11820 (org-table-last-column-widths
11821 (org-remove-by-index (funcall fun org-table-last-column-widths)
11822 skipcols i0)))
11824 (unless (fboundp transform)
11825 (error "No such transformation function %s" transform))
11826 (setq txt (funcall transform table params))
11827 ;; Find the insertion place
11828 (save-excursion
11829 (goto-char (point-min))
11830 (unless (re-search-forward
11831 (concat "BEGIN RECEIVE ORGTBL +" name "\\([ \t]\\|$\\)") nil t)
11832 (error "Don't know where to insert translated table"))
11833 (goto-char (match-beginning 0))
11834 (beginning-of-line 2)
11835 (setq beg (point))
11836 (unless (re-search-forward (concat "END RECEIVE ORGTBL +" name) nil t)
11837 (error "Cannot find end of insertion region"))
11838 (beginning-of-line 1)
11839 (delete-region beg (point))
11840 (goto-char beg)
11841 (insert txt "\n"))
11842 (message "Table converted and installed at receiver location"))))
11844 (defun org-remove-by-index (list indices &optional i0)
11845 "Remove the elements in LIST with indices in INDICES.
11846 First element has index 0, or I0 if given."
11847 (if (not indices)
11848 list
11849 (if (integerp indices) (setq indices (list indices)))
11850 (setq i0 (1- (or i0 0)))
11851 (delq :rm (mapcar (lambda (x)
11852 (setq i0 (1+ i0))
11853 (if (memq i0 indices) :rm x))
11854 list))))
11856 (defun orgtbl-toggle-comment ()
11857 "Comment or uncomment the orgtbl at point."
11858 (interactive)
11859 (let* ((re1 (concat "^" (regexp-quote comment-start) orgtbl-line-start-regexp))
11860 (re2 (concat "^" orgtbl-line-start-regexp))
11861 (commented (save-excursion (beginning-of-line 1)
11862 (cond ((looking-at re1) t)
11863 ((looking-at re2) nil)
11864 (t (error "Not at an org table")))))
11865 (re (if commented re1 re2))
11866 beg end)
11867 (save-excursion
11868 (beginning-of-line 1)
11869 (while (looking-at re) (beginning-of-line 0))
11870 (beginning-of-line 2)
11871 (setq beg (point))
11872 (while (looking-at re) (beginning-of-line 2))
11873 (setq end (point)))
11874 (comment-region beg end (if commented '(4) nil))))
11876 (defun orgtbl-insert-radio-table ()
11877 "Insert a radio table template appropriate for this major mode."
11878 (interactive)
11879 (let* ((e (assq major-mode orgtbl-radio-table-templates))
11880 (txt (nth 1 e))
11881 name pos)
11882 (unless e (error "No radio table setup defined for %s" major-mode))
11883 (setq name (read-string "Table name: "))
11884 (while (string-match "%n" txt)
11885 (setq txt (replace-match name t t txt)))
11886 (or (bolp) (insert "\n"))
11887 (setq pos (point))
11888 (insert txt)
11889 (goto-char pos)))
11891 (defun org-get-param (params header i sym &optional hsym)
11892 "Get parameter value for symbol SYM.
11893 If this is a header line, actually get the value for the symbol with an
11894 additional \"h\" inserted after the colon.
11895 If the value is a protperty list, get the element for the current column.
11896 Assumes variables VAL, PARAMS, HEAD and I to be scoped into the function."
11897 (let ((val (plist-get params sym)))
11898 (and hsym header (setq val (or (plist-get params hsym) val)))
11899 (if (consp val) (plist-get val i) val)))
11901 (defun orgtbl-to-generic (table params)
11902 "Convert the orgtbl-mode TABLE to some other format.
11903 This generic routine can be used for many standard cases.
11904 TABLE is a list, each entry either the symbol `hline' for a horizontal
11905 separator line, or a list of fields for that line.
11906 PARAMS is a property list of parameters that can influence the conversion.
11907 For the generic converter, some parameters are obligatory: You need to
11908 specify either :lfmt, or all of (:lstart :lend :sep). If you do not use
11909 :splice, you must have :tstart and :tend.
11911 Valid parameters are
11913 :tstart String to start the table. Ignored when :splice is t.
11914 :tend String to end the table. Ignored when :splice is t.
11916 :splice When set to t, return only table body lines, don't wrap
11917 them into :tstart and :tend. Default is nil.
11919 :hline String to be inserted on horizontal separation lines.
11920 May be nil to ignore hlines.
11922 :lstart String to start a new table line.
11923 :lend String to end a table line
11924 :sep Separator between two fields
11925 :lfmt Format for entire line, with enough %s to capture all fields.
11926 If this is present, :lstart, :lend, and :sep are ignored.
11927 :fmt A format to be used to wrap the field, should contain
11928 %s for the original field value. For example, to wrap
11929 everything in dollars, you could use :fmt \"$%s$\".
11930 This may also be a property list with column numbers and
11931 formats. For example :fmt (2 \"$%s$\" 4 \"%s%%\")
11933 :hlstart :hlend :hlsep :hlfmt :hfmt
11934 Same as above, specific for the header lines in the table.
11935 All lines before the first hline are treated as header.
11936 If any of these is not present, the data line value is used.
11938 :efmt Use this format to print numbers with exponentials.
11939 The format should have %s twice for inserting mantissa
11940 and exponent, for example \"%s\\\\times10^{%s}\". This
11941 may also be a property list with column numbers and
11942 formats. :fmt will still be applied after :efmt.
11944 In addition to this, the parameters :skip and :skipcols are always handled
11945 directly by `orgtbl-send-table'. See manual."
11946 (interactive)
11947 (let* ((p params)
11948 (splicep (plist-get p :splice))
11949 (hline (plist-get p :hline))
11950 rtn line i fm efm lfmt h)
11952 ;; Do we have a header?
11953 (if (and (not splicep) (listp (car table)) (memq 'hline table))
11954 (setq h t))
11956 ;; Put header
11957 (unless splicep
11958 (push (or (plist-get p :tstart) "ERROR: no :tstart") rtn))
11960 ;; Now loop over all lines
11961 (while (setq line (pop table))
11962 (if (eq line 'hline)
11963 ;; A horizontal separator line
11964 (progn (if hline (push hline rtn))
11965 (setq h nil)) ; no longer in header
11966 ;; A normal line. Convert the fields, push line onto the result list
11967 (setq i 0)
11968 (setq line
11969 (mapcar
11970 (lambda (f)
11971 (setq i (1+ i)
11972 fm (org-get-param p h i :fmt :hfmt)
11973 efm (org-get-param p h i :efmt))
11974 (if (and efm (string-match orgtbl-exp-regexp f))
11975 (setq f (format
11976 efm (match-string 1 f) (match-string 2 f))))
11977 (if fm (setq f (format fm f)))
11979 line))
11980 (if (setq lfmt (org-get-param p h i :lfmt :hlfmt))
11981 (push (apply 'format lfmt line) rtn)
11982 (push (concat
11983 (org-get-param p h i :lstart :hlstart)
11984 (mapconcat 'identity line (org-get-param p h i :sep :hsep))
11985 (org-get-param p h i :lend :hlend))
11986 rtn))))
11988 (unless splicep
11989 (push (or (plist-get p :tend) "ERROR: no :tend") rtn))
11991 (mapconcat 'identity (nreverse rtn) "\n")))
11993 (defun orgtbl-to-latex (table params)
11994 "Convert the orgtbl-mode TABLE to LaTeX.
11995 TABLE is a list, each entry either the symbol `hline' for a horizontal
11996 separator line, or a list of fields for that line.
11997 PARAMS is a property list of parameters that can influence the conversion.
11998 Supports all parameters from `orgtbl-to-generic'. Most important for
11999 LaTeX are:
12001 :splice When set to t, return only table body lines, don't wrap
12002 them into a tabular environment. Default is nil.
12004 :fmt A format to be used to wrap the field, should contain %s for the
12005 original field value. For example, to wrap everything in dollars,
12006 use :fmt \"$%s$\". This may also be a property list with column
12007 numbers and formats. For example :fmt (2 \"$%s$\" 4 \"%s%%\")
12009 :efmt Format for transforming numbers with exponentials. The format
12010 should have %s twice for inserting mantissa and exponent, for
12011 example \"%s\\\\times10^{%s}\". LaTeX default is \"%s\\\\,(%s)\".
12012 This may also be a property list with column numbers and formats.
12014 The general parameters :skip and :skipcols have already been applied when
12015 this function is called."
12016 (let* ((alignment (mapconcat (lambda (x) (if x "r" "l"))
12017 org-table-last-alignment ""))
12018 (params2
12019 (list
12020 :tstart (concat "\\begin{tabular}{" alignment "}")
12021 :tend "\\end{tabular}"
12022 :lstart "" :lend " \\\\" :sep " & "
12023 :efmt "%s\\,(%s)" :hline "\\hline")))
12024 (orgtbl-to-generic table (org-combine-plists params2 params))))
12026 (defun orgtbl-to-html (table params)
12027 "Convert the orgtbl-mode TABLE to LaTeX.
12028 TABLE is a list, each entry either the symbol `hline' for a horizontal
12029 separator line, or a list of fields for that line.
12030 PARAMS is a property list of parameters that can influence the conversion.
12031 Currently this function recognizes the following parameters:
12033 :splice When set to t, return only table body lines, don't wrap
12034 them into a <table> environment. Default is nil.
12036 The general parameters :skip and :skipcols have already been applied when
12037 this function is called. The function does *not* use `orgtbl-to-generic',
12038 so you cannot specify parameters for it."
12039 (let* ((splicep (plist-get params :splice))
12040 html)
12041 ;; Just call the formatter we already have
12042 ;; We need to make text lines for it, so put the fields back together.
12043 (setq html (org-format-org-table-html
12044 (mapcar
12045 (lambda (x)
12046 (if (eq x 'hline)
12047 "|----+----|"
12048 (concat "| " (mapconcat 'identity x " | ") " |")))
12049 table)
12050 splicep))
12051 (if (string-match "\n+\\'" html)
12052 (setq html (replace-match "" t t html)))
12053 html))
12055 (defun orgtbl-to-texinfo (table params)
12056 "Convert the orgtbl-mode TABLE to TeXInfo.
12057 TABLE is a list, each entry either the symbol `hline' for a horizontal
12058 separator line, or a list of fields for that line.
12059 PARAMS is a property list of parameters that can influence the conversion.
12060 Supports all parameters from `orgtbl-to-generic'. Most important for
12061 TeXInfo are:
12063 :splice nil/t When set to t, return only table body lines, don't wrap
12064 them into a multitable environment. Default is nil.
12066 :fmt fmt A format to be used to wrap the field, should contain
12067 %s for the original field value. For example, to wrap
12068 everything in @kbd{}, you could use :fmt \"@kbd{%s}\".
12069 This may also be a property list with column numbers and
12070 formats. For example :fmt (2 \"@kbd{%s}\" 4 \"@code{%s}\").
12072 :cf \"f1 f2..\" The column fractions for the table. By default these
12073 are computed automatically from the width of the columns
12074 under org-mode.
12076 The general parameters :skip and :skipcols have already been applied when
12077 this function is called."
12078 (let* ((total (float (apply '+ org-table-last-column-widths)))
12079 (colfrac (or (plist-get params :cf)
12080 (mapconcat
12081 (lambda (x) (format "%.3f" (/ (float x) total)))
12082 org-table-last-column-widths " ")))
12083 (params2
12084 (list
12085 :tstart (concat "@multitable @columnfractions " colfrac)
12086 :tend "@end multitable"
12087 :lstart "@item " :lend "" :sep " @tab "
12088 :hlstart "@headitem ")))
12089 (orgtbl-to-generic table (org-combine-plists params2 params))))
12091 ;;;; Link Stuff
12093 ;;; Link abbreviations
12095 (defun org-link-expand-abbrev (link)
12096 "Apply replacements as defined in `org-link-abbrev-alist."
12097 (if (string-match "^\\([a-zA-Z][-_a-zA-Z0-9]*\\)\\(::?\\(.*\\)\\)?$" link)
12098 (let* ((key (match-string 1 link))
12099 (as (or (assoc key org-link-abbrev-alist-local)
12100 (assoc key org-link-abbrev-alist)))
12101 (tag (and (match-end 2) (match-string 3 link)))
12102 rpl)
12103 (if (not as)
12104 link
12105 (setq rpl (cdr as))
12106 (cond
12107 ((symbolp rpl) (funcall rpl tag))
12108 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
12109 (t (concat rpl tag)))))
12110 link))
12112 ;;; Storing and inserting links
12114 (defvar org-insert-link-history nil
12115 "Minibuffer history for links inserted with `org-insert-link'.")
12117 (defvar org-stored-links nil
12118 "Contains the links stored with `org-store-link'.")
12120 (defvar org-store-link-plist nil
12121 "Plist with info about the most recently link created with `org-store-link'.")
12123 (defvar org-link-protocols nil
12124 "Link protocols added to Org-mode using `org-add-link-type'.")
12126 (defvar org-store-link-functions nil
12127 "List of functions that are called to create and store a link.
12128 Each function will be called in turn until one returns a non-nil
12129 value. Each function should check if it is responsible for creating
12130 this link (for example by looking at the major mode).
12131 If not, it must exit and return nil.
12132 If yes, it should return a non-nil value after a calling
12133 `org-store-link-props' with a list of properties and values.
12134 Special properties are:
12136 :type The link prefix. like \"http\". This must be given.
12137 :link The link, like \"http://www.astro.uva.nl/~dominik\".
12138 This is obligatory as well.
12139 :description Optional default description for the second pair
12140 of brackets in an Org-mode link. The user can still change
12141 this when inserting this link into an Org-mode buffer.
12143 In addition to these, any additional properties can be specified
12144 and then used in remember templates.")
12146 (defun org-add-link-type (type &optional follow publish)
12147 "Add TYPE to the list of `org-link-types'.
12148 Re-compute all regular expressions depending on `org-link-types'
12149 FOLLOW and PUBLISH are two functions. Both take the link path as
12150 an argument.
12151 FOLLOW should do whatever is necessary to follow the link, for example
12152 to find a file or display a mail message.
12154 PUBLISH takes the path and retuns the string that should be used when
12155 this document is published. FIMXE: This is actually not yet implemented."
12156 (add-to-list 'org-link-types type t)
12157 (org-make-link-regexps)
12158 (add-to-list 'org-link-protocols
12159 (list type follow publish)))
12161 (defun org-add-agenda-custom-command (entry)
12162 "Replace or add a command in `org-agenda-custom-commands'.
12163 This is mostly for hacking and trying a new command - once the command
12164 works you probably want to add it to `org-agenda-custom-commands' for good."
12165 (let ((ass (assoc (car entry) org-agenda-custom-commands)))
12166 (if ass
12167 (setcdr ass (cdr entry))
12168 (push entry org-agenda-custom-commands))))
12170 ;;;###autoload
12171 (defun org-store-link (arg)
12172 "\\<org-mode-map>Store an org-link to the current location.
12173 This link is added to `org-stored-links' and can later be inserted
12174 into an org-buffer with \\[org-insert-link].
12176 For some link types, a prefix arg is interpreted:
12177 For links to usenet articles, arg negates `org-usenet-links-prefer-google'.
12178 For file links, arg negates `org-context-in-file-links'."
12179 (interactive "P")
12180 (require 'org-irc)
12181 (setq org-store-link-plist nil) ; reset
12182 (let (link cpltxt desc description search txt)
12183 (cond
12185 ((run-hook-with-args-until-success 'org-store-link-functions)
12186 (setq link (plist-get org-store-link-plist :link)
12187 desc (or (plist-get org-store-link-plist :description) link)))
12189 ((eq major-mode 'bbdb-mode)
12190 (let ((name (bbdb-record-name (bbdb-current-record)))
12191 (company (bbdb-record-getprop (bbdb-current-record) 'company)))
12192 (setq cpltxt (concat "bbdb:" (or name company))
12193 link (org-make-link cpltxt))
12194 (org-store-link-props :type "bbdb" :name name :company company)))
12196 ((eq major-mode 'Info-mode)
12197 (setq link (org-make-link "info:"
12198 (file-name-nondirectory Info-current-file)
12199 ":" Info-current-node))
12200 (setq cpltxt (concat (file-name-nondirectory Info-current-file)
12201 ":" Info-current-node))
12202 (org-store-link-props :type "info" :file Info-current-file
12203 :node Info-current-node))
12205 ((eq major-mode 'calendar-mode)
12206 (let ((cd (calendar-cursor-to-date)))
12207 (setq link
12208 (format-time-string
12209 (car org-time-stamp-formats)
12210 (apply 'encode-time
12211 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
12212 nil nil nil))))
12213 (org-store-link-props :type "calendar" :date cd)))
12215 ((or (eq major-mode 'vm-summary-mode)
12216 (eq major-mode 'vm-presentation-mode))
12217 (and (eq major-mode 'vm-presentation-mode) (vm-summarize))
12218 (vm-follow-summary-cursor)
12219 (save-excursion
12220 (vm-select-folder-buffer)
12221 (let* ((message (car vm-message-pointer))
12222 (folder buffer-file-name)
12223 (subject (vm-su-subject message))
12224 (to (vm-get-header-contents message "To"))
12225 (from (vm-get-header-contents message "From"))
12226 (message-id (vm-su-message-id message)))
12227 (org-store-link-props :type "vm" :from from :to to :subject subject
12228 :message-id message-id)
12229 (setq message-id (org-remove-angle-brackets message-id))
12230 (setq folder (abbreviate-file-name folder))
12231 (if (string-match (concat "^" (regexp-quote vm-folder-directory))
12232 folder)
12233 (setq folder (replace-match "" t t folder)))
12234 (setq cpltxt (org-email-link-description))
12235 (setq link (org-make-link "vm:" folder "#" message-id)))))
12237 ((eq major-mode 'wl-summary-mode)
12238 (let* ((msgnum (wl-summary-message-number))
12239 (message-id (elmo-message-field wl-summary-buffer-elmo-folder
12240 msgnum 'message-id))
12241 (wl-message-entity
12242 (if (fboundp 'elmo-message-entity)
12243 (elmo-message-entity
12244 wl-summary-buffer-elmo-folder msgnum)
12245 (elmo-msgdb-overview-get-entity
12246 msgnum (wl-summary-buffer-msgdb))))
12247 (from (wl-summary-line-from))
12248 (to (car (elmo-message-entity-field wl-message-entity 'to)))
12249 (subject (let (wl-thr-indent-string wl-parent-message-entity)
12250 (wl-summary-line-subject))))
12251 (org-store-link-props :type "wl" :from from :to to
12252 :subject subject :message-id message-id)
12253 (setq message-id (org-remove-angle-brackets message-id))
12254 (setq cpltxt (org-email-link-description))
12255 (setq link (org-make-link "wl:" wl-summary-buffer-folder-name
12256 "#" message-id))))
12258 ((or (equal major-mode 'mh-folder-mode)
12259 (equal major-mode 'mh-show-mode))
12260 (let ((from (org-mhe-get-header "From:"))
12261 (to (org-mhe-get-header "To:"))
12262 (message-id (org-mhe-get-header "Message-Id:"))
12263 (subject (org-mhe-get-header "Subject:")))
12264 (org-store-link-props :type "mh" :from from :to to
12265 :subject subject :message-id message-id)
12266 (setq cpltxt (org-email-link-description))
12267 (setq link (org-make-link "mhe:" (org-mhe-get-message-real-folder) "#"
12268 (org-remove-angle-brackets message-id)))))
12270 ((or (eq major-mode 'rmail-mode)
12271 (eq major-mode 'rmail-summary-mode))
12272 (save-window-excursion
12273 (save-restriction
12274 (when (eq major-mode 'rmail-summary-mode)
12275 (rmail-show-message rmail-current-message))
12276 (rmail-narrow-to-non-pruned-header)
12277 (let ((folder buffer-file-name)
12278 (message-id (mail-fetch-field "message-id"))
12279 (from (mail-fetch-field "from"))
12280 (to (mail-fetch-field "to"))
12281 (subject (mail-fetch-field "subject")))
12282 (org-store-link-props
12283 :type "rmail" :from from :to to
12284 :subject subject :message-id message-id)
12285 (setq message-id (org-remove-angle-brackets message-id))
12286 (setq cpltxt (org-email-link-description))
12287 (setq link (org-make-link "rmail:" folder "#" message-id)))
12288 (rmail-show-message rmail-current-message))))
12290 ((eq major-mode 'gnus-group-mode)
12291 (let ((group (cond ((fboundp 'gnus-group-group-name) ; depending on Gnus
12292 (gnus-group-group-name)) ; version
12293 ((fboundp 'gnus-group-name)
12294 (gnus-group-name))
12295 (t "???"))))
12296 (unless group (error "Not on a group"))
12297 (org-store-link-props :type "gnus" :group group)
12298 (setq cpltxt (concat
12299 (if (org-xor arg org-usenet-links-prefer-google)
12300 "http://groups.google.com/groups?group="
12301 "gnus:")
12302 group)
12303 link (org-make-link cpltxt))))
12305 ((memq major-mode '(gnus-summary-mode gnus-article-mode))
12306 (and (eq major-mode 'gnus-article-mode) (gnus-article-show-summary))
12307 (let* ((group gnus-newsgroup-name)
12308 (article (gnus-summary-article-number))
12309 (header (gnus-summary-article-header article))
12310 (from (mail-header-from header))
12311 (message-id (mail-header-id header))
12312 (date (mail-header-date header))
12313 (subject (gnus-summary-subject-string)))
12314 (org-store-link-props :type "gnus" :from from :subject subject
12315 :message-id message-id :group group)
12316 (setq cpltxt (org-email-link-description))
12317 (if (org-xor arg org-usenet-links-prefer-google)
12318 (setq link
12319 (concat
12320 cpltxt "\n "
12321 (format "http://groups.google.com/groups?as_umsgid=%s"
12322 (org-fixup-message-id-for-http message-id))))
12323 (setq link (org-make-link "gnus:" group
12324 "#" (number-to-string article))))))
12326 ((eq major-mode 'w3-mode)
12327 (setq cpltxt (url-view-url t)
12328 link (org-make-link cpltxt))
12329 (org-store-link-props :type "w3" :url (url-view-url t)))
12331 ((eq major-mode 'w3m-mode)
12332 (setq cpltxt (or w3m-current-title w3m-current-url)
12333 link (org-make-link w3m-current-url))
12334 (org-store-link-props :type "w3m" :url (url-view-url t)))
12336 ((setq search (run-hook-with-args-until-success
12337 'org-create-file-search-functions))
12338 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
12339 "::" search))
12340 (setq cpltxt (or description link)))
12342 ((eq major-mode 'image-mode)
12343 (setq cpltxt (concat "file:"
12344 (abbreviate-file-name buffer-file-name))
12345 link (org-make-link cpltxt))
12346 (org-store-link-props :type "image" :file buffer-file-name))
12348 ((eq major-mode 'dired-mode)
12349 ;; link to the file in the current line
12350 (setq cpltxt (concat "file:"
12351 (abbreviate-file-name
12352 (expand-file-name
12353 (dired-get-filename nil t))))
12354 link (org-make-link cpltxt)))
12356 ((and buffer-file-name (org-mode-p))
12357 ;; Just link to current headline
12358 (setq cpltxt (concat "file:"
12359 (abbreviate-file-name buffer-file-name)))
12360 ;; Add a context search string
12361 (when (org-xor org-context-in-file-links arg)
12362 ;; Check if we are on a target
12363 (if (org-in-regexp "<<\\(.*?\\)>>")
12364 (setq cpltxt (concat cpltxt "::" (match-string 1)))
12365 (setq txt (cond
12366 ((org-on-heading-p) nil)
12367 ((org-region-active-p)
12368 (buffer-substring (region-beginning) (region-end)))
12369 (t (buffer-substring (point-at-bol) (point-at-eol)))))
12370 (when (or (null txt) (string-match "\\S-" txt))
12371 (setq cpltxt
12372 (concat cpltxt "::" (org-make-org-heading-search-string txt))
12373 desc "NONE"))))
12374 (if (string-match "::\\'" cpltxt)
12375 (setq cpltxt (substring cpltxt 0 -2)))
12376 (setq link (org-make-link cpltxt)))
12378 ((buffer-file-name (buffer-base-buffer))
12379 ;; Just link to this file here.
12380 (setq cpltxt (concat "file:"
12381 (abbreviate-file-name
12382 (buffer-file-name (buffer-base-buffer)))))
12383 ;; Add a context string
12384 (when (org-xor org-context-in-file-links arg)
12385 (setq txt (if (org-region-active-p)
12386 (buffer-substring (region-beginning) (region-end))
12387 (buffer-substring (point-at-bol) (point-at-eol))))
12388 ;; Only use search option if there is some text.
12389 (when (string-match "\\S-" txt)
12390 (setq cpltxt
12391 (concat cpltxt "::" (org-make-org-heading-search-string txt))
12392 desc "NONE")))
12393 (setq link (org-make-link cpltxt)))
12395 ((interactive-p)
12396 (error "Cannot link to a buffer which is not visiting a file"))
12398 (t (setq link nil)))
12400 (if (consp link) (setq cpltxt (car link) link (cdr link)))
12401 (setq link (or link cpltxt)
12402 desc (or desc cpltxt))
12403 (if (equal desc "NONE") (setq desc nil))
12405 (if (and (interactive-p) link)
12406 (progn
12407 (setq org-stored-links
12408 (cons (list link desc) org-stored-links))
12409 (message "Stored: %s" (or desc link)))
12410 (and link (org-make-link-string link desc)))))
12412 (defun org-store-link-props (&rest plist)
12413 "Store link properties, extract names and addresses."
12414 (let (x adr)
12415 (when (setq x (plist-get plist :from))
12416 (setq adr (mail-extract-address-components x))
12417 (plist-put plist :fromname (car adr))
12418 (plist-put plist :fromaddress (nth 1 adr)))
12419 (when (setq x (plist-get plist :to))
12420 (setq adr (mail-extract-address-components x))
12421 (plist-put plist :toname (car adr))
12422 (plist-put plist :toaddress (nth 1 adr))))
12423 (let ((from (plist-get plist :from))
12424 (to (plist-get plist :to)))
12425 (when (and from to org-from-is-user-regexp)
12426 (plist-put plist :fromto
12427 (if (string-match org-from-is-user-regexp from)
12428 (concat "to %t")
12429 (concat "from %f")))))
12430 (setq org-store-link-plist plist))
12432 (defun org-email-link-description (&optional fmt)
12433 "Return the description part of an email link.
12434 This takes information from `org-store-link-plist' and formats it
12435 according to FMT (default from `org-email-link-description-format')."
12436 (setq fmt (or fmt org-email-link-description-format))
12437 (let* ((p org-store-link-plist)
12438 (to (plist-get p :toaddress))
12439 (from (plist-get p :fromaddress))
12440 (table
12441 (list
12442 (cons "%c" (plist-get p :fromto))
12443 (cons "%F" (plist-get p :from))
12444 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
12445 (cons "%T" (plist-get p :to))
12446 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
12447 (cons "%s" (plist-get p :subject))
12448 (cons "%m" (plist-get p :message-id)))))
12449 (when (string-match "%c" fmt)
12450 ;; Check if the user wrote this message
12451 (if (and org-from-is-user-regexp from to
12452 (save-match-data (string-match org-from-is-user-regexp from)))
12453 (setq fmt (replace-match "to %t" t t fmt))
12454 (setq fmt (replace-match "from %f" t t fmt))))
12455 (org-replace-escapes fmt table)))
12457 (defun org-make-org-heading-search-string (&optional string heading)
12458 "Make search string for STRING or current headline."
12459 (interactive)
12460 (let ((s (or string (org-get-heading))))
12461 (unless (and string (not heading))
12462 ;; We are using a headline, clean up garbage in there.
12463 (if (string-match org-todo-regexp s)
12464 (setq s (replace-match "" t t s)))
12465 (if (string-match (org-re ":[[:alnum:]_@:]+:[ \t]*$") s)
12466 (setq s (replace-match "" t t s)))
12467 (setq s (org-trim s))
12468 (if (string-match (concat "^\\(" org-quote-string "\\|"
12469 org-comment-string "\\)") s)
12470 (setq s (replace-match "" t t s)))
12471 (while (string-match org-ts-regexp s)
12472 (setq s (replace-match "" t t s))))
12473 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
12474 (setq s (replace-match " " t t s)))
12475 (or string (setq s (concat "*" s))) ; Add * for headlines
12476 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
12478 (defun org-make-link (&rest strings)
12479 "Concatenate STRINGS."
12480 (apply 'concat strings))
12482 (defun org-make-link-string (link &optional description)
12483 "Make a link with brackets, consisting of LINK and DESCRIPTION."
12484 (unless (string-match "\\S-" link)
12485 (error "Empty link"))
12486 (when (stringp description)
12487 ;; Remove brackets from the description, they are fatal.
12488 (while (string-match "\\[" description)
12489 (setq description (replace-match "{" t t description)))
12490 (while (string-match "\\]" description)
12491 (setq description (replace-match "}" t t description))))
12492 (when (equal (org-link-escape link) description)
12493 ;; No description needed, it is identical
12494 (setq description nil))
12495 (when (and (not description)
12496 (not (equal link (org-link-escape link))))
12497 (setq description link))
12498 (concat "[[" (org-link-escape link) "]"
12499 (if description (concat "[" description "]") "")
12500 "]"))
12502 (defconst org-link-escape-chars
12503 '((?\ . "%20")
12504 (?\[ . "%5B")
12505 (?\] . "%5D")
12506 (?\340 . "%E0") ; `a
12507 (?\342 . "%E2") ; ^a
12508 (?\347 . "%E7") ; ,c
12509 (?\350 . "%E8") ; `e
12510 (?\351 . "%E9") ; 'e
12511 (?\352 . "%EA") ; ^e
12512 (?\356 . "%EE") ; ^i
12513 (?\364 . "%F4") ; ^o
12514 (?\371 . "%F9") ; `u
12515 (?\373 . "%FB") ; ^u
12516 (?\; . "%3B")
12517 (?? . "%3F")
12518 (?= . "%3D")
12519 (?+ . "%2B")
12521 "Association list of escapes for some characters problematic in links.
12522 This is the list that is used for internal purposes.")
12524 (defconst org-link-escape-chars-browser
12525 '((?\ . "%20")) ; 32 for the SPC char
12526 "Association list of escapes for some characters problematic in links.
12527 This is the list that is used before handing over to the browser.")
12529 (defun org-link-escape (text &optional table)
12530 "Escape charaters in TEXT that are problematic for links."
12531 (setq table (or table org-link-escape-chars))
12532 (when text
12533 (let ((re (mapconcat (lambda (x) (regexp-quote
12534 (char-to-string (car x))))
12535 table "\\|")))
12536 (while (string-match re text)
12537 (setq text
12538 (replace-match
12539 (cdr (assoc (string-to-char (match-string 0 text))
12540 table))
12541 t t text)))
12542 text)))
12544 (defun org-link-unescape (text &optional table)
12545 "Reverse the action of `org-link-escape'."
12546 (setq table (or table org-link-escape-chars))
12547 (when text
12548 (let ((re (mapconcat (lambda (x) (regexp-quote (cdr x)))
12549 table "\\|")))
12550 (while (string-match re text)
12551 (setq text
12552 (replace-match
12553 (char-to-string (car (rassoc (match-string 0 text) table)))
12554 t t text)))
12555 text)))
12557 (defun org-xor (a b)
12558 "Exclusive or."
12559 (if a (not b) b))
12561 (defun org-get-header (header)
12562 "Find a header field in the current buffer."
12563 (save-excursion
12564 (goto-char (point-min))
12565 (let ((case-fold-search t) s)
12566 (cond
12567 ((eq header 'from)
12568 (if (re-search-forward "^From:\\s-+\\(.*\\)" nil t)
12569 (setq s (match-string 1)))
12570 (while (string-match "\"" s)
12571 (setq s (replace-match "" t t s)))
12572 (if (string-match "[<(].*" s)
12573 (setq s (replace-match "" t t s))))
12574 ((eq header 'message-id)
12575 (if (re-search-forward "^message-id:\\s-+\\(.*\\)" nil t)
12576 (setq s (match-string 1))))
12577 ((eq header 'subject)
12578 (if (re-search-forward "^subject:\\s-+\\(.*\\)" nil t)
12579 (setq s (match-string 1)))))
12580 (if (string-match "\\`[ \t\]+" s) (setq s (replace-match "" t t s)))
12581 (if (string-match "[ \t\]+\\'" s) (setq s (replace-match "" t t s)))
12582 s)))
12585 (defun org-fixup-message-id-for-http (s)
12586 "Replace special characters in a message id, so it can be used in an http query."
12587 (while (string-match "<" s)
12588 (setq s (replace-match "%3C" t t s)))
12589 (while (string-match ">" s)
12590 (setq s (replace-match "%3E" t t s)))
12591 (while (string-match "@" s)
12592 (setq s (replace-match "%40" t t s)))
12595 ;;;###autoload
12596 (defun org-insert-link-global ()
12597 "Insert a link like Org-mode does.
12598 This command can be called in any mode to insert a link in Org-mode syntax."
12599 (interactive)
12600 (org-run-like-in-org-mode 'org-insert-link))
12602 (defun org-insert-link (&optional complete-file)
12603 "Insert a link. At the prompt, enter the link.
12605 Completion can be used to select a link previously stored with
12606 `org-store-link'. When the empty string is entered (i.e. if you just
12607 press RET at the prompt), the link defaults to the most recently
12608 stored link. As SPC triggers completion in the minibuffer, you need to
12609 use M-SPC or C-q SPC to force the insertion of a space character.
12611 You will also be prompted for a description, and if one is given, it will
12612 be displayed in the buffer instead of the link.
12614 If there is already a link at point, this command will allow you to edit link
12615 and description parts.
12617 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can be
12618 selected using completion. The path to the file will be relative to
12619 the current directory if the file is in the current directory or a
12620 subdirectory. Otherwise, the link will be the absolute path as
12621 completed in the minibuffer (i.e. normally ~/path/to/file).
12623 With two \\[universal-argument] prefixes, enforce an absolute path even if the file
12624 is in the current directory or below.
12625 With three \\[universal-argument] prefixes, negate the meaning of
12626 `org-keep-stored-link-after-insertion'."
12627 (interactive "P")
12628 (let* ((wcf (current-window-configuration))
12629 (region (if (org-region-active-p)
12630 (buffer-substring (region-beginning) (region-end))))
12631 (remove (and region (list (region-beginning) (region-end))))
12632 (desc region)
12633 tmphist ; byte-compile incorrectly complains about this
12634 link entry file)
12635 (cond
12636 ((org-in-regexp org-bracket-link-regexp 1)
12637 ;; We do have a link at point, and we are going to edit it.
12638 (setq remove (list (match-beginning 0) (match-end 0)))
12639 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
12640 (setq link (read-string "Link: "
12641 (org-link-unescape
12642 (org-match-string-no-properties 1)))))
12643 ((or (org-in-regexp org-angle-link-re)
12644 (org-in-regexp org-plain-link-re))
12645 ;; Convert to bracket link
12646 (setq remove (list (match-beginning 0) (match-end 0))
12647 link (read-string "Link: "
12648 (org-remove-angle-brackets (match-string 0)))))
12649 ((equal complete-file '(4))
12650 ;; Completing read for file names.
12651 (setq file (read-file-name "File: "))
12652 (let ((pwd (file-name-as-directory (expand-file-name ".")))
12653 (pwd1 (file-name-as-directory (abbreviate-file-name
12654 (expand-file-name ".")))))
12655 (cond
12656 ((equal complete-file '(16))
12657 (setq link (org-make-link
12658 "file:"
12659 (abbreviate-file-name (expand-file-name file)))))
12660 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
12661 (setq link (org-make-link "file:" (match-string 1 file))))
12662 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
12663 (expand-file-name file))
12664 (setq link (org-make-link
12665 "file:" (match-string 1 (expand-file-name file)))))
12666 (t (setq link (org-make-link "file:" file))))))
12668 ;; Read link, with completion for stored links.
12669 (with-output-to-temp-buffer "*Org Links*"
12670 (princ "Insert a link. Use TAB to complete valid link prefixes.\n")
12671 (when org-stored-links
12672 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
12673 (princ (mapconcat
12674 (lambda (x)
12675 (if (nth 1 x) (concat (car x) " (" (nth 1 x) ")") (car x)))
12676 (reverse org-stored-links) "\n"))))
12677 (let ((cw (selected-window)))
12678 (select-window (get-buffer-window "*Org Links*"))
12679 (shrink-window-if-larger-than-buffer)
12680 (setq truncate-lines t)
12681 (select-window cw))
12682 ;; Fake a link history, containing the stored links.
12683 (setq tmphist (append (mapcar 'car org-stored-links)
12684 org-insert-link-history))
12685 (unwind-protect
12686 (setq link (org-completing-read
12687 "Link: "
12688 (append
12689 (mapcar (lambda (x) (list (concat (car x) ":")))
12690 (append org-link-abbrev-alist-local org-link-abbrev-alist))
12691 (mapcar (lambda (x) (list (concat x ":")))
12692 org-link-types))
12693 nil nil nil
12694 'tmphist
12695 (or (car (car org-stored-links)))))
12696 (set-window-configuration wcf)
12697 (kill-buffer "*Org Links*"))
12698 (setq entry (assoc link org-stored-links))
12699 (or entry (push link org-insert-link-history))
12700 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
12701 (not org-keep-stored-link-after-insertion))
12702 (setq org-stored-links (delq (assoc link org-stored-links)
12703 org-stored-links)))
12704 (setq desc (or desc (nth 1 entry)))))
12706 (if (string-match org-plain-link-re link)
12707 ;; URL-like link, normalize the use of angular brackets.
12708 (setq link (org-make-link (org-remove-angle-brackets link))))
12710 ;; Check if we are linking to the current file with a search option
12711 ;; If yes, simplify the link by using only the search option.
12712 (when (and buffer-file-name
12713 (string-match "\\<file:\\(.+?\\)::\\([^>]+\\)" link))
12714 (let* ((path (match-string 1 link))
12715 (case-fold-search nil)
12716 (search (match-string 2 link)))
12717 (save-match-data
12718 (if (equal (file-truename buffer-file-name) (file-truename path))
12719 ;; We are linking to this same file, with a search option
12720 (setq link search)))))
12722 ;; Check if we can/should use a relative path. If yes, simplify the link
12723 (when (string-match "\\<file:\\(.*\\)" link)
12724 (let* ((path (match-string 1 link))
12725 (origpath path)
12726 (case-fold-search nil))
12727 (cond
12728 ((eq org-link-file-path-type 'absolute)
12729 (setq path (abbreviate-file-name (expand-file-name path))))
12730 ((eq org-link-file-path-type 'noabbrev)
12731 (setq path (expand-file-name path)))
12732 ((eq org-link-file-path-type 'relative)
12733 (setq path (file-relative-name path)))
12735 (save-match-data
12736 (if (string-match (concat "^" (regexp-quote
12737 (file-name-as-directory
12738 (expand-file-name "."))))
12739 (expand-file-name path))
12740 ;; We are linking a file with relative path name.
12741 (setq path (substring (expand-file-name path)
12742 (match-end 0)))))))
12743 (setq link (concat "file:" path))
12744 (if (equal desc origpath)
12745 (setq desc path))))
12747 (setq desc (read-string "Description: " desc))
12748 (unless (string-match "\\S-" desc) (setq desc nil))
12749 (if remove (apply 'delete-region remove))
12750 (insert (org-make-link-string link desc))))
12752 (defun org-completing-read (&rest args)
12753 (let ((minibuffer-local-completion-map
12754 (copy-keymap minibuffer-local-completion-map)))
12755 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
12756 (apply 'completing-read args)))
12758 ;;; Opening/following a link
12759 (defvar org-link-search-failed nil)
12761 (defun org-next-link ()
12762 "Move forward to the next link.
12763 If the link is in hidden text, expose it."
12764 (interactive)
12765 (when (and org-link-search-failed (eq this-command last-command))
12766 (goto-char (point-min))
12767 (message "Link search wrapped back to beginning of buffer"))
12768 (setq org-link-search-failed nil)
12769 (let* ((pos (point))
12770 (ct (org-context))
12771 (a (assoc :link ct)))
12772 (if a (goto-char (nth 2 a)))
12773 (if (re-search-forward org-any-link-re nil t)
12774 (progn
12775 (goto-char (match-beginning 0))
12776 (if (org-invisible-p) (org-show-context)))
12777 (goto-char pos)
12778 (setq org-link-search-failed t)
12779 (error "No further link found"))))
12781 (defun org-previous-link ()
12782 "Move backward to the previous link.
12783 If the link is in hidden text, expose it."
12784 (interactive)
12785 (when (and org-link-search-failed (eq this-command last-command))
12786 (goto-char (point-max))
12787 (message "Link search wrapped back to end of buffer"))
12788 (setq org-link-search-failed nil)
12789 (let* ((pos (point))
12790 (ct (org-context))
12791 (a (assoc :link ct)))
12792 (if a (goto-char (nth 1 a)))
12793 (if (re-search-backward org-any-link-re nil t)
12794 (progn
12795 (goto-char (match-beginning 0))
12796 (if (org-invisible-p) (org-show-context)))
12797 (goto-char pos)
12798 (setq org-link-search-failed t)
12799 (error "No further link found"))))
12801 (defun org-find-file-at-mouse (ev)
12802 "Open file link or URL at mouse."
12803 (interactive "e")
12804 (mouse-set-point ev)
12805 (org-open-at-point 'in-emacs))
12807 (defun org-open-at-mouse (ev)
12808 "Open file link or URL at mouse."
12809 (interactive "e")
12810 (mouse-set-point ev)
12811 (org-open-at-point))
12813 (defvar org-window-config-before-follow-link nil
12814 "The window configuration before following a link.
12815 This is saved in case the need arises to restore it.")
12817 (defvar org-open-link-marker (make-marker)
12818 "Marker pointing to the location where `org-open-at-point; was called.")
12820 ;;;###autoload
12821 (defun org-open-at-point-global ()
12822 "Follow a link like Org-mode does.
12823 This command can be called in any mode to follow a link that has
12824 Org-mode syntax."
12825 (interactive)
12826 (org-run-like-in-org-mode 'org-open-at-point))
12828 (defun org-open-at-point (&optional in-emacs)
12829 "Open link at or after point.
12830 If there is no link at point, this function will search forward up to
12831 the end of the current subtree.
12832 Normally, files will be opened by an appropriate application. If the
12833 optional argument IN-EMACS is non-nil, Emacs will visit the file."
12834 (interactive "P")
12835 (require 'org-irc)
12836 (move-marker org-open-link-marker (point))
12837 (setq org-window-config-before-follow-link (current-window-configuration))
12838 (org-remove-occur-highlights nil nil t)
12839 (if (org-at-timestamp-p t)
12840 (org-follow-timestamp-link)
12841 (let (type path link line search (pos (point)))
12842 (catch 'match
12843 (save-excursion
12844 (skip-chars-forward "^]\n\r")
12845 (when (org-in-regexp org-bracket-link-regexp)
12846 (setq link (org-link-unescape (org-match-string-no-properties 1)))
12847 (while (string-match " *\n *" link)
12848 (setq link (replace-match " " t t link)))
12849 (setq link (org-link-expand-abbrev link))
12850 (if (string-match org-link-re-with-space2 link)
12851 (setq type (match-string 1 link) path (match-string 2 link))
12852 (setq type "thisfile" path link))
12853 (throw 'match t)))
12855 (when (get-text-property (point) 'org-linked-text)
12856 (setq type "thisfile"
12857 pos (if (get-text-property (1+ (point)) 'org-linked-text)
12858 (1+ (point)) (point))
12859 path (buffer-substring
12860 (previous-single-property-change pos 'org-linked-text)
12861 (next-single-property-change pos 'org-linked-text)))
12862 (throw 'match t))
12864 (save-excursion
12865 (when (or (org-in-regexp org-angle-link-re)
12866 (org-in-regexp org-plain-link-re))
12867 (setq type (match-string 1) path (match-string 2))
12868 (throw 'match t)))
12869 (when (org-in-regexp "\\<\\([^><\n]+\\)\\>")
12870 (setq type "tree-match"
12871 path (match-string 1))
12872 (throw 'match t))
12873 (save-excursion
12874 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@:]+\\):[ \t]*$"))
12875 (setq type "tags"
12876 path (match-string 1))
12877 (while (string-match ":" path)
12878 (setq path (replace-match "+" t t path)))
12879 (throw 'match t))))
12880 (unless path
12881 (error "No link found"))
12882 ;; Remove any trailing spaces in path
12883 (if (string-match " +\\'" path)
12884 (setq path (replace-match "" t t path)))
12886 (cond
12888 ((assoc type org-link-protocols)
12889 (funcall (nth 1 (assoc type org-link-protocols)) path))
12891 ((equal type "mailto")
12892 (let ((cmd (car org-link-mailto-program))
12893 (args (cdr org-link-mailto-program)) args1
12894 (address path) (subject "") a)
12895 (if (string-match "\\(.*\\)::\\(.*\\)" path)
12896 (setq address (match-string 1 path)
12897 subject (org-link-escape (match-string 2 path))))
12898 (while args
12899 (cond
12900 ((not (stringp (car args))) (push (pop args) args1))
12901 (t (setq a (pop args))
12902 (if (string-match "%a" a)
12903 (setq a (replace-match address t t a)))
12904 (if (string-match "%s" a)
12905 (setq a (replace-match subject t t a)))
12906 (push a args1))))
12907 (apply cmd (nreverse args1))))
12909 ((member type '("http" "https" "ftp" "news"))
12910 (browse-url (concat type ":" (org-link-escape
12911 path org-link-escape-chars-browser))))
12913 ((member type '("message"))
12914 (browse-url (concat type ":" path)))
12916 ((string= type "tags")
12917 (org-tags-view in-emacs path))
12918 ((string= type "thisfile")
12919 (if in-emacs
12920 (switch-to-buffer-other-window
12921 (org-get-buffer-for-internal-link (current-buffer)))
12922 (org-mark-ring-push))
12923 (let ((cmd `(org-link-search
12924 ,path
12925 ,(cond ((equal in-emacs '(4)) 'occur)
12926 ((equal in-emacs '(16)) 'org-occur)
12927 (t nil))
12928 ,pos)))
12929 (condition-case nil (eval cmd)
12930 (error (progn (widen) (eval cmd))))))
12932 ((string= type "tree-match")
12933 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
12935 ((string= type "file")
12936 (if (string-match "::\\([0-9]+\\)\\'" path)
12937 (setq line (string-to-number (match-string 1 path))
12938 path (substring path 0 (match-beginning 0)))
12939 (if (string-match "::\\(.+\\)\\'" path)
12940 (setq search (match-string 1 path)
12941 path (substring path 0 (match-beginning 0)))))
12942 (if (string-match "[*?{]" (file-name-nondirectory path))
12943 (dired path)
12944 (org-open-file path in-emacs line search)))
12946 ((string= type "news")
12947 (org-follow-gnus-link path))
12949 ((string= type "bbdb")
12950 (org-follow-bbdb-link path))
12952 ((string= type "info")
12953 (org-follow-info-link path))
12955 ((string= type "gnus")
12956 (let (group article)
12957 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
12958 (error "Error in Gnus link"))
12959 (setq group (match-string 1 path)
12960 article (match-string 3 path))
12961 (org-follow-gnus-link group article)))
12963 ((string= type "vm")
12964 (let (folder article)
12965 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
12966 (error "Error in VM link"))
12967 (setq folder (match-string 1 path)
12968 article (match-string 3 path))
12969 ;; in-emacs is the prefix arg, will be interpreted as read-only
12970 (org-follow-vm-link folder article in-emacs)))
12972 ((string= type "wl")
12973 (let (folder article)
12974 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
12975 (error "Error in Wanderlust link"))
12976 (setq folder (match-string 1 path)
12977 article (match-string 3 path))
12978 (org-follow-wl-link folder article)))
12980 ((string= type "mhe")
12981 (let (folder article)
12982 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
12983 (error "Error in MHE link"))
12984 (setq folder (match-string 1 path)
12985 article (match-string 3 path))
12986 (org-follow-mhe-link folder article)))
12988 ((string= type "rmail")
12989 (let (folder article)
12990 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
12991 (error "Error in RMAIL link"))
12992 (setq folder (match-string 1 path)
12993 article (match-string 3 path))
12994 (org-follow-rmail-link folder article)))
12996 ((string= type "shell")
12997 (let ((cmd path))
12998 (if (or (not org-confirm-shell-link-function)
12999 (funcall org-confirm-shell-link-function
13000 (format "Execute \"%s\" in shell? "
13001 (org-add-props cmd nil
13002 'face 'org-warning))))
13003 (progn
13004 (message "Executing %s" cmd)
13005 (shell-command cmd))
13006 (error "Abort"))))
13008 ((string= type "elisp")
13009 (let ((cmd path))
13010 (if (or (not org-confirm-elisp-link-function)
13011 (funcall org-confirm-elisp-link-function
13012 (format "Execute \"%s\" as elisp? "
13013 (org-add-props cmd nil
13014 'face 'org-warning))))
13015 (message "%s => %s" cmd (eval (read cmd)))
13016 (error "Abort"))))
13019 (browse-url-at-point)))))
13020 (move-marker org-open-link-marker nil)
13021 (run-hook-with-args 'org-follow-link-hook))
13023 ;;; File search
13025 (defvar org-create-file-search-functions nil
13026 "List of functions to construct the right search string for a file link.
13027 These functions are called in turn with point at the location to
13028 which the link should point.
13030 A function in the hook should first test if it would like to
13031 handle this file type, for example by checking the major-mode or
13032 the file extension. If it decides not to handle this file, it
13033 should just return nil to give other functions a chance. If it
13034 does handle the file, it must return the search string to be used
13035 when following the link. The search string will be part of the
13036 file link, given after a double colon, and `org-open-at-point'
13037 will automatically search for it. If special measures must be
13038 taken to make the search successful, another function should be
13039 added to the companion hook `org-execute-file-search-functions',
13040 which see.
13042 A function in this hook may also use `setq' to set the variable
13043 `description' to provide a suggestion for the descriptive text to
13044 be used for this link when it gets inserted into an Org-mode
13045 buffer with \\[org-insert-link].")
13047 (defvar org-execute-file-search-functions nil
13048 "List of functions to execute a file search triggered by a link.
13050 Functions added to this hook must accept a single argument, the
13051 search string that was part of the file link, the part after the
13052 double colon. The function must first check if it would like to
13053 handle this search, for example by checking the major-mode or the
13054 file extension. If it decides not to handle this search, it
13055 should just return nil to give other functions a chance. If it
13056 does handle the search, it must return a non-nil value to keep
13057 other functions from trying.
13059 Each function can access the current prefix argument through the
13060 variable `current-prefix-argument'. Note that a single prefix is
13061 used to force opening a link in Emacs, so it may be good to only
13062 use a numeric or double prefix to guide the search function.
13064 In case this is needed, a function in this hook can also restore
13065 the window configuration before `org-open-at-point' was called using:
13067 (set-window-configuration org-window-config-before-follow-link)")
13069 (defun org-link-search (s &optional type avoid-pos)
13070 "Search for a link search option.
13071 If S is surrounded by forward slashes, it is interpreted as a
13072 regular expression. In org-mode files, this will create an `org-occur'
13073 sparse tree. In ordinary files, `occur' will be used to list matches.
13074 If the current buffer is in `dired-mode', grep will be used to search
13075 in all files. If AVOID-POS is given, ignore matches near that position."
13076 (let ((case-fold-search t)
13077 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
13078 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
13079 (append '(("") (" ") ("\t") ("\n"))
13080 org-emphasis-alist)
13081 "\\|") "\\)"))
13082 (pos (point))
13083 (pre "") (post "")
13084 words re0 re1 re2 re3 re4 re5 re2a reall)
13085 (cond
13086 ;; First check if there are any special
13087 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
13088 ;; Now try the builtin stuff
13089 ((save-excursion
13090 (goto-char (point-min))
13091 (and
13092 (re-search-forward
13093 (concat "<<" (regexp-quote s0) ">>") nil t)
13094 (setq pos (match-beginning 0))))
13095 ;; There is an exact target for this
13096 (goto-char pos))
13097 ((string-match "^/\\(.*\\)/$" s)
13098 ;; A regular expression
13099 (cond
13100 ((org-mode-p)
13101 (org-occur (match-string 1 s)))
13102 ;;((eq major-mode 'dired-mode)
13103 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
13104 (t (org-do-occur (match-string 1 s)))))
13106 ;; A normal search strings
13107 (when (equal (string-to-char s) ?*)
13108 ;; Anchor on headlines, post may include tags.
13109 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
13110 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@:+]:[ \t]*\\)?$")
13111 s (substring s 1)))
13112 (remove-text-properties
13113 0 (length s)
13114 '(face nil mouse-face nil keymap nil fontified nil) s)
13115 ;; Make a series of regular expressions to find a match
13116 (setq words (org-split-string s "[ \n\r\t]+")
13117 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
13118 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
13119 "\\)" markers)
13120 re2a (concat "[ \t\r\n]\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
13121 re4 (concat "[^a-zA-Z_]\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
13122 re1 (concat pre re2 post)
13123 re3 (concat pre re4 post)
13124 re5 (concat pre ".*" re4)
13125 re2 (concat pre re2)
13126 re2a (concat pre re2a)
13127 re4 (concat pre re4)
13128 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
13129 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
13130 re5 "\\)"
13132 (cond
13133 ((eq type 'org-occur) (org-occur reall))
13134 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
13135 (t (goto-char (point-min))
13136 (if (or (org-search-not-self 1 re0 nil t)
13137 (org-search-not-self 1 re1 nil t)
13138 (org-search-not-self 1 re2 nil t)
13139 (org-search-not-self 1 re2a nil t)
13140 (org-search-not-self 1 re3 nil t)
13141 (org-search-not-self 1 re4 nil t)
13142 (org-search-not-self 1 re5 nil t)
13144 (goto-char (match-beginning 1))
13145 (goto-char pos)
13146 (error "No match")))))
13148 ;; Normal string-search
13149 (goto-char (point-min))
13150 (if (search-forward s nil t)
13151 (goto-char (match-beginning 0))
13152 (error "No match"))))
13153 (and (org-mode-p) (org-show-context 'link-search))))
13155 (defun org-search-not-self (group &rest args)
13156 "Execute `re-search-forward', but only accept matches that do not
13157 enclose the position of `org-open-link-marker'."
13158 (let ((m org-open-link-marker))
13159 (catch 'exit
13160 (while (apply 're-search-forward args)
13161 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
13162 (goto-char (match-end group))
13163 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
13164 (> (match-beginning 0) (marker-position m))
13165 (< (match-end 0) (marker-position m)))
13166 (save-match-data
13167 (or (not (org-in-regexp
13168 org-bracket-link-analytic-regexp 1))
13169 (not (match-end 4)) ; no description
13170 (and (<= (match-beginning 4) (point))
13171 (>= (match-end 4) (point))))))
13172 (throw 'exit (point))))))))
13174 (defun org-get-buffer-for-internal-link (buffer)
13175 "Return a buffer to be used for displaying the link target of internal links."
13176 (cond
13177 ((not org-display-internal-link-with-indirect-buffer)
13178 buffer)
13179 ((string-match "(Clone)$" (buffer-name buffer))
13180 (message "Buffer is already a clone, not making another one")
13181 ;; we also do not modify visibility in this case
13182 buffer)
13183 (t ; make a new indirect buffer for displaying the link
13184 (let* ((bn (buffer-name buffer))
13185 (ibn (concat bn "(Clone)"))
13186 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
13187 (with-current-buffer ib (org-overview))
13188 ib))))
13190 (defun org-do-occur (regexp &optional cleanup)
13191 "Call the Emacs command `occur'.
13192 If CLEANUP is non-nil, remove the printout of the regular expression
13193 in the *Occur* buffer. This is useful if the regex is long and not useful
13194 to read."
13195 (occur regexp)
13196 (when cleanup
13197 (let ((cwin (selected-window)) win beg end)
13198 (when (setq win (get-buffer-window "*Occur*"))
13199 (select-window win))
13200 (goto-char (point-min))
13201 (when (re-search-forward "match[a-z]+" nil t)
13202 (setq beg (match-end 0))
13203 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
13204 (setq end (1- (match-beginning 0)))))
13205 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
13206 (goto-char (point-min))
13207 (select-window cwin))))
13209 ;;; The mark ring for links jumps
13211 (defvar org-mark-ring nil
13212 "Mark ring for positions before jumps in Org-mode.")
13213 (defvar org-mark-ring-last-goto nil
13214 "Last position in the mark ring used to go back.")
13215 ;; Fill and close the ring
13216 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
13217 (loop for i from 1 to org-mark-ring-length do
13218 (push (make-marker) org-mark-ring))
13219 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
13220 org-mark-ring)
13222 (defun org-mark-ring-push (&optional pos buffer)
13223 "Put the current position or POS into the mark ring and rotate it."
13224 (interactive)
13225 (setq pos (or pos (point)))
13226 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
13227 (move-marker (car org-mark-ring)
13228 (or pos (point))
13229 (or buffer (current-buffer)))
13230 (message "%s"
13231 (substitute-command-keys
13232 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
13234 (defun org-mark-ring-goto (&optional n)
13235 "Jump to the previous position in the mark ring.
13236 With prefix arg N, jump back that many stored positions. When
13237 called several times in succession, walk through the entire ring.
13238 Org-mode commands jumping to a different position in the current file,
13239 or to another Org-mode file, automatically push the old position
13240 onto the ring."
13241 (interactive "p")
13242 (let (p m)
13243 (if (eq last-command this-command)
13244 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
13245 (setq p org-mark-ring))
13246 (setq org-mark-ring-last-goto p)
13247 (setq m (car p))
13248 (switch-to-buffer (marker-buffer m))
13249 (goto-char m)
13250 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
13252 (defun org-remove-angle-brackets (s)
13253 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
13254 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
13256 (defun org-add-angle-brackets (s)
13257 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
13258 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
13261 ;;; Following specific links
13263 (defun org-follow-timestamp-link ()
13264 (cond
13265 ((org-at-date-range-p t)
13266 (let ((org-agenda-start-on-weekday)
13267 (t1 (match-string 1))
13268 (t2 (match-string 2)))
13269 (setq t1 (time-to-days (org-time-string-to-time t1))
13270 t2 (time-to-days (org-time-string-to-time t2)))
13271 (org-agenda-list nil t1 (1+ (- t2 t1)))))
13272 ((org-at-timestamp-p t)
13273 (org-agenda-list nil (time-to-days (org-time-string-to-time
13274 (substring (match-string 1) 0 10)))
13276 (t (error "This should not happen"))))
13279 (defun org-follow-bbdb-link (name)
13280 "Follow a BBDB link to NAME."
13281 (require 'bbdb)
13282 (let ((inhibit-redisplay (not debug-on-error))
13283 (bbdb-electric-p nil))
13284 (catch 'exit
13285 ;; Exact match on name
13286 (bbdb-name (concat "\\`" name "\\'") nil)
13287 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
13288 ;; Exact match on name
13289 (bbdb-company (concat "\\`" name "\\'") nil)
13290 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
13291 ;; Partial match on name
13292 (bbdb-name name nil)
13293 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
13294 ;; Partial match on company
13295 (bbdb-company name nil)
13296 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
13297 ;; General match including network address and notes
13298 (bbdb name nil)
13299 (when (= 0 (buffer-size (get-buffer "*BBDB*")))
13300 (delete-window (get-buffer-window "*BBDB*"))
13301 (error "No matching BBDB record")))))
13303 (defun org-follow-info-link (name)
13304 "Follow an info file & node link to NAME."
13305 (if (or (string-match "\\(.*\\)::?\\(.*\\)" name)
13306 (string-match "\\(.*\\)" name))
13307 (progn
13308 (require 'info)
13309 (if (match-string 2 name) ; If there isn't a node, choose "Top"
13310 (Info-find-node (match-string 1 name) (match-string 2 name))
13311 (Info-find-node (match-string 1 name) "Top")))
13312 (message "Could not open: %s" name)))
13314 (defun org-follow-gnus-link (&optional group article)
13315 "Follow a Gnus link to GROUP and ARTICLE."
13316 (require 'gnus)
13317 (funcall (cdr (assq 'gnus org-link-frame-setup)))
13318 (if gnus-other-frame-object (select-frame gnus-other-frame-object))
13319 (cond ((and group article)
13320 (gnus-group-read-group 1 nil group)
13321 (gnus-summary-goto-article (string-to-number article) nil t))
13322 (group (gnus-group-jump-to-group group))))
13324 (defun org-follow-vm-link (&optional folder article readonly)
13325 "Follow a VM link to FOLDER and ARTICLE."
13326 (require 'vm)
13327 (setq article (org-add-angle-brackets article))
13328 (if (string-match "^//\\([a-zA-Z]+@\\)?\\([^:]+\\):\\(.*\\)" folder)
13329 ;; ange-ftp or efs or tramp access
13330 (let ((user (or (match-string 1 folder) (user-login-name)))
13331 (host (match-string 2 folder))
13332 (file (match-string 3 folder)))
13333 (cond
13334 ((featurep 'tramp)
13335 ;; use tramp to access the file
13336 (if (featurep 'xemacs)
13337 (setq folder (format "[%s@%s]%s" user host file))
13338 (setq folder (format "/%s@%s:%s" user host file))))
13340 ;; use ange-ftp or efs
13341 (require (if (featurep 'xemacs) 'efs 'ange-ftp))
13342 (setq folder (format "/%s@%s:%s" user host file))))))
13343 (when folder
13344 (funcall (cdr (assq 'vm org-link-frame-setup)) folder readonly)
13345 (sit-for 0.1)
13346 (when article
13347 (vm-select-folder-buffer)
13348 (widen)
13349 (let ((case-fold-search t))
13350 (goto-char (point-min))
13351 (if (not (re-search-forward
13352 (concat "^" "message-id: *" (regexp-quote article))))
13353 (error "Could not find the specified message in this folder"))
13354 (vm-isearch-update)
13355 (vm-isearch-narrow)
13356 (vm-beginning-of-message)
13357 (vm-summarize)))))
13359 (defun org-follow-wl-link (folder article)
13360 "Follow a Wanderlust link to FOLDER and ARTICLE."
13361 (if (and (string= folder "%")
13362 article
13363 (string-match "^\\([^#]+\\)\\(#\\(.*\\)\\)?" article))
13364 ;; XXX: imap-uw supports folders starting with '#' such as "#mh/inbox".
13365 ;; Thus, we recompose folder and article ids.
13366 (setq folder (format "%s#%s" folder (match-string 1 article))
13367 article (match-string 3 article)))
13368 (if (not (elmo-folder-exists-p (wl-folder-get-elmo-folder folder)))
13369 (error "No such folder: %s" folder))
13370 (wl-summary-goto-folder-subr folder 'no-sync t nil t nil nil)
13371 (and article
13372 (wl-summary-jump-to-msg-by-message-id (org-add-angle-brackets article))
13373 (wl-summary-redisplay)))
13375 (defun org-follow-rmail-link (folder article)
13376 "Follow an RMAIL link to FOLDER and ARTICLE."
13377 (setq article (org-add-angle-brackets article))
13378 (let (message-number)
13379 (save-excursion
13380 (save-window-excursion
13381 (rmail (if (string= folder "RMAIL") rmail-file-name folder))
13382 (setq message-number
13383 (save-restriction
13384 (widen)
13385 (goto-char (point-max))
13386 (if (re-search-backward
13387 (concat "^Message-ID:\\s-+" (regexp-quote
13388 (or article "")))
13389 nil t)
13390 (rmail-what-message))))))
13391 (if message-number
13392 (progn
13393 (rmail (if (string= folder "RMAIL") rmail-file-name folder))
13394 (rmail-show-message message-number)
13395 message-number)
13396 (error "Message not found"))))
13398 ;;; mh-e integration based on planner-mode
13399 (defun org-mhe-get-message-real-folder ()
13400 "Return the name of the current message real folder, so if you use
13401 sequences, it will now work."
13402 (save-excursion
13403 (let* ((folder
13404 (if (equal major-mode 'mh-folder-mode)
13405 mh-current-folder
13406 ;; Refer to the show buffer
13407 mh-show-folder-buffer))
13408 (end-index
13409 (if (boundp 'mh-index-folder)
13410 (min (length mh-index-folder) (length folder))))
13412 ;; a simple test on mh-index-data does not work, because
13413 ;; mh-index-data is always nil in a show buffer.
13414 (if (and (boundp 'mh-index-folder)
13415 (string= mh-index-folder (substring folder 0 end-index)))
13416 (if (equal major-mode 'mh-show-mode)
13417 (save-window-excursion
13418 (let (pop-up-frames)
13419 (when (buffer-live-p (get-buffer folder))
13420 (progn
13421 (pop-to-buffer folder)
13422 (org-mhe-get-message-folder-from-index)
13425 (org-mhe-get-message-folder-from-index)
13427 folder
13431 (defun org-mhe-get-message-folder-from-index ()
13432 "Returns the name of the message folder in a index folder buffer."
13433 (save-excursion
13434 (mh-index-previous-folder)
13435 (re-search-forward "^\\(+.*\\)$" nil t)
13436 (message "%s" (match-string 1))))
13438 (defun org-mhe-get-message-folder ()
13439 "Return the name of the current message folder. Be careful if you
13440 use sequences."
13441 (save-excursion
13442 (if (equal major-mode 'mh-folder-mode)
13443 mh-current-folder
13444 ;; Refer to the show buffer
13445 mh-show-folder-buffer)))
13447 (defun org-mhe-get-message-num ()
13448 "Return the number of the current message. Be careful if you
13449 use sequences."
13450 (save-excursion
13451 (if (equal major-mode 'mh-folder-mode)
13452 (mh-get-msg-num nil)
13453 ;; Refer to the show buffer
13454 (mh-show-buffer-message-number))))
13456 (defun org-mhe-get-header (header)
13457 "Return a header of the message in folder mode. This will create a
13458 show buffer for the corresponding message. If you have a more clever
13459 idea..."
13460 (let* ((folder (org-mhe-get-message-folder))
13461 (num (org-mhe-get-message-num))
13462 (buffer (get-buffer-create (concat "show-" folder)))
13463 (header-field))
13464 (with-current-buffer buffer
13465 (mh-display-msg num folder)
13466 (if (equal major-mode 'mh-folder-mode)
13467 (mh-header-display)
13468 (mh-show-header-display))
13469 (set-buffer buffer)
13470 (setq header-field (mh-get-header-field header))
13471 (if (equal major-mode 'mh-folder-mode)
13472 (mh-show)
13473 (mh-show-show))
13474 header-field)))
13476 (defun org-follow-mhe-link (folder article)
13477 "Follow an MHE link to FOLDER and ARTICLE.
13478 If ARTICLE is nil FOLDER is shown. If the configuration variable
13479 `org-mhe-search-all-folders' is t and `mh-searcher' is pick,
13480 ARTICLE is searched in all folders. Indexed searches (swish++,
13481 namazu, and others supported by MH-E) will always search in all
13482 folders."
13483 (require 'mh-e)
13484 (require 'mh-search)
13485 (require 'mh-utils)
13486 (mh-find-path)
13487 (if (not article)
13488 (mh-visit-folder (mh-normalize-folder-name folder))
13489 (setq article (org-add-angle-brackets article))
13490 (mh-search-choose)
13491 (if (equal mh-searcher 'pick)
13492 (progn
13493 (mh-search folder (list "--message-id" article))
13494 (when (and org-mhe-search-all-folders
13495 (not (org-mhe-get-message-real-folder)))
13496 (kill-this-buffer)
13497 (mh-search "+" (list "--message-id" article))))
13498 (mh-search "+" article))
13499 (if (org-mhe-get-message-real-folder)
13500 (mh-show-msg 1)
13501 (kill-this-buffer)
13502 (error "Message not found"))))
13504 ;;; BibTeX links
13506 ;; Use the custom search meachnism to construct and use search strings for
13507 ;; file links to BibTeX database entries.
13509 (defun org-create-file-search-in-bibtex ()
13510 "Create the search string and description for a BibTeX database entry."
13511 (when (eq major-mode 'bibtex-mode)
13512 ;; yes, we want to construct this search string.
13513 ;; Make a good description for this entry, using names, year and the title
13514 ;; Put it into the `description' variable which is dynamically scoped.
13515 (let ((bibtex-autokey-names 1)
13516 (bibtex-autokey-names-stretch 1)
13517 (bibtex-autokey-name-case-convert-function 'identity)
13518 (bibtex-autokey-name-separator " & ")
13519 (bibtex-autokey-additional-names " et al.")
13520 (bibtex-autokey-year-length 4)
13521 (bibtex-autokey-name-year-separator " ")
13522 (bibtex-autokey-titlewords 3)
13523 (bibtex-autokey-titleword-separator " ")
13524 (bibtex-autokey-titleword-case-convert-function 'identity)
13525 (bibtex-autokey-titleword-length 'infty)
13526 (bibtex-autokey-year-title-separator ": "))
13527 (setq description (bibtex-generate-autokey)))
13528 ;; Now parse the entry, get the key and return it.
13529 (save-excursion
13530 (bibtex-beginning-of-entry)
13531 (cdr (assoc "=key=" (bibtex-parse-entry))))))
13533 (defun org-execute-file-search-in-bibtex (s)
13534 "Find the link search string S as a key for a database entry."
13535 (when (eq major-mode 'bibtex-mode)
13536 ;; Yes, we want to do the search in this file.
13537 ;; We construct a regexp that searches for "@entrytype{" followed by the key
13538 (goto-char (point-min))
13539 (and (re-search-forward (concat "@[a-zA-Z]+[ \t\n]*{[ \t\n]*"
13540 (regexp-quote s) "[ \t\n]*,") nil t)
13541 (goto-char (match-beginning 0)))
13542 (if (and (match-beginning 0) (equal current-prefix-arg '(16)))
13543 ;; Use double prefix to indicate that any web link should be browsed
13544 (let ((b (current-buffer)) (p (point)))
13545 ;; Restore the window configuration because we just use the web link
13546 (set-window-configuration org-window-config-before-follow-link)
13547 (save-excursion (set-buffer b) (goto-char p)
13548 (bibtex-url)))
13549 (recenter 0)) ; Move entry start to beginning of window
13550 ;; return t to indicate that the search is done.
13553 ;; Finally add the functions to the right hooks.
13554 (add-hook 'org-create-file-search-functions 'org-create-file-search-in-bibtex)
13555 (add-hook 'org-execute-file-search-functions 'org-execute-file-search-in-bibtex)
13557 ;; end of Bibtex link setup
13559 ;;; Following file links
13561 (defun org-open-file (path &optional in-emacs line search)
13562 "Open the file at PATH.
13563 First, this expands any special file name abbreviations. Then the
13564 configuration variable `org-file-apps' is checked if it contains an
13565 entry for this file type, and if yes, the corresponding command is launched.
13566 If no application is found, Emacs simply visits the file.
13567 With optional argument IN-EMACS, Emacs will visit the file.
13568 Optional LINE specifies a line to go to, optional SEARCH a string to
13569 search for. If LINE or SEARCH is given, the file will always be
13570 opened in Emacs.
13571 If the file does not exist, an error is thrown."
13572 (setq in-emacs (or in-emacs line search))
13573 (let* ((file (if (equal path "")
13574 buffer-file-name
13575 (substitute-in-file-name (expand-file-name path))))
13576 (apps (append org-file-apps (org-default-apps)))
13577 (remp (and (assq 'remote apps) (org-file-remote-p file)))
13578 (dirp (if remp nil (file-directory-p file)))
13579 (dfile (downcase file))
13580 (old-buffer (current-buffer))
13581 (old-pos (point))
13582 (old-mode major-mode)
13583 ext cmd)
13584 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
13585 (setq ext (match-string 1 dfile))
13586 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
13587 (setq ext (match-string 1 dfile))))
13588 (if in-emacs
13589 (setq cmd 'emacs)
13590 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
13591 (and dirp (cdr (assoc 'directory apps)))
13592 (cdr (assoc ext apps))
13593 (cdr (assoc t apps)))))
13594 (when (eq cmd 'mailcap)
13595 (require 'mailcap)
13596 (mailcap-parse-mailcaps)
13597 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
13598 (command (mailcap-mime-info mime-type)))
13599 (if (stringp command)
13600 (setq cmd command)
13601 (setq cmd 'emacs))))
13602 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
13603 (not (file-exists-p file))
13604 (not org-open-non-existing-files))
13605 (error "No such file: %s" file))
13606 (cond
13607 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
13608 ;; Remove quotes around the file name - we'll use shell-quote-argument.
13609 (while (string-match "['\"]%s['\"]" cmd)
13610 (setq cmd (replace-match "%s" t t cmd)))
13611 (while (string-match "%s" cmd)
13612 (setq cmd (replace-match
13613 (save-match-data (shell-quote-argument file))
13614 t t cmd)))
13615 (save-window-excursion
13616 (start-process-shell-command cmd nil cmd)))
13617 ((or (stringp cmd)
13618 (eq cmd 'emacs))
13619 (funcall (cdr (assq 'file org-link-frame-setup)) file)
13620 (widen)
13621 (if line (goto-line line)
13622 (if search (org-link-search search))))
13623 ((consp cmd)
13624 (eval cmd))
13625 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
13626 (and (org-mode-p) (eq old-mode 'org-mode)
13627 (or (not (equal old-buffer (current-buffer)))
13628 (not (equal old-pos (point))))
13629 (org-mark-ring-push old-pos old-buffer))))
13631 (defun org-default-apps ()
13632 "Return the default applications for this operating system."
13633 (cond
13634 ((eq system-type 'darwin)
13635 org-file-apps-defaults-macosx)
13636 ((eq system-type 'windows-nt)
13637 org-file-apps-defaults-windowsnt)
13638 (t org-file-apps-defaults-gnu)))
13640 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
13641 (defun org-file-remote-p (file)
13642 "Test whether FILE specifies a location on a remote system.
13643 Return non-nil if the location is indeed remote.
13645 For example, the filename \"/user@host:/foo\" specifies a location
13646 on the system \"/user@host:\"."
13647 (cond ((fboundp 'file-remote-p)
13648 (file-remote-p file))
13649 ((fboundp 'tramp-handle-file-remote-p)
13650 (tramp-handle-file-remote-p file))
13651 ((and (boundp 'ange-ftp-name-format)
13652 (string-match (car ange-ftp-name-format) file))
13654 (t nil)))
13657 ;;;; Hooks for remember.el, and refiling
13659 (defvar annotation) ; from remember.el, dynamically scoped in `remember-mode'
13660 (defvar initial) ; from remember.el, dynamically scoped in `remember-mode'
13662 ;;;###autoload
13663 (defun org-remember-insinuate ()
13664 "Setup remember.el for use wiht Org-mode."
13665 (require 'remember)
13666 (setq remember-annotation-functions '(org-remember-annotation))
13667 (setq remember-handler-functions '(org-remember-handler))
13668 (add-hook 'remember-mode-hook 'org-remember-apply-template))
13670 ;;;###autoload
13671 (defun org-remember-annotation ()
13672 "Return a link to the current location as an annotation for remember.el.
13673 If you are using Org-mode files as target for data storage with
13674 remember.el, then the annotations should include a link compatible with the
13675 conventions in Org-mode. This function returns such a link."
13676 (org-store-link nil))
13678 (defconst org-remember-help
13679 "Select a destination location for the note.
13680 UP/DOWN=headline TAB=cycle visibility [Q]uit RET/<left>/<right>=Store
13681 RET on headline -> Store as sublevel entry to current headline
13682 RET at beg-of-buf -> Append to file as level 2 headline
13683 <left>/<right> -> before/after current headline, same headings level")
13685 (defvar org-remember-previous-location nil)
13686 (defvar org-force-remember-template-char) ;; dynamically scoped
13688 ;; Save the major mode of the buffer we called remember from
13689 (defvar org-select-template-temp-major-mode nil)
13691 ;; Temporary store the buffer where remember was called from
13692 (defvar org-select-template-original-buffer nil)
13694 (defun org-select-remember-template (&optional use-char)
13695 (when org-remember-templates
13696 (let* ((pre-selected-templates
13697 (mapcar
13698 (lambda (tpl)
13699 (let ((ctxt (nth 5 tpl))
13700 (mode org-select-template-temp-major-mode)
13701 (buf org-select-template-original-buffer))
13702 (and (or (not ctxt) (eq ctxt t)
13703 (and (listp ctxt) (memq mode ctxt))
13704 (and (functionp ctxt)
13705 (with-current-buffer buf
13706 ;; Protect the user-defined function from error
13707 (condition-case nil (funcall ctxt) (error nil)))))
13708 tpl)))
13709 org-remember-templates))
13710 ;; If no template at this point, add the default templates:
13711 (pre-selected-templates1
13712 (if (not (delq nil pre-selected-templates))
13713 (mapcar (lambda(x) (if (not (nth 5 x)) x))
13714 org-remember-templates)
13715 pre-selected-templates))
13716 ;; Then unconditionnally add template for any contexts
13717 (pre-selected-templates2
13718 (append (mapcar (lambda(x) (if (eq (nth 5 x) t) x))
13719 org-remember-templates)
13720 (delq nil pre-selected-templates1)))
13721 (templates (mapcar (lambda (x)
13722 (if (stringp (car x))
13723 (append (list (nth 1 x) (car x)) (cddr x))
13724 (append (list (car x) "") (cdr x))))
13725 (delq nil pre-selected-templates2)))
13726 (char (or use-char
13727 (cond
13728 ((= (length templates) 1)
13729 (caar templates))
13730 ((and (boundp 'org-force-remember-template-char)
13731 org-force-remember-template-char)
13732 (if (stringp org-force-remember-template-char)
13733 (string-to-char org-force-remember-template-char)
13734 org-force-remember-template-char))
13736 (message "Select template: %s"
13737 (mapconcat
13738 (lambda (x)
13739 (cond
13740 ((not (string-match "\\S-" (nth 1 x)))
13741 (format "[%c]" (car x)))
13742 ((equal (downcase (car x))
13743 (downcase (aref (nth 1 x) 0)))
13744 (format "[%c]%s" (car x)
13745 (substring (nth 1 x) 1)))
13746 (t (format "[%c]%s" (car x) (nth 1 x)))))
13747 templates " "))
13748 (let ((inhibit-quit t) (char0 (read-char-exclusive)))
13749 (when (equal char0 ?\C-g)
13750 (jump-to-register remember-register)
13751 (kill-buffer remember-buffer))
13752 char0))))))
13753 (cddr (assoc char templates)))))
13755 (defvar x-last-selected-text)
13756 (defvar x-last-selected-text-primary)
13758 ;;;###autoload
13759 (defun org-remember-apply-template (&optional use-char skip-interactive)
13760 "Initialize *remember* buffer with template, invoke `org-mode'.
13761 This function should be placed into `remember-mode-hook' and in fact requires
13762 to be run from that hook to function properly."
13763 (if org-remember-templates
13764 (let* ((entry (org-select-remember-template use-char))
13765 (tpl (car entry))
13766 (plist-p (if org-store-link-plist t nil))
13767 (file (if (and (nth 1 entry) (stringp (nth 1 entry))
13768 (string-match "\\S-" (nth 1 entry)))
13769 (nth 1 entry)
13770 org-default-notes-file))
13771 (headline (nth 2 entry))
13772 (v-c (or (and (eq window-system 'x)
13773 (fboundp 'x-cut-buffer-or-selection-value)
13774 (x-cut-buffer-or-selection-value))
13775 (org-bound-and-true-p x-last-selected-text)
13776 (org-bound-and-true-p x-last-selected-text-primary)
13777 (and (> (length kill-ring) 0) (current-kill 0))))
13778 (v-t (format-time-string (car org-time-stamp-formats) (org-current-time)))
13779 (v-T (format-time-string (cdr org-time-stamp-formats) (org-current-time)))
13780 (v-u (concat "[" (substring v-t 1 -1) "]"))
13781 (v-U (concat "[" (substring v-T 1 -1) "]"))
13782 ;; `initial' and `annotation' are bound in `remember'
13783 (v-i (if (boundp 'initial) initial))
13784 (v-a (if (and (boundp 'annotation) annotation)
13785 (if (equal annotation "[[]]") "" annotation)
13786 ""))
13787 (v-A (if (and v-a
13788 (string-match "\\[\\(\\[.*?\\]\\)\\(\\[.*?\\]\\)?\\]" v-a))
13789 (replace-match "[\\1[%^{Link description}]]" nil nil v-a)
13790 v-a))
13791 (v-n user-full-name)
13792 (org-startup-folded nil)
13793 org-time-was-given org-end-time-was-given x
13794 prompt completions char time pos default histvar)
13795 (setq org-store-link-plist
13796 (append (list :annotation v-a :initial v-i)
13797 org-store-link-plist))
13798 (unless tpl (setq tpl "") (message "No template") (ding) (sit-for 1))
13799 (erase-buffer)
13800 (insert (substitute-command-keys
13801 (format
13802 "## Filing location: Select interactively, default, or last used:
13803 ## %s to select file and header location interactively.
13804 ## %s \"%s\" -> \"* %s\"
13805 ## C-u C-u C-c C-c \"%s\" -> \"* %s\"
13806 ## To switch templates, use `\\[org-remember]'. To abort use `C-c C-k'.\n\n"
13807 (if org-remember-store-without-prompt " C-u C-c C-c" " C-c C-c")
13808 (if org-remember-store-without-prompt " C-c C-c" " C-u C-c C-c")
13809 (abbreviate-file-name (or file org-default-notes-file))
13810 (or headline "")
13811 (or (car org-remember-previous-location) "???")
13812 (or (cdr org-remember-previous-location) "???"))))
13813 (insert tpl) (goto-char (point-min))
13814 ;; Simple %-escapes
13815 (while (re-search-forward "%\\([tTuUaiAc]\\)" nil t)
13816 (when (and initial (equal (match-string 0) "%i"))
13817 (save-match-data
13818 (let* ((lead (buffer-substring
13819 (point-at-bol) (match-beginning 0))))
13820 (setq v-i (mapconcat 'identity
13821 (org-split-string initial "\n")
13822 (concat "\n" lead))))))
13823 (replace-match
13824 (or (eval (intern (concat "v-" (match-string 1)))) "")
13825 t t))
13827 ;; %[] Insert contents of a file.
13828 (goto-char (point-min))
13829 (while (re-search-forward "%\\[\\(.+\\)\\]" nil t)
13830 (let ((start (match-beginning 0))
13831 (end (match-end 0))
13832 (filename (expand-file-name (match-string 1))))
13833 (goto-char start)
13834 (delete-region start end)
13835 (condition-case error
13836 (insert-file-contents filename)
13837 (error (insert (format "%%![Couldn't insert %s: %s]"
13838 filename error))))))
13839 ;; %() embedded elisp
13840 (goto-char (point-min))
13841 (while (re-search-forward "%\\((.+)\\)" nil t)
13842 (goto-char (match-beginning 0))
13843 (let ((template-start (point)))
13844 (forward-char 1)
13845 (let ((result
13846 (condition-case error
13847 (eval (read (current-buffer)))
13848 (error (format "%%![Error: %s]" error)))))
13849 (delete-region template-start (point))
13850 (insert result))))
13852 ;; From the property list
13853 (when plist-p
13854 (goto-char (point-min))
13855 (while (re-search-forward "%\\(:[-a-zA-Z]+\\)" nil t)
13856 (and (setq x (or (plist-get org-store-link-plist
13857 (intern (match-string 1))) ""))
13858 (replace-match x t t))))
13860 ;; Turn on org-mode in the remember buffer, set local variables
13861 (org-mode)
13862 (org-set-local 'org-finish-function 'org-remember-finalize)
13863 (if (and file (string-match "\\S-" file) (not (file-directory-p file)))
13864 (org-set-local 'org-default-notes-file file))
13865 (if (and headline (stringp headline) (string-match "\\S-" headline))
13866 (org-set-local 'org-remember-default-headline headline))
13867 ;; Interactive template entries
13868 (goto-char (point-min))
13869 (while (re-search-forward "%^\\({\\([^}]*\\)}\\)?\\([gGuUtT]\\)?" nil t)
13870 (setq char (if (match-end 3) (match-string 3))
13871 prompt (if (match-end 2) (match-string 2)))
13872 (goto-char (match-beginning 0))
13873 (replace-match "")
13874 (setq completions nil default nil)
13875 (when prompt
13876 (setq completions (org-split-string prompt "|")
13877 prompt (pop completions)
13878 default (car completions)
13879 histvar (intern (concat
13880 "org-remember-template-prompt-history::"
13881 (or prompt "")))
13882 completions (mapcar 'list completions)))
13883 (cond
13884 ((member char '("G" "g"))
13885 (let* ((org-last-tags-completion-table
13886 (org-global-tags-completion-table
13887 (if (equal char "G") (org-agenda-files) (and file (list file)))))
13888 (org-add-colon-after-tag-completion t)
13889 (ins (completing-read
13890 (if prompt (concat prompt ": ") "Tags: ")
13891 'org-tags-completion-function nil nil nil
13892 'org-tags-history)))
13893 (setq ins (mapconcat 'identity
13894 (org-split-string ins (org-re "[^[:alnum:]_@]+"))
13895 ":"))
13896 (when (string-match "\\S-" ins)
13897 (or (equal (char-before) ?:) (insert ":"))
13898 (insert ins)
13899 (or (equal (char-after) ?:) (insert ":")))))
13900 (char
13901 (setq org-time-was-given (equal (upcase char) char))
13902 (setq time (org-read-date (equal (upcase char) "U") t nil
13903 prompt))
13904 (org-insert-time-stamp time org-time-was-given
13905 (member char '("u" "U"))
13906 nil nil (list org-end-time-was-given)))
13908 (insert (org-completing-read
13909 (concat (if prompt prompt "Enter string")
13910 (if default (concat " [" default "]"))
13911 ": ")
13912 completions nil nil nil histvar default)))))
13913 (goto-char (point-min))
13914 (if (re-search-forward "%\\?" nil t)
13915 (replace-match "")
13916 (and (re-search-forward "^[^#\n]" nil t) (backward-char 1))))
13917 (org-mode)
13918 (org-set-local 'org-finish-function 'org-remember-finalize))
13919 (when (save-excursion
13920 (goto-char (point-min))
13921 (re-search-forward "%!" nil t))
13922 (replace-match "")
13923 (add-hook 'post-command-hook 'org-remember-finish-immediately 'append)))
13925 (defun org-remember-finish-immediately ()
13926 "File remember note immediately.
13927 This should be run in `post-command-hook' and will remove itself
13928 from that hook."
13929 (remove-hook 'post-command-hook 'org-remember-finish-immediately)
13930 (when org-finish-function
13931 (funcall org-finish-function)))
13933 (defvar org-clock-marker) ; Defined below
13934 (defun org-remember-finalize ()
13935 "Finalize the remember process."
13936 (unless (fboundp 'remember-finalize)
13937 (defalias 'remember-finalize 'remember-buffer))
13938 (when (and org-clock-marker
13939 (equal (marker-buffer org-clock-marker) (current-buffer)))
13940 ;; FIXME: test this, this is w/o notetaking!
13941 (let (org-log-note-clock-out) (org-clock-out)))
13942 (when buffer-file-name
13943 (save-buffer)
13944 (setq buffer-file-name nil))
13945 (remember-finalize))
13947 ;;;###autoload
13948 (defun org-remember (&optional goto org-force-remember-template-char)
13949 "Call `remember'. If this is already a remember buffer, re-apply template.
13950 If there is an active region, make sure remember uses it as initial content
13951 of the remember buffer.
13953 When called interactively with a `C-u' prefix argument GOTO, don't remember
13954 anything, just go to the file/headline where the selected template usually
13955 stores its notes. With a double prefix arg `C-u C-u', go to the last
13956 note stored by remember.
13958 Lisp programs can set ORG-FORCE-REMEMBER-TEMPLATE-CHAR to a character
13959 associated with a template in `org-remember-templates'."
13960 (interactive "P")
13961 (cond
13962 ((equal goto '(4)) (org-go-to-remember-target))
13963 ((equal goto '(16)) (org-remember-goto-last-stored))
13965 ;; set temporary variables that will be needed in
13966 ;; `org-select-remember-template'
13967 (setq org-select-template-temp-major-mode major-mode)
13968 (setq org-select-template-original-buffer (current-buffer))
13969 (if (memq org-finish-function '(remember-buffer remember-finalize))
13970 (progn
13971 (when (< (length org-remember-templates) 2)
13972 (error "No other template available"))
13973 (erase-buffer)
13974 (let ((annotation (plist-get org-store-link-plist :annotation))
13975 (initial (plist-get org-store-link-plist :initial)))
13976 (org-remember-apply-template))
13977 (message "Press C-c C-c to remember data"))
13978 (if (org-region-active-p)
13979 (remember (buffer-substring (point) (mark)))
13980 (call-interactively 'remember))))))
13982 (defun org-remember-goto-last-stored ()
13983 "Go to the location where the last remember note was stored."
13984 (interactive)
13985 (bookmark-jump "org-remember-last-stored")
13986 (message "This is the last note stored by remember"))
13988 (defun org-go-to-remember-target (&optional template-key)
13989 "Go to the target location of a remember template.
13990 The user is queried for the template."
13991 (interactive)
13992 (let* (org-select-template-temp-major-mode
13993 (entry (org-select-remember-template template-key))
13994 (file (nth 1 entry))
13995 (heading (nth 2 entry))
13996 visiting)
13997 (unless (and file (stringp file) (string-match "\\S-" file))
13998 (setq file org-default-notes-file))
13999 (unless (and heading (stringp heading) (string-match "\\S-" heading))
14000 (setq heading org-remember-default-headline))
14001 (setq visiting (org-find-base-buffer-visiting file))
14002 (if (not visiting) (find-file-noselect file))
14003 (switch-to-buffer (or visiting (get-file-buffer file)))
14004 (widen)
14005 (goto-char (point-min))
14006 (if (re-search-forward
14007 (concat "^\\*+[ \t]+" (regexp-quote heading)
14008 (org-re "\\([ \t]+:[[:alnum:]@_:]*\\)?[ \t]*$"))
14009 nil t)
14010 (goto-char (match-beginning 0))
14011 (error "Target headline not found: %s" heading))))
14013 (defvar org-note-abort nil) ; dynamically scoped
14015 ;;;###autoload
14016 (defun org-remember-handler ()
14017 "Store stuff from remember.el into an org file.
14018 First prompts for an org file. If the user just presses return, the value
14019 of `org-default-notes-file' is used.
14020 Then the command offers the headings tree of the selected file in order to
14021 file the text at a specific location.
14022 You can either immediately press RET to get the note appended to the
14023 file, or you can use vertical cursor motion and visibility cycling (TAB) to
14024 find a better place. Then press RET or <left> or <right> in insert the note.
14026 Key Cursor position Note gets inserted
14027 -----------------------------------------------------------------------------
14028 RET buffer-start as level 1 heading at end of file
14029 RET on headline as sublevel of the heading at cursor
14030 RET no heading at cursor position, level taken from context.
14031 Or use prefix arg to specify level manually.
14032 <left> on headline as same level, before current heading
14033 <right> on headline as same level, after current heading
14035 So the fastest way to store the note is to press RET RET to append it to
14036 the default file. This way your current train of thought is not
14037 interrupted, in accordance with the principles of remember.el.
14038 You can also get the fast execution without prompting by using
14039 C-u C-c C-c to exit the remember buffer. See also the variable
14040 `org-remember-store-without-prompt'.
14042 Before being stored away, the function ensures that the text has a
14043 headline, i.e. a first line that starts with a \"*\". If not, a headline
14044 is constructed from the current date and some additional data.
14046 If the variable `org-adapt-indentation' is non-nil, the entire text is
14047 also indented so that it starts in the same column as the headline
14048 \(i.e. after the stars).
14050 See also the variable `org-reverse-note-order'."
14051 (goto-char (point-min))
14052 (while (looking-at "^[ \t]*\n\\|^##.*\n")
14053 (replace-match ""))
14054 (goto-char (point-max))
14055 (beginning-of-line 1)
14056 (while (looking-at "[ \t]*$\\|##.*")
14057 (delete-region (1- (point)) (point-max))
14058 (beginning-of-line 1))
14059 (catch 'quit
14060 (if org-note-abort (throw 'quit nil))
14061 (let* ((txt (buffer-substring (point-min) (point-max)))
14062 (fastp (org-xor (equal current-prefix-arg '(4))
14063 org-remember-store-without-prompt))
14064 (file (cond
14065 (fastp org-default-notes-file)
14066 ((and (eq org-remember-interactive-interface 'refile)
14067 org-refile-targets)
14068 org-default-notes-file)
14069 ((not (and (equal current-prefix-arg '(16))
14070 org-remember-previous-location))
14071 (org-get-org-file))))
14072 (heading org-remember-default-headline)
14073 (visiting (and file (org-find-base-buffer-visiting file)))
14074 (org-startup-folded nil)
14075 (org-startup-align-all-tables nil)
14076 (org-goto-start-pos 1)
14077 spos exitcmd level indent reversed)
14078 (if (and (equal current-prefix-arg '(16)) org-remember-previous-location)
14079 (setq file (car org-remember-previous-location)
14080 heading (cdr org-remember-previous-location)
14081 fastp t))
14082 (setq current-prefix-arg nil)
14083 (if (string-match "[ \t\n]+\\'" txt)
14084 (setq txt (replace-match "" t t txt)))
14085 ;; Modify text so that it becomes a nice subtree which can be inserted
14086 ;; into an org tree.
14087 (let* ((lines (split-string txt "\n"))
14088 first)
14089 (setq first (car lines) lines (cdr lines))
14090 (if (string-match "^\\*+ " first)
14091 ;; Is already a headline
14092 (setq indent nil)
14093 ;; We need to add a headline: Use time and first buffer line
14094 (setq lines (cons first lines)
14095 first (concat "* " (current-time-string)
14096 " (" (remember-buffer-desc) ")")
14097 indent " "))
14098 (if (and org-adapt-indentation indent)
14099 (setq lines (mapcar
14100 (lambda (x)
14101 (if (string-match "\\S-" x)
14102 (concat indent x) x))
14103 lines)))
14104 (setq txt (concat first "\n"
14105 (mapconcat 'identity lines "\n"))))
14106 (if (string-match "\n[ \t]*\n[ \t\n]*\\'" txt)
14107 (setq txt (replace-match "\n\n" t t txt))
14108 (if (string-match "[ \t\n]*\\'" txt)
14109 (setq txt (replace-match "\n" t t txt))))
14110 ;; Put the modified text back into the remember buffer, for refile.
14111 (erase-buffer)
14112 (insert txt)
14113 (goto-char (point-min))
14114 (when (and (eq org-remember-interactive-interface 'refile)
14115 (not fastp))
14116 (org-refile nil (or visiting (find-file-noselect file)))
14117 (throw 'quit t))
14118 ;; Find the file
14119 (if (not visiting) (find-file-noselect file))
14120 (with-current-buffer (or visiting (get-file-buffer file))
14121 (unless (org-mode-p)
14122 (error "Target files for remember notes must be in Org-mode"))
14123 (save-excursion
14124 (save-restriction
14125 (widen)
14126 (and (goto-char (point-min))
14127 (not (re-search-forward "^\\* " nil t))
14128 (insert "\n* " (or heading "Notes") "\n"))
14129 (setq reversed (org-notes-order-reversed-p))
14131 ;; Find the default location
14132 (when (and heading (stringp heading) (string-match "\\S-" heading))
14133 (goto-char (point-min))
14134 (if (re-search-forward
14135 (concat "^\\*+[ \t]+" (regexp-quote heading)
14136 (org-re "\\([ \t]+:[[:alnum:]@_:]*\\)?[ \t]*$"))
14137 nil t)
14138 (setq org-goto-start-pos (match-beginning 0))
14139 (when fastp
14140 (goto-char (point-max))
14141 (unless (bolp) (newline))
14142 (insert "* " heading "\n")
14143 (setq org-goto-start-pos (point-at-bol 0)))))
14145 ;; Ask the User for a location, using the appropriate interface
14146 (cond
14147 (fastp (setq spos org-goto-start-pos
14148 exitcmd 'return))
14149 ((eq org-remember-interactive-interface 'outline)
14150 (setq spos (org-get-location (current-buffer)
14151 org-remember-help)
14152 exitcmd (cdr spos)
14153 spos (car spos)))
14154 ((eq org-remember-interactive-interface 'outline-path-completion)
14155 (let ((org-refile-targets '((nil . (:maxlevel . 10))))
14156 (org-refile-use-outline-path t))
14157 (setq spos (org-refile-get-location "Heading: ")
14158 exitcmd 'return
14159 spos (nth 3 spos))))
14160 (t (error "this should not hapen")))
14161 (if (not spos) (throw 'quit nil)) ; return nil to show we did
14162 ; not handle this note
14163 (goto-char spos)
14164 (cond ((org-on-heading-p t)
14165 (org-back-to-heading t)
14166 (setq level (funcall outline-level))
14167 (cond
14168 ((eq exitcmd 'return)
14169 ;; sublevel of current
14170 (setq org-remember-previous-location
14171 (cons (abbreviate-file-name file)
14172 (org-get-heading 'notags)))
14173 (if reversed
14174 (outline-next-heading)
14175 (org-end-of-subtree t)
14176 (if (not (bolp))
14177 (if (looking-at "[ \t]*\n")
14178 (beginning-of-line 2)
14179 (end-of-line 1)
14180 (insert "\n"))))
14181 (bookmark-set "org-remember-last-stored")
14182 (org-paste-subtree (org-get-valid-level level 1) txt))
14183 ((eq exitcmd 'left)
14184 ;; before current
14185 (bookmark-set "org-remember-last-stored")
14186 (org-paste-subtree level txt))
14187 ((eq exitcmd 'right)
14188 ;; after current
14189 (org-end-of-subtree t)
14190 (bookmark-set "org-remember-last-stored")
14191 (org-paste-subtree level txt))
14192 (t (error "This should not happen"))))
14194 ((and (bobp) (not reversed))
14195 ;; Put it at the end, one level below level 1
14196 (save-restriction
14197 (widen)
14198 (goto-char (point-max))
14199 (if (not (bolp)) (newline))
14200 (bookmark-set "org-remember-last-stored")
14201 (org-paste-subtree (org-get-valid-level 1 1) txt)))
14203 ((and (bobp) reversed)
14204 ;; Put it at the start, as level 1
14205 (save-restriction
14206 (widen)
14207 (goto-char (point-min))
14208 (re-search-forward "^\\*+ " nil t)
14209 (beginning-of-line 1)
14210 (bookmark-set "org-remember-last-stored")
14211 (org-paste-subtree 1 txt)))
14213 ;; Put it right there, with automatic level determined by
14214 ;; org-paste-subtree or from prefix arg
14215 (bookmark-set "org-remember-last-stored")
14216 (org-paste-subtree
14217 (if (numberp current-prefix-arg) current-prefix-arg)
14218 txt)))
14219 (when remember-save-after-remembering
14220 (save-buffer)
14221 (if (not visiting) (kill-buffer (current-buffer)))))))))
14223 t) ;; return t to indicate that we took care of this note.
14225 (defun org-get-org-file ()
14226 "Read a filename, with default directory `org-directory'."
14227 (let ((default (or org-default-notes-file remember-data-file)))
14228 (read-file-name (format "File name [%s]: " default)
14229 (file-name-as-directory org-directory)
14230 default)))
14232 (defun org-notes-order-reversed-p ()
14233 "Check if the current file should receive notes in reversed order."
14234 (cond
14235 ((not org-reverse-note-order) nil)
14236 ((eq t org-reverse-note-order) t)
14237 ((not (listp org-reverse-note-order)) nil)
14238 (t (catch 'exit
14239 (let ((all org-reverse-note-order)
14240 entry)
14241 (while (setq entry (pop all))
14242 (if (string-match (car entry) buffer-file-name)
14243 (throw 'exit (cdr entry))))
14244 nil)))))
14246 ;;; Refiling
14248 (defvar org-refile-target-table nil
14249 "The list of refile targets, created by `org-refile'.")
14251 (defvar org-agenda-new-buffers nil
14252 "Buffers created to visit agenda files.")
14254 (defun org-get-refile-targets (&optional default-buffer)
14255 "Produce a table with refile targets."
14256 (let ((entries (or org-refile-targets '((nil . (:level . 1)))))
14257 targets txt re files f desc descre)
14258 (with-current-buffer (or default-buffer (current-buffer))
14259 (while (setq entry (pop entries))
14260 (setq files (car entry) desc (cdr entry))
14261 (cond
14262 ((null files) (setq files (list (current-buffer))))
14263 ((eq files 'org-agenda-files)
14264 (setq files (org-agenda-files 'unrestricted)))
14265 ((and (symbolp files) (fboundp files))
14266 (setq files (funcall files)))
14267 ((and (symbolp files) (boundp files))
14268 (setq files (symbol-value files))))
14269 (if (stringp files) (setq files (list files)))
14270 (cond
14271 ((eq (car desc) :tag)
14272 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
14273 ((eq (car desc) :todo)
14274 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
14275 ((eq (car desc) :regexp)
14276 (setq descre (cdr desc)))
14277 ((eq (car desc) :level)
14278 (setq descre (concat "^\\*\\{" (number-to-string
14279 (if org-odd-levels-only
14280 (1- (* 2 (cdr desc)))
14281 (cdr desc)))
14282 "\\}[ \t]")))
14283 ((eq (car desc) :maxlevel)
14284 (setq descre (concat "^\\*\\{1," (number-to-string
14285 (if org-odd-levels-only
14286 (1- (* 2 (cdr desc)))
14287 (cdr desc)))
14288 "\\}[ \t]")))
14289 (t (error "Bad refiling target description %s" desc)))
14290 (while (setq f (pop files))
14291 (save-excursion
14292 (set-buffer (if (bufferp f) f (org-get-agenda-file-buffer f)))
14293 (if (bufferp f) (setq f (buffer-file-name (buffer-base-buffer f))))
14294 (save-excursion
14295 (save-restriction
14296 (widen)
14297 (goto-char (point-min))
14298 (while (re-search-forward descre nil t)
14299 (goto-char (point-at-bol))
14300 (when (looking-at org-complex-heading-regexp)
14301 (setq txt (match-string 4)
14302 re (concat "^" (regexp-quote
14303 (buffer-substring (match-beginning 1)
14304 (match-end 4)))))
14305 (if (match-end 5) (setq re (concat re "[ \t]+"
14306 (regexp-quote
14307 (match-string 5)))))
14308 (setq re (concat re "[ \t]*$"))
14309 (when org-refile-use-outline-path
14310 (setq txt (mapconcat 'identity
14311 (append
14312 (if (eq org-refile-use-outline-path 'file)
14313 (list (file-name-nondirectory
14314 (buffer-file-name (buffer-base-buffer))))
14315 (if (eq org-refile-use-outline-path 'full-file-path)
14316 (list (buffer-file-name (buffer-base-buffer)))))
14317 (org-get-outline-path)
14318 (list txt))
14319 "/")))
14320 (push (list txt f re (point)) targets))
14321 (goto-char (point-at-eol))))))))
14322 (nreverse targets))))
14324 (defun org-get-outline-path ()
14325 "Return the outline path to the current entry, as a list."
14326 (let (rtn)
14327 (save-excursion
14328 (while (org-up-heading-safe)
14329 (when (looking-at org-complex-heading-regexp)
14330 (push (org-match-string-no-properties 4) rtn)))
14331 rtn)))
14333 (defvar org-refile-history nil
14334 "History for refiling operations.")
14336 (defun org-refile (&optional goto default-buffer)
14337 "Move the entry at point to another heading.
14338 The list of target headings is compiled using the information in
14339 `org-refile-targets', which see. This list is created upon first use, and
14340 you can update it by calling this command with a double prefix (`C-u C-u').
14341 FIXME: Can we find a better way of updating?
14343 At the target location, the entry is filed as a subitem of the target heading.
14344 Depending on `org-reverse-note-order', the new subitem will either be the
14345 first of the last subitem.
14347 With prefix arg GOTO, the command will only visit the target location,
14348 not actually move anything.
14349 With a double prefix `C-c C-c', go to the location where the last refiling
14350 operation has put the subtree.
14352 With a double prefix argument, the command can be used to jump to any
14353 heading in the current buffer."
14354 (interactive "P")
14355 (let* ((cbuf (current-buffer))
14356 (filename (buffer-file-name (buffer-base-buffer cbuf)))
14357 pos it nbuf file re level reversed)
14358 (if (equal goto '(16))
14359 (org-refile-goto-last-stored)
14360 (when (setq it (org-refile-get-location
14361 (if goto "Goto: " "Refile to: ") default-buffer))
14362 (setq file (nth 1 it)
14363 re (nth 2 it)
14364 pos (nth 3 it))
14365 (setq nbuf (or (find-buffer-visiting file)
14366 (find-file-noselect file)))
14367 (if goto
14368 (progn
14369 (switch-to-buffer nbuf)
14370 (goto-char pos)
14371 (org-show-context 'org-goto))
14372 (org-copy-special)
14373 (save-excursion
14374 (set-buffer (setq nbuf (or (find-buffer-visiting file)
14375 (find-file-noselect file))))
14376 (setq reversed (org-notes-order-reversed-p))
14377 (save-excursion
14378 (save-restriction
14379 (widen)
14380 (goto-char pos)
14381 (looking-at outline-regexp)
14382 (setq level (org-get-valid-level (funcall outline-level) 1))
14383 (goto-char
14384 (if reversed
14385 (outline-next-heading)
14386 (or (save-excursion (outline-get-next-sibling))
14387 (org-end-of-subtree t t)
14388 (point-max))))
14389 (bookmark-set "org-refile-last-stored")
14390 (org-paste-subtree level))))
14391 (org-cut-special)
14392 (message "Entry refiled to \"%s\"" (car it)))))))
14394 (defun org-refile-goto-last-stored ()
14395 "Go to the location where the last refile was stored."
14396 (interactive)
14397 (bookmark-jump "org-refile-last-stored")
14398 (message "This is the location of the last refile"))
14400 (defun org-refile-get-location (&optional prompt default-buffer)
14401 "Prompt the user for a refile location, using PROMPT."
14402 (let ((org-refile-targets org-refile-targets)
14403 (org-refile-use-outline-path org-refile-use-outline-path))
14404 (setq org-refile-target-table (org-get-refile-targets default-buffer)))
14405 (unless org-refile-target-table
14406 (error "No refile targets"))
14407 (let* ((cbuf (current-buffer))
14408 (filename (buffer-file-name (buffer-base-buffer cbuf)))
14409 (fname (and filename (file-truename filename)))
14410 (tbl (mapcar
14411 (lambda (x)
14412 (if (not (equal fname (file-truename (nth 1 x))))
14413 (cons (concat (car x) " (" (file-name-nondirectory
14414 (nth 1 x)) ")")
14415 (cdr x))
14417 org-refile-target-table))
14418 (completion-ignore-case t))
14419 (assoc (completing-read prompt tbl nil t nil 'org-refile-history)
14420 tbl)))
14422 ;;;; Dynamic blocks
14424 (defun org-find-dblock (name)
14425 "Find the first dynamic block with name NAME in the buffer.
14426 If not found, stay at current position and return nil."
14427 (let (pos)
14428 (save-excursion
14429 (goto-char (point-min))
14430 (setq pos (and (re-search-forward (concat "^#\\+BEGIN:[ \t]+" name "\\>")
14431 nil t)
14432 (match-beginning 0))))
14433 (if pos (goto-char pos))
14434 pos))
14436 (defconst org-dblock-start-re
14437 "^#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
14438 "Matches the startline of a dynamic block, with parameters.")
14440 (defconst org-dblock-end-re "^#\\+END\\([: \t\r\n]\\|$\\)"
14441 "Matches the end of a dyhamic block.")
14443 (defun org-create-dblock (plist)
14444 "Create a dynamic block section, with parameters taken from PLIST.
14445 PLIST must containe a :name entry which is used as name of the block."
14446 (unless (bolp) (newline))
14447 (let ((name (plist-get plist :name)))
14448 (insert "#+BEGIN: " name)
14449 (while plist
14450 (if (eq (car plist) :name)
14451 (setq plist (cddr plist))
14452 (insert " " (prin1-to-string (pop plist)))))
14453 (insert "\n\n#+END:\n")
14454 (beginning-of-line -2)))
14456 (defun org-prepare-dblock ()
14457 "Prepare dynamic block for refresh.
14458 This empties the block, puts the cursor at the insert position and returns
14459 the property list including an extra property :name with the block name."
14460 (unless (looking-at org-dblock-start-re)
14461 (error "Not at a dynamic block"))
14462 (let* ((begdel (1+ (match-end 0)))
14463 (name (org-no-properties (match-string 1)))
14464 (params (append (list :name name)
14465 (read (concat "(" (match-string 3) ")")))))
14466 (unless (re-search-forward org-dblock-end-re nil t)
14467 (error "Dynamic block not terminated"))
14468 (setq params
14469 (append params
14470 (list :content (buffer-substring
14471 begdel (match-beginning 0)))))
14472 (delete-region begdel (match-beginning 0))
14473 (goto-char begdel)
14474 (open-line 1)
14475 params))
14477 (defun org-map-dblocks (&optional command)
14478 "Apply COMMAND to all dynamic blocks in the current buffer.
14479 If COMMAND is not given, use `org-update-dblock'."
14480 (let ((cmd (or command 'org-update-dblock))
14481 pos)
14482 (save-excursion
14483 (goto-char (point-min))
14484 (while (re-search-forward org-dblock-start-re nil t)
14485 (goto-char (setq pos (match-beginning 0)))
14486 (condition-case nil
14487 (funcall cmd)
14488 (error (message "Error during update of dynamic block")))
14489 (goto-char pos)
14490 (unless (re-search-forward org-dblock-end-re nil t)
14491 (error "Dynamic block not terminated"))))))
14493 (defun org-dblock-update (&optional arg)
14494 "User command for updating dynamic blocks.
14495 Update the dynamic block at point. With prefix ARG, update all dynamic
14496 blocks in the buffer."
14497 (interactive "P")
14498 (if arg
14499 (org-update-all-dblocks)
14500 (or (looking-at org-dblock-start-re)
14501 (org-beginning-of-dblock))
14502 (org-update-dblock)))
14504 (defun org-update-dblock ()
14505 "Update the dynamic block at point
14506 This means to empty the block, parse for parameters and then call
14507 the correct writing function."
14508 (save-window-excursion
14509 (let* ((pos (point))
14510 (line (org-current-line))
14511 (params (org-prepare-dblock))
14512 (name (plist-get params :name))
14513 (cmd (intern (concat "org-dblock-write:" name))))
14514 (message "Updating dynamic block `%s' at line %d..." name line)
14515 (funcall cmd params)
14516 (message "Updating dynamic block `%s' at line %d...done" name line)
14517 (goto-char pos))))
14519 (defun org-beginning-of-dblock ()
14520 "Find the beginning of the dynamic block at point.
14521 Error if there is no scuh block at point."
14522 (let ((pos (point))
14523 beg)
14524 (end-of-line 1)
14525 (if (and (re-search-backward org-dblock-start-re nil t)
14526 (setq beg (match-beginning 0))
14527 (re-search-forward org-dblock-end-re nil t)
14528 (> (match-end 0) pos))
14529 (goto-char beg)
14530 (goto-char pos)
14531 (error "Not in a dynamic block"))))
14533 (defun org-update-all-dblocks ()
14534 "Update all dynamic blocks in the buffer.
14535 This function can be used in a hook."
14536 (when (org-mode-p)
14537 (org-map-dblocks 'org-update-dblock)))
14540 ;;;; Completion
14542 (defconst org-additional-option-like-keywords
14543 '("BEGIN_HTML" "BEGIN_LaTeX" "END_HTML" "END_LaTeX"
14544 "ORGTBL" "HTML:" "LaTeX:" "BEGIN:" "END:" "DATE:" "TBLFM"
14545 "BEGIN_EXAMPLE" "END_EXAMPLE"))
14547 (defun org-complete (&optional arg)
14548 "Perform completion on word at point.
14549 At the beginning of a headline, this completes TODO keywords as given in
14550 `org-todo-keywords'.
14551 If the current word is preceded by a backslash, completes the TeX symbols
14552 that are supported for HTML support.
14553 If the current word is preceded by \"#+\", completes special words for
14554 setting file options.
14555 In the line after \"#+STARTUP:, complete valid keywords.\"
14556 At all other locations, this simply calls the value of
14557 `org-completion-fallback-command'."
14558 (interactive "P")
14559 (org-without-partial-completion
14560 (catch 'exit
14561 (let* ((end (point))
14562 (beg1 (save-excursion
14563 (skip-chars-backward (org-re "[:alnum:]_@"))
14564 (point)))
14565 (beg (save-excursion
14566 (skip-chars-backward "a-zA-Z0-9_:$")
14567 (point)))
14568 (confirm (lambda (x) (stringp (car x))))
14569 (searchhead (equal (char-before beg) ?*))
14570 (tag (and (equal (char-before beg1) ?:)
14571 (equal (char-after (point-at-bol)) ?*)))
14572 (prop (and (equal (char-before beg1) ?:)
14573 (not (equal (char-after (point-at-bol)) ?*))))
14574 (texp (equal (char-before beg) ?\\))
14575 (link (equal (char-before beg) ?\[))
14576 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
14577 beg)
14578 "#+"))
14579 (startup (string-match "^#\\+STARTUP:.*"
14580 (buffer-substring (point-at-bol) (point))))
14581 (completion-ignore-case opt)
14582 (type nil)
14583 (tbl nil)
14584 (table (cond
14585 (opt
14586 (setq type :opt)
14587 (append
14588 (mapcar
14589 (lambda (x)
14590 (string-match "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
14591 (cons (match-string 2 x) (match-string 1 x)))
14592 (org-split-string (org-get-current-options) "\n"))
14593 (mapcar 'list org-additional-option-like-keywords)))
14594 (startup
14595 (setq type :startup)
14596 org-startup-options)
14597 (link (append org-link-abbrev-alist-local
14598 org-link-abbrev-alist))
14599 (texp
14600 (setq type :tex)
14601 org-html-entities)
14602 ((string-match "\\`\\*+[ \t]+\\'"
14603 (buffer-substring (point-at-bol) beg))
14604 (setq type :todo)
14605 (mapcar 'list org-todo-keywords-1))
14606 (searchhead
14607 (setq type :searchhead)
14608 (save-excursion
14609 (goto-char (point-min))
14610 (while (re-search-forward org-todo-line-regexp nil t)
14611 (push (list
14612 (org-make-org-heading-search-string
14613 (match-string 3) t))
14614 tbl)))
14615 tbl)
14616 (tag (setq type :tag beg beg1)
14617 (or org-tag-alist (org-get-buffer-tags)))
14618 (prop (setq type :prop beg beg1)
14619 (mapcar 'list (org-buffer-property-keys nil t t)))
14620 (t (progn
14621 (call-interactively org-completion-fallback-command)
14622 (throw 'exit nil)))))
14623 (pattern (buffer-substring-no-properties beg end))
14624 (completion (try-completion pattern table confirm)))
14625 (cond ((eq completion t)
14626 (if (not (assoc (upcase pattern) table))
14627 (message "Already complete")
14628 (if (equal type :opt)
14629 (insert (substring (cdr (assoc (upcase pattern) table))
14630 (length pattern)))
14631 (if (memq type '(:tag :prop)) (insert ":")))))
14632 ((null completion)
14633 (message "Can't find completion for \"%s\"" pattern)
14634 (ding))
14635 ((not (string= pattern completion))
14636 (delete-region beg end)
14637 (if (string-match " +$" completion)
14638 (setq completion (replace-match "" t t completion)))
14639 (insert completion)
14640 (if (get-buffer-window "*Completions*")
14641 (delete-window (get-buffer-window "*Completions*")))
14642 (if (assoc completion table)
14643 (if (eq type :todo) (insert " ")
14644 (if (memq type '(:tag :prop)) (insert ":"))))
14645 (if (and (equal type :opt) (assoc completion table))
14646 (message "%s" (substitute-command-keys
14647 "Press \\[org-complete] again to insert example settings"))))
14649 (message "Making completion list...")
14650 (let ((list (sort (all-completions pattern table confirm)
14651 'string<)))
14652 (with-output-to-temp-buffer "*Completions*"
14653 (condition-case nil
14654 ;; Protection needed for XEmacs and emacs 21
14655 (display-completion-list list pattern)
14656 (error (display-completion-list list)))))
14657 (message "Making completion list...%s" "done")))))))
14659 ;;;; TODO, DEADLINE, Comments
14661 (defun org-toggle-comment ()
14662 "Change the COMMENT state of an entry."
14663 (interactive)
14664 (save-excursion
14665 (org-back-to-heading)
14666 (let (case-fold-search)
14667 (if (looking-at (concat outline-regexp
14668 "\\( *\\<" org-comment-string "\\>[ \t]*\\)"))
14669 (replace-match "" t t nil 1)
14670 (if (looking-at outline-regexp)
14671 (progn
14672 (goto-char (match-end 0))
14673 (insert org-comment-string " ")))))))
14675 (defvar org-last-todo-state-is-todo nil
14676 "This is non-nil when the last TODO state change led to a TODO state.
14677 If the last change removed the TODO tag or switched to DONE, then
14678 this is nil.")
14680 (defvar org-setting-tags nil) ; dynamically skiped
14682 ;; FIXME: better place
14683 (defun org-property-or-variable-value (var &optional inherit)
14684 "Check if there is a property fixing the value of VAR.
14685 If yes, return this value. If not, return the current value of the variable."
14686 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
14687 (if (and prop (stringp prop) (string-match "\\S-" prop))
14688 (read prop)
14689 (symbol-value var))))
14691 (defun org-parse-local-options (string var)
14692 "Parse STRING for startup setting relevant for variable VAR."
14693 (let ((rtn (symbol-value var))
14694 e opts)
14695 (save-match-data
14696 (if (or (not string) (not (string-match "\\S-" string)))
14698 (setq opts (delq nil (mapcar (lambda (x)
14699 (setq e (assoc x org-startup-options))
14700 (if (eq (nth 1 e) var) e nil))
14701 (org-split-string string "[ \t]+"))))
14702 (if (not opts)
14704 (setq rtn nil)
14705 (while (setq e (pop opts))
14706 (if (not (nth 3 e))
14707 (setq rtn (nth 2 e))
14708 (if (not (listp rtn)) (setq rtn nil))
14709 (push (nth 2 e) rtn)))
14710 rtn)))))
14712 (defvar org-blocker-hook nil
14713 "Hook for functions that are allowed to block a state change.
14715 Each function gets as its single argument a property list, see
14716 `org-trigger-hook' for more information about this list.
14718 If any of the functions in this hook returns nil, the state change
14719 is blocked.")
14721 (defvar org-trigger-hook nil
14722 "Hook for functions that are triggered by a state change.
14724 Each function gets as its single argument a property list with at least
14725 the following elements:
14727 (:type type-of-change :position pos-at-entry-start
14728 :from old-state :to new-state)
14730 Depending on the type, more properties may be present.
14732 This mechanism is currently implemented for:
14734 TODO state changes
14735 ------------------
14736 :type todo-state-change
14737 :from previous state (keyword as a string), or nil
14738 :to new state (keyword as a string), or nil")
14741 (defun org-todo (&optional arg)
14742 "Change the TODO state of an item.
14743 The state of an item is given by a keyword at the start of the heading,
14744 like
14745 *** TODO Write paper
14746 *** DONE Call mom
14748 The different keywords are specified in the variable `org-todo-keywords'.
14749 By default the available states are \"TODO\" and \"DONE\".
14750 So for this example: when the item starts with TODO, it is changed to DONE.
14751 When it starts with DONE, the DONE is removed. And when neither TODO nor
14752 DONE are present, add TODO at the beginning of the heading.
14754 With C-u prefix arg, use completion to determine the new state.
14755 With numeric prefix arg, switch to that state.
14757 For calling through lisp, arg is also interpreted in the following way:
14758 'none -> empty state
14759 \"\"(empty string) -> switch to empty state
14760 'done -> switch to DONE
14761 'nextset -> switch to the next set of keywords
14762 'previousset -> switch to the previous set of keywords
14763 \"WAITING\" -> switch to the specified keyword, but only if it
14764 really is a member of `org-todo-keywords'."
14765 (interactive "P")
14766 (save-excursion
14767 (catch 'exit
14768 (org-back-to-heading)
14769 (if (looking-at outline-regexp) (goto-char (1- (match-end 0))))
14770 (or (looking-at (concat " +" org-todo-regexp " *"))
14771 (looking-at " *"))
14772 (let* ((match-data (match-data))
14773 (startpos (point-at-bol))
14774 (logging (save-match-data (org-entry-get nil "LOGGING" t)))
14775 (org-log-done org-log-done)
14776 (org-log-repeat org-log-repeat)
14777 (org-todo-log-states org-todo-log-states)
14778 (this (match-string 1))
14779 (hl-pos (match-beginning 0))
14780 (head (org-get-todo-sequence-head this))
14781 (ass (assoc head org-todo-kwd-alist))
14782 (interpret (nth 1 ass))
14783 (done-word (nth 3 ass))
14784 (final-done-word (nth 4 ass))
14785 (last-state (or this ""))
14786 (completion-ignore-case t)
14787 (member (member this org-todo-keywords-1))
14788 (tail (cdr member))
14789 (state (cond
14790 ((and org-todo-key-trigger
14791 (or (and (equal arg '(4)) (eq org-use-fast-todo-selection 'prefix))
14792 (and (not arg) org-use-fast-todo-selection
14793 (not (eq org-use-fast-todo-selection 'prefix)))))
14794 ;; Use fast selection
14795 (org-fast-todo-selection))
14796 ((and (equal arg '(4))
14797 (or (not org-use-fast-todo-selection)
14798 (not org-todo-key-trigger)))
14799 ;; Read a state with completion
14800 (completing-read "State: " (mapcar (lambda(x) (list x))
14801 org-todo-keywords-1)
14802 nil t))
14803 ((eq arg 'right)
14804 (if this
14805 (if tail (car tail) nil)
14806 (car org-todo-keywords-1)))
14807 ((eq arg 'left)
14808 (if (equal member org-todo-keywords-1)
14810 (if this
14811 (nth (- (length org-todo-keywords-1) (length tail) 2)
14812 org-todo-keywords-1)
14813 (org-last org-todo-keywords-1))))
14814 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
14815 (setq arg nil))) ; hack to fall back to cycling
14816 (arg
14817 ;; user or caller requests a specific state
14818 (cond
14819 ((equal arg "") nil)
14820 ((eq arg 'none) nil)
14821 ((eq arg 'done) (or done-word (car org-done-keywords)))
14822 ((eq arg 'nextset)
14823 (or (car (cdr (member head org-todo-heads)))
14824 (car org-todo-heads)))
14825 ((eq arg 'previousset)
14826 (let ((org-todo-heads (reverse org-todo-heads)))
14827 (or (car (cdr (member head org-todo-heads)))
14828 (car org-todo-heads))))
14829 ((car (member arg org-todo-keywords-1)))
14830 ((nth (1- (prefix-numeric-value arg))
14831 org-todo-keywords-1))))
14832 ((null member) (or head (car org-todo-keywords-1)))
14833 ((equal this final-done-word) nil) ;; -> make empty
14834 ((null tail) nil) ;; -> first entry
14835 ((eq interpret 'sequence)
14836 (car tail))
14837 ((memq interpret '(type priority))
14838 (if (eq this-command last-command)
14839 (car tail)
14840 (if (> (length tail) 0)
14841 (or done-word (car org-done-keywords))
14842 nil)))
14843 (t nil)))
14844 (next (if state (concat " " state " ") " "))
14845 (change-plist (list :type 'todo-state-change :from this :to state
14846 :position startpos))
14847 dolog now-done-p)
14848 (when org-blocker-hook
14849 (unless (save-excursion
14850 (save-match-data
14851 (run-hook-with-args-until-failure
14852 'org-blocker-hook change-plist)))
14853 (if (interactive-p)
14854 (error "TODO state change from %s to %s blocked" this state)
14855 ;; fail silently
14856 (message "TODO state change from %s to %s blocked" this state)
14857 (throw 'exit nil))))
14858 (store-match-data match-data)
14859 (replace-match next t t)
14860 (unless (pos-visible-in-window-p hl-pos)
14861 (message "TODO state changed to %s" (org-trim next)))
14862 (unless head
14863 (setq head (org-get-todo-sequence-head state)
14864 ass (assoc head org-todo-kwd-alist)
14865 interpret (nth 1 ass)
14866 done-word (nth 3 ass)
14867 final-done-word (nth 4 ass)))
14868 (when (memq arg '(nextset previousset))
14869 (message "Keyword-Set %d/%d: %s"
14870 (- (length org-todo-sets) -1
14871 (length (memq (assoc state org-todo-sets) org-todo-sets)))
14872 (length org-todo-sets)
14873 (mapconcat 'identity (assoc state org-todo-sets) " ")))
14874 (setq org-last-todo-state-is-todo
14875 (not (member state org-done-keywords)))
14876 (setq now-done-p (and (member state org-done-keywords)
14877 (not (member this org-done-keywords))))
14878 (and logging (org-local-logging logging))
14879 (when (and (or org-todo-log-states org-log-done)
14880 (not (memq arg '(nextset previousset))))
14881 ;; we need to look at recording a time and note
14882 (setq dolog (or (nth 1 (assoc state org-todo-log-states))
14883 (nth 2 (assoc this org-todo-log-states))))
14884 (when (and state
14885 (member state org-not-done-keywords)
14886 (not (member this org-not-done-keywords)))
14887 ;; This is now a todo state and was not one before
14888 ;; If there was a CLOSED time stamp, get rid of it.
14889 (org-add-planning-info nil nil 'closed))
14890 (when (and now-done-p org-log-done)
14891 ;; It is now done, and it was not done before
14892 (org-add-planning-info 'closed (org-current-time))
14893 (if (and (not dolog) (eq 'note org-log-done))
14894 (org-add-log-maybe 'done state 'findpos 'note)))
14895 (when (and state dolog)
14896 ;; This is a non-nil state, and we need to log it
14897 (org-add-log-maybe 'state state 'findpos dolog)))
14898 ;; Fixup tag positioning
14899 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
14900 (run-hooks 'org-after-todo-state-change-hook)
14901 (if (and arg (not (member state org-done-keywords)))
14902 (setq head (org-get-todo-sequence-head state)))
14903 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
14904 ;; Do we need to trigger a repeat?
14905 (when now-done-p (org-auto-repeat-maybe state))
14906 ;; Fixup cursor location if close to the keyword
14907 (if (and (outline-on-heading-p)
14908 (not (bolp))
14909 (save-excursion (beginning-of-line 1)
14910 (looking-at org-todo-line-regexp))
14911 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
14912 (progn
14913 (goto-char (or (match-end 2) (match-end 1)))
14914 (just-one-space)))
14915 (when org-trigger-hook
14916 (save-excursion
14917 (run-hook-with-args 'org-trigger-hook change-plist)))))))
14919 (defun org-local-logging (value)
14920 "Get logging settings from a property VALUE."
14921 (let* (words w a)
14922 ;; directly set the variables, they are already local.
14923 (setq org-log-done nil
14924 org-log-repeat nil
14925 org-todo-log-states nil)
14926 (setq words (org-split-string value))
14927 (while (setq w (pop words))
14928 (cond
14929 ((setq a (assoc w org-startup-options))
14930 (and (member (nth 1 a) '(org-log-done org-log-repeat))
14931 (set (nth 1 a) (nth 2 a))))
14932 ((setq a (org-extract-log-state-settings w))
14933 (and (member (car a) org-todo-keywords-1)
14934 (push a org-todo-log-states)))))))
14936 (defun org-get-todo-sequence-head (kwd)
14937 "Return the head of the TODO sequence to which KWD belongs.
14938 If KWD is not set, check if there is a text property remembering the
14939 right sequence."
14940 (let (p)
14941 (cond
14942 ((not kwd)
14943 (or (get-text-property (point-at-bol) 'org-todo-head)
14944 (progn
14945 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
14946 nil (point-at-eol)))
14947 (get-text-property p 'org-todo-head))))
14948 ((not (member kwd org-todo-keywords-1))
14949 (car org-todo-keywords-1))
14950 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
14952 (defun org-fast-todo-selection ()
14953 "Fast TODO keyword selection with single keys.
14954 Returns the new TODO keyword, or nil if no state change should occur."
14955 (let* ((fulltable org-todo-key-alist)
14956 (done-keywords org-done-keywords) ;; needed for the faces.
14957 (maxlen (apply 'max (mapcar
14958 (lambda (x)
14959 (if (stringp (car x)) (string-width (car x)) 0))
14960 fulltable)))
14961 (expert nil)
14962 (fwidth (+ maxlen 3 1 3))
14963 (ncol (/ (- (window-width) 4) fwidth))
14964 tg cnt e c tbl
14965 groups ingroup)
14966 (save-window-excursion
14967 (if expert
14968 (set-buffer (get-buffer-create " *Org todo*"))
14969 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
14970 (erase-buffer)
14971 (org-set-local 'org-done-keywords done-keywords)
14972 (setq tbl fulltable cnt 0)
14973 (while (setq e (pop tbl))
14974 (cond
14975 ((equal e '(:startgroup))
14976 (push '() groups) (setq ingroup t)
14977 (when (not (= cnt 0))
14978 (setq cnt 0)
14979 (insert "\n"))
14980 (insert "{ "))
14981 ((equal e '(:endgroup))
14982 (setq ingroup nil cnt 0)
14983 (insert "}\n"))
14985 (setq tg (car e) c (cdr e))
14986 (if ingroup (push tg (car groups)))
14987 (setq tg (org-add-props tg nil 'face
14988 (org-get-todo-face tg)))
14989 (if (and (= cnt 0) (not ingroup)) (insert " "))
14990 (insert "[" c "] " tg (make-string
14991 (- fwidth 4 (length tg)) ?\ ))
14992 (when (= (setq cnt (1+ cnt)) ncol)
14993 (insert "\n")
14994 (if ingroup (insert " "))
14995 (setq cnt 0)))))
14996 (insert "\n")
14997 (goto-char (point-min))
14998 (if (and (not expert) (fboundp 'fit-window-to-buffer))
14999 (fit-window-to-buffer))
15000 (message "[a-z..]:Set [SPC]:clear")
15001 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
15002 (cond
15003 ((or (= c ?\C-g)
15004 (and (= c ?q) (not (rassoc c fulltable))))
15005 (setq quit-flag t))
15006 ((= c ?\ ) nil)
15007 ((setq e (rassoc c fulltable) tg (car e))
15009 (t (setq quit-flag t))))))
15011 (defun org-get-repeat ()
15012 "Check if tere is a deadline/schedule with repeater in this entry."
15013 (save-match-data
15014 (save-excursion
15015 (org-back-to-heading t)
15016 (if (re-search-forward
15017 org-repeat-re (save-excursion (outline-next-heading) (point)) t)
15018 (match-string 1)))))
15020 (defvar org-last-changed-timestamp)
15021 (defvar org-log-post-message)
15022 (defvar org-log-note-purpose)
15023 (defun org-auto-repeat-maybe (done-word)
15024 "Check if the current headline contains a repeated deadline/schedule.
15025 If yes, set TODO state back to what it was and change the base date
15026 of repeating deadline/scheduled time stamps to new date.
15027 This function is run automatically after each state change to a DONE state."
15028 ;; last-state is dynamically scoped into this function
15029 (let* ((repeat (org-get-repeat))
15030 (aa (assoc last-state org-todo-kwd-alist))
15031 (interpret (nth 1 aa))
15032 (head (nth 2 aa))
15033 (whata '(("d" . day) ("m" . month) ("y" . year)))
15034 (msg "Entry repeats: ")
15035 (org-log-done nil)
15036 (org-todo-log-states nil)
15037 (nshiftmax 10) (nshift 0)
15038 re type n what ts mb0 time)
15039 (when repeat
15040 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
15041 (org-todo (if (eq interpret 'type) last-state head))
15042 (when (and org-log-repeat
15043 (or (not (memq 'org-add-log-note
15044 (default-value 'post-command-hook)))
15045 (eq org-log-note-purpose 'done)))
15046 ;; Make sure a note is taken;
15047 (org-add-log-maybe 'state (or done-word (car org-done-keywords))
15048 'findpos org-log-repeat))
15049 (org-back-to-heading t)
15050 (org-add-planning-info nil nil 'closed)
15051 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
15052 org-deadline-time-regexp "\\)\\|\\("
15053 org-ts-regexp "\\)"))
15054 (while (re-search-forward
15055 re (save-excursion (outline-next-heading) (point)) t)
15056 (setq type (if (match-end 1) org-scheduled-string
15057 (if (match-end 3) org-deadline-string "Plain:"))
15058 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0)))
15059 mb0 (match-beginning 0))
15060 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts)
15061 (setq n (string-to-number (match-string 2 ts))
15062 what (match-string 3 ts))
15063 (if (equal what "w") (setq n (* n 7) what "d"))
15064 ;; Preparation, see if we need to modify the start date for the change
15065 (when (match-end 1)
15066 (setq time (save-match-data (org-time-string-to-time ts)))
15067 (cond
15068 ((equal (match-string 1 ts) ".")
15069 ;; Shift starting date to today
15070 (org-timestamp-change
15071 (- (time-to-days (current-time)) (time-to-days time))
15072 'day))
15073 ((equal (match-string 1 ts) "+")
15074 (while (< (time-to-days time) (time-to-days (current-time)))
15075 (when (= (incf nshift) nshiftmax)
15076 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
15077 (error "Abort")))
15078 (org-timestamp-change n (cdr (assoc what whata)))
15079 (sit-for .0001) ;; so we can watch the date shifting
15080 (org-at-timestamp-p t)
15081 (setq ts (match-string 1))
15082 (setq time (save-match-data (org-time-string-to-time ts))))
15083 (org-timestamp-change (- n) (cdr (assoc what whata)))
15084 ;; rematch, so that we have everything in place for the real shift
15085 (org-at-timestamp-p t)
15086 (setq ts (match-string 1))
15087 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts))))
15088 (org-timestamp-change n (cdr (assoc what whata)))
15089 (setq msg (concat msg type org-last-changed-timestamp " "))))
15090 (setq org-log-post-message msg)
15091 (message "%s" msg))))
15093 (defun org-show-todo-tree (arg)
15094 "Make a compact tree which shows all headlines marked with TODO.
15095 The tree will show the lines where the regexp matches, and all higher
15096 headlines above the match.
15097 With a \\[universal-argument] prefix, also show the DONE entries.
15098 With a numeric prefix N, construct a sparse tree for the Nth element
15099 of `org-todo-keywords-1'."
15100 (interactive "P")
15101 (let ((case-fold-search nil)
15102 (kwd-re
15103 (cond ((null arg) org-not-done-regexp)
15104 ((equal arg '(4))
15105 (let ((kwd (completing-read "Keyword (or KWD1|KWD2|...): "
15106 (mapcar 'list org-todo-keywords-1))))
15107 (concat "\\("
15108 (mapconcat 'identity (org-split-string kwd "|") "\\|")
15109 "\\)\\>")))
15110 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
15111 (regexp-quote (nth (1- (prefix-numeric-value arg))
15112 org-todo-keywords-1)))
15113 (t (error "Invalid prefix argument: %s" arg)))))
15114 (message "%d TODO entries found"
15115 (org-occur (concat "^" outline-regexp " *" kwd-re )))))
15117 (defun org-deadline (&optional remove)
15118 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
15119 With argument REMOVE, remove any deadline from the item."
15120 (interactive "P")
15121 (if remove
15122 (progn
15123 (org-remove-timestamp-with-keyword org-deadline-string)
15124 (message "Item no longer has a deadline."))
15125 (org-add-planning-info 'deadline nil 'closed)))
15127 (defun org-schedule (&optional remove)
15128 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
15129 With argument REMOVE, remove any scheduling date from the item."
15130 (interactive "P")
15131 (if remove
15132 (progn
15133 (org-remove-timestamp-with-keyword org-scheduled-string)
15134 (message "Item is no longer scheduled."))
15135 (org-add-planning-info 'scheduled nil 'closed)))
15137 (defun org-remove-timestamp-with-keyword (keyword)
15138 "Remove all time stamps with KEYWORD in the current entry."
15139 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
15140 beg)
15141 (save-excursion
15142 (org-back-to-heading t)
15143 (setq beg (point))
15144 (org-end-of-subtree t t)
15145 (while (re-search-backward re beg t)
15146 (replace-match "")
15147 (unless (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
15148 (delete-region (point-at-bol) (min (1+ (point)) (point-max))))))))
15150 (defun org-add-planning-info (what &optional time &rest remove)
15151 "Insert new timestamp with keyword in the line directly after the headline.
15152 WHAT indicates what kind of time stamp to add. TIME indicated the time to use.
15153 If non is given, the user is prompted for a date.
15154 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
15155 be removed."
15156 (interactive)
15157 (let (org-time-was-given org-end-time-was-given ts
15158 end default-time default-input)
15160 (when (and (not time) (memq what '(scheduled deadline)))
15161 ;; Try to get a default date/time from existing timestamp
15162 (save-excursion
15163 (org-back-to-heading t)
15164 (setq end (save-excursion (outline-next-heading) (point)))
15165 (when (re-search-forward (if (eq what 'scheduled)
15166 org-scheduled-time-regexp
15167 org-deadline-time-regexp)
15168 end t)
15169 (setq ts (match-string 1)
15170 default-time
15171 (apply 'encode-time (org-parse-time-string ts))
15172 default-input (and ts (org-get-compact-tod ts))))))
15173 (when what
15174 ;; If necessary, get the time from the user
15175 (setq time (or time (org-read-date nil 'to-time nil nil
15176 default-time default-input))))
15178 (when (and org-insert-labeled-timestamps-at-point
15179 (member what '(scheduled deadline)))
15180 (insert
15181 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
15182 (org-insert-time-stamp time org-time-was-given
15183 nil nil nil (list org-end-time-was-given))
15184 (setq what nil))
15185 (save-excursion
15186 (save-restriction
15187 (let (col list elt ts buffer-invisibility-spec)
15188 (org-back-to-heading t)
15189 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
15190 (goto-char (match-end 1))
15191 (setq col (current-column))
15192 (goto-char (match-end 0))
15193 (if (eobp) (insert "\n") (forward-char 1))
15194 (if (and (not (looking-at outline-regexp))
15195 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
15196 "[^\r\n]*"))
15197 (not (equal (match-string 1) org-clock-string)))
15198 (narrow-to-region (match-beginning 0) (match-end 0))
15199 (insert-before-markers "\n")
15200 (backward-char 1)
15201 (narrow-to-region (point) (point))
15202 (indent-to-column col))
15203 ;; Check if we have to remove something.
15204 (setq list (cons what remove))
15205 (while list
15206 (setq elt (pop list))
15207 (goto-char (point-min))
15208 (when (or (and (eq elt 'scheduled)
15209 (re-search-forward org-scheduled-time-regexp nil t))
15210 (and (eq elt 'deadline)
15211 (re-search-forward org-deadline-time-regexp nil t))
15212 (and (eq elt 'closed)
15213 (re-search-forward org-closed-time-regexp nil t)))
15214 (replace-match "")
15215 (if (looking-at "--+<[^>]+>") (replace-match ""))
15216 (if (looking-at " +") (replace-match ""))))
15217 (goto-char (point-max))
15218 (when what
15219 (insert
15220 (if (not (equal (char-before) ?\ )) " " "")
15221 (cond ((eq what 'scheduled) org-scheduled-string)
15222 ((eq what 'deadline) org-deadline-string)
15223 ((eq what 'closed) org-closed-string))
15224 " ")
15225 (setq ts (org-insert-time-stamp
15226 time
15227 (or org-time-was-given
15228 (and (eq what 'closed) org-log-done-with-time))
15229 (eq what 'closed)
15230 nil nil (list org-end-time-was-given)))
15231 (end-of-line 1))
15232 (goto-char (point-min))
15233 (widen)
15234 (if (looking-at "[ \t]+\r?\n")
15235 (replace-match ""))
15236 ts)))))
15238 (defvar org-log-note-marker (make-marker))
15239 (defvar org-log-note-purpose nil)
15240 (defvar org-log-note-state nil)
15241 (defvar org-log-note-how nil)
15242 (defvar org-log-note-window-configuration nil)
15243 (defvar org-log-note-return-to (make-marker))
15244 (defvar org-log-post-message nil
15245 "Message to be displayed after a log note has been stored.
15246 The auto-repeater uses this.")
15248 (defun org-add-log-maybe (&optional purpose state findpos how)
15249 "Set up the post command hook to take a note.
15250 If this is about to TODO state change, the new state is expected in STATE.
15251 When FINDPOS is non-nil, find the correct position for the note in
15252 the current entry. If not, assume that it can be inserted at point."
15253 (save-excursion
15254 (when findpos
15255 (org-back-to-heading t)
15256 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"
15257 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
15258 "[^\r\n]*\\)?"))
15259 (goto-char (match-end 0))
15260 (unless org-log-states-order-reversed
15261 (and (= (char-after) ?\n) (forward-char 1))
15262 (org-skip-over-state-notes)
15263 (skip-chars-backward " \t\n\r")))
15264 (move-marker org-log-note-marker (point))
15265 (setq org-log-note-purpose purpose
15266 org-log-note-state state
15267 org-log-note-how how)
15268 (add-hook 'post-command-hook 'org-add-log-note 'append)))
15270 (defun org-skip-over-state-notes ()
15271 "Skip past the list of State notes in an entry."
15272 (if (looking-at "\n[ \t]*- State") (forward-char 1))
15273 (while (looking-at "[ \t]*- State")
15274 (condition-case nil
15275 (org-next-item)
15276 (error (org-end-of-item)))))
15278 (defun org-add-log-note (&optional purpose)
15279 "Pop up a window for taking a note, and add this note later at point."
15280 (remove-hook 'post-command-hook 'org-add-log-note)
15281 (setq org-log-note-window-configuration (current-window-configuration))
15282 (delete-other-windows)
15283 (move-marker org-log-note-return-to (point))
15284 (switch-to-buffer (marker-buffer org-log-note-marker))
15285 (goto-char org-log-note-marker)
15286 (org-switch-to-buffer-other-window "*Org Note*")
15287 (erase-buffer)
15288 (if (memq org-log-note-how '(time state)) ; FIXME: time or state????????????
15289 (org-store-log-note)
15290 (let ((org-inhibit-startup t)) (org-mode))
15291 (insert (format "# Insert note for %s.
15292 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
15293 (cond
15294 ((eq org-log-note-purpose 'clock-out) "stopped clock")
15295 ((eq org-log-note-purpose 'done) "closed todo item")
15296 ((eq org-log-note-purpose 'state)
15297 (format "state change to \"%s\"" org-log-note-state))
15298 (t (error "This should not happen")))))
15299 (org-set-local 'org-finish-function 'org-store-log-note)))
15301 (defun org-store-log-note ()
15302 "Finish taking a log note, and insert it to where it belongs."
15303 (let ((txt (buffer-string))
15304 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
15305 lines ind)
15306 (kill-buffer (current-buffer))
15307 (while (string-match "\\`#.*\n[ \t\n]*" txt)
15308 (setq txt (replace-match "" t t txt)))
15309 (if (string-match "\\s-+\\'" txt)
15310 (setq txt (replace-match "" t t txt)))
15311 (setq lines (org-split-string txt "\n"))
15312 (when (and note (string-match "\\S-" note))
15313 (setq note
15314 (org-replace-escapes
15315 note
15316 (list (cons "%u" (user-login-name))
15317 (cons "%U" user-full-name)
15318 (cons "%t" (format-time-string
15319 (org-time-stamp-format 'long 'inactive)
15320 (current-time)))
15321 (cons "%s" (if org-log-note-state
15322 (concat "\"" org-log-note-state "\"")
15323 "")))))
15324 (if lines (setq note (concat note " \\\\")))
15325 (push note lines))
15326 (when (or current-prefix-arg org-note-abort) (setq lines nil))
15327 (when lines
15328 (save-excursion
15329 (set-buffer (marker-buffer org-log-note-marker))
15330 (save-excursion
15331 (goto-char org-log-note-marker)
15332 (move-marker org-log-note-marker nil)
15333 (end-of-line 1)
15334 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
15335 (indent-relative nil)
15336 (insert "- " (pop lines))
15337 (org-indent-line-function)
15338 (beginning-of-line 1)
15339 (looking-at "[ \t]*")
15340 (setq ind (concat (match-string 0) " "))
15341 (end-of-line 1)
15342 (while lines (insert "\n" ind (pop lines)))))))
15343 (set-window-configuration org-log-note-window-configuration)
15344 (with-current-buffer (marker-buffer org-log-note-return-to)
15345 (goto-char org-log-note-return-to))
15346 (move-marker org-log-note-return-to nil)
15347 (and org-log-post-message (message "%s" org-log-post-message)))
15349 ;; FIXME: what else would be useful?
15350 ;; - priority
15351 ;; - date
15353 (defun org-sparse-tree (&optional arg)
15354 "Create a sparse tree, prompt for the details.
15355 This command can create sparse trees. You first need to select the type
15356 of match used to create the tree:
15358 t Show entries with a specific TODO keyword.
15359 T Show entries selected by a tags match.
15360 p Enter a property name and its value (both with completion on existing
15361 names/values) and show entries with that property.
15362 r Show entries matching a regular expression
15363 d Show deadlines due within `org-deadline-warning-days'."
15364 (interactive "P")
15365 (let (ans kwd value)
15366 (message "Sparse tree: [/]regexp [t]odo-kwd [T]ag [p]roperty [d]eadlines [b]efore-date")
15367 (setq ans (read-char-exclusive))
15368 (cond
15369 ((equal ans ?d)
15370 (call-interactively 'org-check-deadlines))
15371 ((equal ans ?b)
15372 (call-interactively 'org-check-before-date))
15373 ((equal ans ?t)
15374 (org-show-todo-tree '(4)))
15375 ((equal ans ?T)
15376 (call-interactively 'org-tags-sparse-tree))
15377 ((member ans '(?p ?P))
15378 (setq kwd (completing-read "Property: "
15379 (mapcar 'list (org-buffer-property-keys))))
15380 (setq value (completing-read "Value: "
15381 (mapcar 'list (org-property-values kwd))))
15382 (unless (string-match "\\`{.*}\\'" value)
15383 (setq value (concat "\"" value "\"")))
15384 (org-tags-sparse-tree arg (concat kwd "=" value)))
15385 ((member ans '(?r ?R ?/))
15386 (call-interactively 'org-occur))
15387 (t (error "No such sparse tree command \"%c\"" ans)))))
15389 (defvar org-occur-highlights nil
15390 "List of overlays used for occur matches.")
15391 (make-variable-buffer-local 'org-occur-highlights)
15392 (defvar org-occur-parameters nil
15393 "Parameters of the active org-occur calls.
15394 This is a list, each call to org-occur pushes as cons cell,
15395 containing the regular expression and the callback, onto the list.
15396 The list can contain several entries if `org-occur' has been called
15397 several time with the KEEP-PREVIOUS argument. Otherwise, this list
15398 will only contain one set of parameters. When the highlights are
15399 removed (for example with `C-c C-c', or with the next edit (depending
15400 on `org-remove-highlights-with-change'), this variable is emptied
15401 as well.")
15402 (make-variable-buffer-local 'org-occur-parameters)
15404 (defun org-occur (regexp &optional keep-previous callback)
15405 "Make a compact tree which shows all matches of REGEXP.
15406 The tree will show the lines where the regexp matches, and all higher
15407 headlines above the match. It will also show the heading after the match,
15408 to make sure editing the matching entry is easy.
15409 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
15410 call to `org-occur' will be kept, to allow stacking of calls to this
15411 command.
15412 If CALLBACK is non-nil, it is a function which is called to confirm
15413 that the match should indeed be shown."
15414 (interactive "sRegexp: \nP")
15415 (unless keep-previous
15416 (org-remove-occur-highlights nil nil t))
15417 (push (cons regexp callback) org-occur-parameters)
15418 (let ((cnt 0))
15419 (save-excursion
15420 (goto-char (point-min))
15421 (if (or (not keep-previous) ; do not want to keep
15422 (not org-occur-highlights)) ; no previous matches
15423 ;; hide everything
15424 (org-overview))
15425 (while (re-search-forward regexp nil t)
15426 (when (or (not callback)
15427 (save-match-data (funcall callback)))
15428 (setq cnt (1+ cnt))
15429 (when org-highlight-sparse-tree-matches
15430 (org-highlight-new-match (match-beginning 0) (match-end 0)))
15431 (org-show-context 'occur-tree))))
15432 (when org-remove-highlights-with-change
15433 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
15434 nil 'local))
15435 (unless org-sparse-tree-open-archived-trees
15436 (org-hide-archived-subtrees (point-min) (point-max)))
15437 (run-hooks 'org-occur-hook)
15438 (if (interactive-p)
15439 (message "%d match(es) for regexp %s" cnt regexp))
15440 cnt))
15442 (defun org-show-context (&optional key)
15443 "Make sure point and context and visible.
15444 How much context is shown depends upon the variables
15445 `org-show-hierarchy-above', `org-show-following-heading'. and
15446 `org-show-siblings'."
15447 (let ((heading-p (org-on-heading-p t))
15448 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
15449 (following-p (org-get-alist-option org-show-following-heading key))
15450 (entry-p (org-get-alist-option org-show-entry-below key))
15451 (siblings-p (org-get-alist-option org-show-siblings key)))
15452 (catch 'exit
15453 ;; Show heading or entry text
15454 (if (and heading-p (not entry-p))
15455 (org-flag-heading nil) ; only show the heading
15456 (and (or entry-p (org-invisible-p) (org-invisible-p2))
15457 (org-show-hidden-entry))) ; show entire entry
15458 (when following-p
15459 ;; Show next sibling, or heading below text
15460 (save-excursion
15461 (and (if heading-p (org-goto-sibling) (outline-next-heading))
15462 (org-flag-heading nil))))
15463 (when siblings-p (org-show-siblings))
15464 (when hierarchy-p
15465 ;; show all higher headings, possibly with siblings
15466 (save-excursion
15467 (while (and (condition-case nil
15468 (progn (org-up-heading-all 1) t)
15469 (error nil))
15470 (not (bobp)))
15471 (org-flag-heading nil)
15472 (when siblings-p (org-show-siblings))))))))
15474 (defun org-reveal (&optional siblings)
15475 "Show current entry, hierarchy above it, and the following headline.
15476 This can be used to show a consistent set of context around locations
15477 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
15478 not t for the search context.
15480 With optional argument SIBLINGS, on each level of the hierarchy all
15481 siblings are shown. This repairs the tree structure to what it would
15482 look like when opened with hierarchical calls to `org-cycle'."
15483 (interactive "P")
15484 (let ((org-show-hierarchy-above t)
15485 (org-show-following-heading t)
15486 (org-show-siblings (if siblings t org-show-siblings)))
15487 (org-show-context nil)))
15489 (defun org-highlight-new-match (beg end)
15490 "Highlight from BEG to END and mark the highlight is an occur headline."
15491 (let ((ov (org-make-overlay beg end)))
15492 (org-overlay-put ov 'face 'secondary-selection)
15493 (push ov org-occur-highlights)))
15495 (defun org-remove-occur-highlights (&optional beg end noremove)
15496 "Remove the occur highlights from the buffer.
15497 BEG and END are ignored. If NOREMOVE is nil, remove this function
15498 from the `before-change-functions' in the current buffer."
15499 (interactive)
15500 (unless org-inhibit-highlight-removal
15501 (mapc 'org-delete-overlay org-occur-highlights)
15502 (setq org-occur-highlights nil)
15503 (setq org-occur-parameters nil)
15504 (unless noremove
15505 (remove-hook 'before-change-functions
15506 'org-remove-occur-highlights 'local))))
15508 ;;;; Priorities
15510 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
15511 "Regular expression matching the priority indicator.")
15513 (defvar org-remove-priority-next-time nil)
15515 (defun org-priority-up ()
15516 "Increase the priority of the current item."
15517 (interactive)
15518 (org-priority 'up))
15520 (defun org-priority-down ()
15521 "Decrease the priority of the current item."
15522 (interactive)
15523 (org-priority 'down))
15525 (defun org-priority (&optional action)
15526 "Change the priority of an item by ARG.
15527 ACTION can be `set', `up', `down', or a character."
15528 (interactive)
15529 (setq action (or action 'set))
15530 (let (current new news have remove)
15531 (save-excursion
15532 (org-back-to-heading)
15533 (if (looking-at org-priority-regexp)
15534 (setq current (string-to-char (match-string 2))
15535 have t)
15536 (setq current org-default-priority))
15537 (cond
15538 ((or (eq action 'set) (integerp action))
15539 (if (integerp action)
15540 (setq new action)
15541 (message "Priority %c-%c, SPC to remove: " org-highest-priority org-lowest-priority)
15542 (setq new (read-char-exclusive)))
15543 (if (and (= (upcase org-highest-priority) org-highest-priority)
15544 (= (upcase org-lowest-priority) org-lowest-priority))
15545 (setq new (upcase new)))
15546 (cond ((equal new ?\ ) (setq remove t))
15547 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
15548 (error "Priority must be between `%c' and `%c'"
15549 org-highest-priority org-lowest-priority))))
15550 ((eq action 'up)
15551 (if (and (not have) (eq last-command this-command))
15552 (setq new org-lowest-priority)
15553 (setq new (if (and org-priority-start-cycle-with-default (not have))
15554 org-default-priority (1- current)))))
15555 ((eq action 'down)
15556 (if (and (not have) (eq last-command this-command))
15557 (setq new org-highest-priority)
15558 (setq new (if (and org-priority-start-cycle-with-default (not have))
15559 org-default-priority (1+ current)))))
15560 (t (error "Invalid action")))
15561 (if (or (< (upcase new) org-highest-priority)
15562 (> (upcase new) org-lowest-priority))
15563 (setq remove t))
15564 (setq news (format "%c" new))
15565 (if have
15566 (if remove
15567 (replace-match "" t t nil 1)
15568 (replace-match news t t nil 2))
15569 (if remove
15570 (error "No priority cookie found in line")
15571 (looking-at org-todo-line-regexp)
15572 (if (match-end 2)
15573 (progn
15574 (goto-char (match-end 2))
15575 (insert " [#" news "]"))
15576 (goto-char (match-beginning 3))
15577 (insert "[#" news "] ")))))
15578 (org-preserve-lc (org-set-tags nil 'align))
15579 (if remove
15580 (message "Priority removed")
15581 (message "Priority of current item set to %s" news))))
15584 (defun org-get-priority (s)
15585 "Find priority cookie and return priority."
15586 (save-match-data
15587 (if (not (string-match org-priority-regexp s))
15588 (* 1000 (- org-lowest-priority org-default-priority))
15589 (* 1000 (- org-lowest-priority
15590 (string-to-char (match-string 2 s)))))))
15592 ;;;; Tags
15594 (defun org-scan-tags (action matcher &optional todo-only)
15595 "Scan headline tags with inheritance and produce output ACTION.
15596 ACTION can be `sparse-tree' or `agenda'. MATCHER is a Lisp form to be
15597 evaluated, testing if a given set of tags qualifies a headline for
15598 inclusion. When TODO-ONLY is non-nil, only lines with a TODO keyword
15599 are included in the output."
15600 (let* ((re (concat "[\n\r]" outline-regexp " *\\(\\<\\("
15601 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
15602 (org-re
15603 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*$")))
15604 (props (list 'face nil
15605 'done-face 'org-done
15606 'undone-face nil
15607 'mouse-face 'highlight
15608 'org-not-done-regexp org-not-done-regexp
15609 'org-todo-regexp org-todo-regexp
15610 'keymap org-agenda-keymap
15611 'help-echo
15612 (format "mouse-2 or RET jump to org file %s"
15613 (abbreviate-file-name
15614 (or (buffer-file-name (buffer-base-buffer))
15615 (buffer-name (buffer-base-buffer)))))))
15616 (case-fold-search nil)
15617 lspos
15618 tags tags-list tags-alist (llast 0) rtn level category i txt
15619 todo marker entry priority)
15620 (save-excursion
15621 (goto-char (point-min))
15622 (when (eq action 'sparse-tree)
15623 (org-overview)
15624 (org-remove-occur-highlights))
15625 (while (re-search-forward re nil t)
15626 (catch :skip
15627 (setq todo (if (match-end 1) (match-string 2))
15628 tags (if (match-end 4) (match-string 4)))
15629 (goto-char (setq lspos (1+ (match-beginning 0))))
15630 (setq level (org-reduced-level (funcall outline-level))
15631 category (org-get-category))
15632 (setq i llast llast level)
15633 ;; remove tag lists from same and sublevels
15634 (while (>= i level)
15635 (when (setq entry (assoc i tags-alist))
15636 (setq tags-alist (delete entry tags-alist)))
15637 (setq i (1- i)))
15638 ;; add the nex tags
15639 (when tags
15640 (setq tags (mapcar 'downcase (org-split-string tags ":"))
15641 tags-alist
15642 (cons (cons level tags) tags-alist)))
15643 ;; compile tags for current headline
15644 (setq tags-list
15645 (if org-use-tag-inheritance
15646 (apply 'append (mapcar 'cdr tags-alist))
15647 tags))
15648 (when (and (or (not todo-only) (member todo org-not-done-keywords))
15649 (eval matcher)
15650 (or (not org-agenda-skip-archived-trees)
15651 (not (member org-archive-tag tags-list))))
15652 (and (eq action 'agenda) (org-agenda-skip))
15653 ;; list this headline
15655 (if (eq action 'sparse-tree)
15656 (progn
15657 (and org-highlight-sparse-tree-matches
15658 (org-get-heading) (match-end 0)
15659 (org-highlight-new-match
15660 (match-beginning 0) (match-beginning 1)))
15661 (org-show-context 'tags-tree))
15662 (setq txt (org-format-agenda-item
15664 (concat
15665 (if org-tags-match-list-sublevels
15666 (make-string (1- level) ?.) "")
15667 (org-get-heading))
15668 category tags-list)
15669 priority (org-get-priority txt))
15670 (goto-char lspos)
15671 (setq marker (org-agenda-new-marker))
15672 (org-add-props txt props
15673 'org-marker marker 'org-hd-marker marker 'org-category category
15674 'priority priority 'type "tagsmatch")
15675 (push txt rtn))
15676 ;; if we are to skip sublevels, jump to end of subtree
15677 (or org-tags-match-list-sublevels (org-end-of-subtree t))))))
15678 (when (and (eq action 'sparse-tree)
15679 (not org-sparse-tree-open-archived-trees))
15680 (org-hide-archived-subtrees (point-min) (point-max)))
15681 (nreverse rtn)))
15683 (defvar todo-only) ;; dynamically scoped
15685 (defun org-tags-sparse-tree (&optional todo-only match)
15686 "Create a sparse tree according to tags string MATCH.
15687 MATCH can contain positive and negative selection of tags, like
15688 \"+WORK+URGENT-WITHBOSS\".
15689 If optional argument TODO_ONLY is non-nil, only select lines that are
15690 also TODO lines."
15691 (interactive "P")
15692 (org-prepare-agenda-buffers (list (current-buffer)))
15693 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
15695 (defvar org-cached-props nil)
15696 (defun org-cached-entry-get (pom property)
15697 (if (or (eq t org-use-property-inheritance)
15698 (member property org-use-property-inheritance))
15699 ;; Caching is not possible, check it directly
15700 (org-entry-get pom property 'inherit)
15701 ;; Get all properties, so that we can do complicated checks easily
15702 (cdr (assoc property (or org-cached-props
15703 (setq org-cached-props
15704 (org-entry-properties pom)))))))
15706 (defun org-global-tags-completion-table (&optional files)
15707 "Return the list of all tags in all agenda buffer/files."
15708 (save-excursion
15709 (org-uniquify
15710 (delq nil
15711 (apply 'append
15712 (mapcar
15713 (lambda (file)
15714 (set-buffer (find-file-noselect file))
15715 (append (org-get-buffer-tags)
15716 (mapcar (lambda (x) (if (stringp (car-safe x))
15717 (list (car-safe x)) nil))
15718 org-tag-alist)))
15719 (if (and files (car files))
15720 files
15721 (org-agenda-files))))))))
15723 (defun org-make-tags-matcher (match)
15724 "Create the TAGS//TODO matcher form for the selection string MATCH."
15725 ;; todo-only is scoped dynamically into this function, and the function
15726 ;; may change it it the matcher asksk for it.
15727 (unless match
15728 ;; Get a new match request, with completion
15729 (let ((org-last-tags-completion-table
15730 (org-global-tags-completion-table)))
15731 (setq match (completing-read
15732 "Match: " 'org-tags-completion-function nil nil nil
15733 'org-tags-history))))
15735 ;; Parse the string and create a lisp form
15736 (let ((match0 match)
15737 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL=\\([0-9]+\\)\\|\\([[:alnum:]_]+\\)=\\({[^}]+}\\|\"[^\"]*\"\\)\\|[[:alnum:]_@]+\\)"))
15738 minus tag mm
15739 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
15740 orterms term orlist re-p level-p prop-p pn pv cat-p gv)
15741 (if (string-match "/+" match)
15742 ;; match contains also a todo-matching request
15743 (progn
15744 (setq tagsmatch (substring match 0 (match-beginning 0))
15745 todomatch (substring match (match-end 0)))
15746 (if (string-match "^!" todomatch)
15747 (setq todo-only t todomatch (substring todomatch 1)))
15748 (if (string-match "^\\s-*$" todomatch)
15749 (setq todomatch nil)))
15750 ;; only matching tags
15751 (setq tagsmatch match todomatch nil))
15753 ;; Make the tags matcher
15754 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
15755 (setq tagsmatcher t)
15756 (setq orterms (org-split-string tagsmatch "|") orlist nil)
15757 (while (setq term (pop orterms))
15758 (while (and (equal (substring term -1) "\\") orterms)
15759 (setq term (concat term "|" (pop orterms)))) ; repair bad split
15760 (while (string-match re term)
15761 (setq minus (and (match-end 1)
15762 (equal (match-string 1 term) "-"))
15763 tag (match-string 2 term)
15764 re-p (equal (string-to-char tag) ?{)
15765 level-p (match-end 3)
15766 prop-p (match-end 4)
15767 mm (cond
15768 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
15769 (level-p `(= level ,(string-to-number
15770 (match-string 3 term))))
15771 (prop-p
15772 (setq pn (match-string 4 term)
15773 pv (match-string 5 term)
15774 cat-p (equal pn "CATEGORY")
15775 re-p (equal (string-to-char pv) ?{)
15776 pv (substring pv 1 -1))
15777 (if (equal pn "CATEGORY")
15778 (setq gv '(get-text-property (point) 'org-category))
15779 (setq gv `(org-cached-entry-get nil ,pn)))
15780 (if re-p
15781 `(string-match ,pv (or ,gv ""))
15782 `(equal ,pv (or ,gv ""))))
15783 (t `(member ,(downcase tag) tags-list)))
15784 mm (if minus (list 'not mm) mm)
15785 term (substring term (match-end 0)))
15786 (push mm tagsmatcher))
15787 (push (if (> (length tagsmatcher) 1)
15788 (cons 'and tagsmatcher)
15789 (car tagsmatcher))
15790 orlist)
15791 (setq tagsmatcher nil))
15792 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
15793 (setq tagsmatcher
15794 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
15796 ;; Make the todo matcher
15797 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
15798 (setq todomatcher t)
15799 (setq orterms (org-split-string todomatch "|") orlist nil)
15800 (while (setq term (pop orterms))
15801 (while (string-match re term)
15802 (setq minus (and (match-end 1)
15803 (equal (match-string 1 term) "-"))
15804 kwd (match-string 2 term)
15805 re-p (equal (string-to-char kwd) ?{)
15806 term (substring term (match-end 0))
15807 mm (if re-p
15808 `(string-match ,(substring kwd 1 -1) todo)
15809 (list 'equal 'todo kwd))
15810 mm (if minus (list 'not mm) mm))
15811 (push mm todomatcher))
15812 (push (if (> (length todomatcher) 1)
15813 (cons 'and todomatcher)
15814 (car todomatcher))
15815 orlist)
15816 (setq todomatcher nil))
15817 (setq todomatcher (if (> (length orlist) 1)
15818 (cons 'or orlist) (car orlist))))
15820 ;; Return the string and lisp forms of the matcher
15821 (setq matcher (if todomatcher
15822 (list 'and tagsmatcher todomatcher)
15823 tagsmatcher))
15824 (cons match0 matcher)))
15826 (defun org-match-any-p (re list)
15827 "Does re match any element of list?"
15828 (setq list (mapcar (lambda (x) (string-match re x)) list))
15829 (delq nil list))
15831 (defvar org-add-colon-after-tag-completion nil) ;; dynamically skoped param
15832 (defvar org-tags-overlay (org-make-overlay 1 1))
15833 (org-detach-overlay org-tags-overlay)
15835 (defun org-align-tags-here (to-col)
15836 ;; Assumes that this is a headline
15837 (let ((pos (point)) (col (current-column)) tags)
15838 (beginning-of-line 1)
15839 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
15840 (< pos (match-beginning 2)))
15841 (progn
15842 (setq tags (match-string 2))
15843 (goto-char (match-beginning 1))
15844 (insert " ")
15845 (delete-region (point) (1+ (match-end 0)))
15846 (backward-char 1)
15847 (move-to-column
15848 (max (1+ (current-column))
15849 (1+ col)
15850 (if (> to-col 0)
15851 to-col
15852 (- (abs to-col) (length tags))))
15854 (insert tags)
15855 (move-to-column (min (current-column) col) t))
15856 (goto-char pos))))
15858 (defun org-set-tags (&optional arg just-align)
15859 "Set the tags for the current headline.
15860 With prefix ARG, realign all tags in headings in the current buffer."
15861 (interactive "P")
15862 (let* ((re (concat "^" outline-regexp))
15863 (current (org-get-tags-string))
15864 (col (current-column))
15865 (org-setting-tags t)
15866 table current-tags inherited-tags ; computed below when needed
15867 tags p0 c0 c1 rpl)
15868 (if arg
15869 (save-excursion
15870 (goto-char (point-min))
15871 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
15872 (while (re-search-forward re nil t)
15873 (org-set-tags nil t)
15874 (end-of-line 1)))
15875 (message "All tags realigned to column %d" org-tags-column))
15876 (if just-align
15877 (setq tags current)
15878 ;; Get a new set of tags from the user
15879 (save-excursion
15880 (setq table (or org-tag-alist (org-get-buffer-tags))
15881 org-last-tags-completion-table table
15882 current-tags (org-split-string current ":")
15883 inherited-tags (nreverse
15884 (nthcdr (length current-tags)
15885 (nreverse (org-get-tags-at))))
15886 tags
15887 (if (or (eq t org-use-fast-tag-selection)
15888 (and org-use-fast-tag-selection
15889 (delq nil (mapcar 'cdr table))))
15890 (org-fast-tag-selection
15891 current-tags inherited-tags table
15892 (if org-fast-tag-selection-include-todo org-todo-key-alist))
15893 (let ((org-add-colon-after-tag-completion t))
15894 (org-trim
15895 (org-without-partial-completion
15896 (completing-read "Tags: " 'org-tags-completion-function
15897 nil nil current 'org-tags-history)))))))
15898 (while (string-match "[-+&]+" tags)
15899 ;; No boolean logic, just a list
15900 (setq tags (replace-match ":" t t tags))))
15902 (if (string-match "\\`[\t ]*\\'" tags)
15903 (setq tags "")
15904 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
15905 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
15907 ;; Insert new tags at the correct column
15908 (beginning-of-line 1)
15909 (cond
15910 ((and (equal current "") (equal tags "")))
15911 ((re-search-forward
15912 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
15913 (point-at-eol) t)
15914 (if (equal tags "")
15915 (setq rpl "")
15916 (goto-char (match-beginning 0))
15917 (setq c0 (current-column) p0 (point)
15918 c1 (max (1+ c0) (if (> org-tags-column 0)
15919 org-tags-column
15920 (- (- org-tags-column) (length tags))))
15921 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
15922 (replace-match rpl t t)
15923 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
15924 tags)
15925 (t (error "Tags alignment failed")))
15926 (move-to-column col)
15927 (unless just-align
15928 (run-hooks 'org-after-tags-change-hook)))))
15930 (defun org-change-tag-in-region (beg end tag off)
15931 "Add or remove TAG for each entry in the region.
15932 This works in the agenda, and also in an org-mode buffer."
15933 (interactive
15934 (list (region-beginning) (region-end)
15935 (let ((org-last-tags-completion-table
15936 (if (org-mode-p)
15937 (org-get-buffer-tags)
15938 (org-global-tags-completion-table))))
15939 (completing-read
15940 "Tag: " 'org-tags-completion-function nil nil nil
15941 'org-tags-history))
15942 (progn
15943 (message "[s]et or [r]emove? ")
15944 (equal (read-char-exclusive) ?r))))
15945 (if (fboundp 'deactivate-mark) (deactivate-mark))
15946 (let ((agendap (equal major-mode 'org-agenda-mode))
15947 l1 l2 m buf pos newhead (cnt 0))
15948 (goto-char end)
15949 (setq l2 (1- (org-current-line)))
15950 (goto-char beg)
15951 (setq l1 (org-current-line))
15952 (loop for l from l1 to l2 do
15953 (goto-line l)
15954 (setq m (get-text-property (point) 'org-hd-marker))
15955 (when (or (and (org-mode-p) (org-on-heading-p))
15956 (and agendap m))
15957 (setq buf (if agendap (marker-buffer m) (current-buffer))
15958 pos (if agendap m (point)))
15959 (with-current-buffer buf
15960 (save-excursion
15961 (save-restriction
15962 (goto-char pos)
15963 (setq cnt (1+ cnt))
15964 (org-toggle-tag tag (if off 'off 'on))
15965 (setq newhead (org-get-heading)))))
15966 (and agendap (org-agenda-change-all-lines newhead m))))
15967 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
15969 (defun org-tags-completion-function (string predicate &optional flag)
15970 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
15971 (confirm (lambda (x) (stringp (car x)))))
15972 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
15973 (setq s1 (match-string 1 string)
15974 s2 (match-string 2 string))
15975 (setq s1 "" s2 string))
15976 (cond
15977 ((eq flag nil)
15978 ;; try completion
15979 (setq rtn (try-completion s2 ctable confirm))
15980 (if (stringp rtn)
15981 (setq rtn
15982 (concat s1 s2 (substring rtn (length s2))
15983 (if (and org-add-colon-after-tag-completion
15984 (assoc rtn ctable))
15985 ":" ""))))
15986 rtn)
15987 ((eq flag t)
15988 ;; all-completions
15989 (all-completions s2 ctable confirm)
15991 ((eq flag 'lambda)
15992 ;; exact match?
15993 (assoc s2 ctable)))
15996 (defun org-fast-tag-insert (kwd tags face &optional end)
15997 "Insert KDW, and the TAGS, the latter with face FACE. Also inser END."
15998 (insert (format "%-12s" (concat kwd ":"))
15999 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
16000 (or end "")))
16002 (defun org-fast-tag-show-exit (flag)
16003 (save-excursion
16004 (goto-line 3)
16005 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
16006 (replace-match ""))
16007 (when flag
16008 (end-of-line 1)
16009 (move-to-column (- (window-width) 19) t)
16010 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
16012 (defun org-set-current-tags-overlay (current prefix)
16013 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
16014 (if (featurep 'xemacs)
16015 (org-overlay-display org-tags-overlay (concat prefix s)
16016 'secondary-selection)
16017 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
16018 (org-overlay-display org-tags-overlay (concat prefix s)))))
16020 (defun org-fast-tag-selection (current inherited table &optional todo-table)
16021 "Fast tag selection with single keys.
16022 CURRENT is the current list of tags in the headline, INHERITED is the
16023 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
16024 possibly with grouping information. TODO-TABLE is a similar table with
16025 TODO keywords, should these have keys assigned to them.
16026 If the keys are nil, a-z are automatically assigned.
16027 Returns the new tags string, or nil to not change the current settings."
16028 (let* ((fulltable (append table todo-table))
16029 (maxlen (apply 'max (mapcar
16030 (lambda (x)
16031 (if (stringp (car x)) (string-width (car x)) 0))
16032 fulltable)))
16033 (buf (current-buffer))
16034 (expert (eq org-fast-tag-selection-single-key 'expert))
16035 (buffer-tags nil)
16036 (fwidth (+ maxlen 3 1 3))
16037 (ncol (/ (- (window-width) 4) fwidth))
16038 (i-face 'org-done)
16039 (c-face 'org-todo)
16040 tg cnt e c char c1 c2 ntable tbl rtn
16041 ov-start ov-end ov-prefix
16042 (exit-after-next org-fast-tag-selection-single-key)
16043 (done-keywords org-done-keywords)
16044 groups ingroup)
16045 (save-excursion
16046 (beginning-of-line 1)
16047 (if (looking-at
16048 (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
16049 (setq ov-start (match-beginning 1)
16050 ov-end (match-end 1)
16051 ov-prefix "")
16052 (setq ov-start (1- (point-at-eol))
16053 ov-end (1+ ov-start))
16054 (skip-chars-forward "^\n\r")
16055 (setq ov-prefix
16056 (concat
16057 (buffer-substring (1- (point)) (point))
16058 (if (> (current-column) org-tags-column)
16060 (make-string (- org-tags-column (current-column)) ?\ ))))))
16061 (org-move-overlay org-tags-overlay ov-start ov-end)
16062 (save-window-excursion
16063 (if expert
16064 (set-buffer (get-buffer-create " *Org tags*"))
16065 (delete-other-windows)
16066 (split-window-vertically)
16067 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
16068 (erase-buffer)
16069 (org-set-local 'org-done-keywords done-keywords)
16070 (org-fast-tag-insert "Inherited" inherited i-face "\n")
16071 (org-fast-tag-insert "Current" current c-face "\n\n")
16072 (org-fast-tag-show-exit exit-after-next)
16073 (org-set-current-tags-overlay current ov-prefix)
16074 (setq tbl fulltable char ?a cnt 0)
16075 (while (setq e (pop tbl))
16076 (cond
16077 ((equal e '(:startgroup))
16078 (push '() groups) (setq ingroup t)
16079 (when (not (= cnt 0))
16080 (setq cnt 0)
16081 (insert "\n"))
16082 (insert "{ "))
16083 ((equal e '(:endgroup))
16084 (setq ingroup nil cnt 0)
16085 (insert "}\n"))
16087 (setq tg (car e) c2 nil)
16088 (if (cdr e)
16089 (setq c (cdr e))
16090 ;; automatically assign a character.
16091 (setq c1 (string-to-char
16092 (downcase (substring
16093 tg (if (= (string-to-char tg) ?@) 1 0)))))
16094 (if (or (rassoc c1 ntable) (rassoc c1 table))
16095 (while (or (rassoc char ntable) (rassoc char table))
16096 (setq char (1+ char)))
16097 (setq c2 c1))
16098 (setq c (or c2 char)))
16099 (if ingroup (push tg (car groups)))
16100 (setq tg (org-add-props tg nil 'face
16101 (cond
16102 ((not (assoc tg table))
16103 (org-get-todo-face tg))
16104 ((member tg current) c-face)
16105 ((member tg inherited) i-face)
16106 (t nil))))
16107 (if (and (= cnt 0) (not ingroup)) (insert " "))
16108 (insert "[" c "] " tg (make-string
16109 (- fwidth 4 (length tg)) ?\ ))
16110 (push (cons tg c) ntable)
16111 (when (= (setq cnt (1+ cnt)) ncol)
16112 (insert "\n")
16113 (if ingroup (insert " "))
16114 (setq cnt 0)))))
16115 (setq ntable (nreverse ntable))
16116 (insert "\n")
16117 (goto-char (point-min))
16118 (if (and (not expert) (fboundp 'fit-window-to-buffer))
16119 (fit-window-to-buffer))
16120 (setq rtn
16121 (catch 'exit
16122 (while t
16123 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free%s%s"
16124 (if groups " [!] no groups" " [!]groups")
16125 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
16126 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
16127 (cond
16128 ((= c ?\r) (throw 'exit t))
16129 ((= c ?!)
16130 (setq groups (not groups))
16131 (goto-char (point-min))
16132 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
16133 ((= c ?\C-c)
16134 (if (not expert)
16135 (org-fast-tag-show-exit
16136 (setq exit-after-next (not exit-after-next)))
16137 (setq expert nil)
16138 (delete-other-windows)
16139 (split-window-vertically)
16140 (org-switch-to-buffer-other-window " *Org tags*")
16141 (and (fboundp 'fit-window-to-buffer)
16142 (fit-window-to-buffer))))
16143 ((or (= c ?\C-g)
16144 (and (= c ?q) (not (rassoc c ntable))))
16145 (org-detach-overlay org-tags-overlay)
16146 (setq quit-flag t))
16147 ((= c ?\ )
16148 (setq current nil)
16149 (if exit-after-next (setq exit-after-next 'now)))
16150 ((= c ?\t)
16151 (condition-case nil
16152 (setq tg (completing-read
16153 "Tag: "
16154 (or buffer-tags
16155 (with-current-buffer buf
16156 (org-get-buffer-tags)))))
16157 (quit (setq tg "")))
16158 (when (string-match "\\S-" tg)
16159 (add-to-list 'buffer-tags (list tg))
16160 (if (member tg current)
16161 (setq current (delete tg current))
16162 (push tg current)))
16163 (if exit-after-next (setq exit-after-next 'now)))
16164 ((setq e (rassoc c todo-table) tg (car e))
16165 (with-current-buffer buf
16166 (save-excursion (org-todo tg)))
16167 (if exit-after-next (setq exit-after-next 'now)))
16168 ((setq e (rassoc c ntable) tg (car e))
16169 (if (member tg current)
16170 (setq current (delete tg current))
16171 (loop for g in groups do
16172 (if (member tg g)
16173 (mapc (lambda (x)
16174 (setq current (delete x current)))
16175 g)))
16176 (push tg current))
16177 (if exit-after-next (setq exit-after-next 'now))))
16179 ;; Create a sorted list
16180 (setq current
16181 (sort current
16182 (lambda (a b)
16183 (assoc b (cdr (memq (assoc a ntable) ntable))))))
16184 (if (eq exit-after-next 'now) (throw 'exit t))
16185 (goto-char (point-min))
16186 (beginning-of-line 2)
16187 (delete-region (point) (point-at-eol))
16188 (org-fast-tag-insert "Current" current c-face)
16189 (org-set-current-tags-overlay current ov-prefix)
16190 (while (re-search-forward
16191 (org-re "\\[.\\] \\([[:alnum:]_@]+\\)") nil t)
16192 (setq tg (match-string 1))
16193 (add-text-properties
16194 (match-beginning 1) (match-end 1)
16195 (list 'face
16196 (cond
16197 ((member tg current) c-face)
16198 ((member tg inherited) i-face)
16199 (t (get-text-property (match-beginning 1) 'face))))))
16200 (goto-char (point-min)))))
16201 (org-detach-overlay org-tags-overlay)
16202 (if rtn
16203 (mapconcat 'identity current ":")
16204 nil))))
16206 (defun org-get-tags-string ()
16207 "Get the TAGS string in the current headline."
16208 (unless (org-on-heading-p t)
16209 (error "Not on a heading"))
16210 (save-excursion
16211 (beginning-of-line 1)
16212 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
16213 (org-match-string-no-properties 1)
16214 "")))
16216 (defun org-get-tags ()
16217 "Get the list of tags specified in the current headline."
16218 (org-split-string (org-get-tags-string) ":"))
16220 (defun org-get-buffer-tags ()
16221 "Get a table of all tags used in the buffer, for completion."
16222 (let (tags)
16223 (save-excursion
16224 (goto-char (point-min))
16225 (while (re-search-forward
16226 (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t\r\n]") nil t)
16227 (when (equal (char-after (point-at-bol 0)) ?*)
16228 (mapc (lambda (x) (add-to-list 'tags x))
16229 (org-split-string (org-match-string-no-properties 1) ":")))))
16230 (mapcar 'list tags)))
16233 ;;;; Properties
16235 ;;; Setting and retrieving properties
16237 (defconst org-special-properties
16238 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "PRIORITY"
16239 "TIMESTAMP" "TIMESTAMP_IA")
16240 "The special properties valid in Org-mode.
16242 These are properties that are not defined in the property drawer,
16243 but in some other way.")
16245 (defconst org-default-properties
16246 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION"
16247 "LOCATION" "LOGGING" "COLUMNS")
16248 "Some properties that are used by Org-mode for various purposes.
16249 Being in this list makes sure that they are offered for completion.")
16251 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
16252 "Regular expression matching the first line of a property drawer.")
16254 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
16255 "Regular expression matching the first line of a property drawer.")
16257 (defun org-property-action ()
16258 "Do an action on properties."
16259 (interactive)
16260 (let (c)
16261 (org-at-property-p)
16262 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
16263 (setq c (read-char-exclusive))
16264 (cond
16265 ((equal c ?s)
16266 (call-interactively 'org-set-property))
16267 ((equal c ?d)
16268 (call-interactively 'org-delete-property))
16269 ((equal c ?D)
16270 (call-interactively 'org-delete-property-globally))
16271 ((equal c ?c)
16272 (call-interactively 'org-compute-property-at-point))
16273 (t (error "No such property action %c" c)))))
16275 (defun org-at-property-p ()
16276 "Is the cursor in a property line?"
16277 ;; FIXME: Does not check if we are actually in the drawer.
16278 ;; FIXME: also returns true on any drawers.....
16279 ;; This is used by C-c C-c for property action.
16280 (save-excursion
16281 (beginning-of-line 1)
16282 (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))))
16284 (defmacro org-with-point-at (pom &rest body)
16285 "Move to buffer and point of point-or-marker POM for the duration of BODY."
16286 (declare (indent 1) (debug t))
16287 `(save-excursion
16288 (if (markerp pom) (set-buffer (marker-buffer pom)))
16289 (save-excursion
16290 (goto-char (or pom (point)))
16291 ,@body)))
16293 (defun org-get-property-block (&optional beg end force)
16294 "Return the (beg . end) range of the body of the property drawer.
16295 BEG and END can be beginning and end of subtree, if not given
16296 they will be found.
16297 If the drawer does not exist and FORCE is non-nil, create the drawer."
16298 (catch 'exit
16299 (save-excursion
16300 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
16301 (end (or end (progn (outline-next-heading) (point)))))
16302 (goto-char beg)
16303 (if (re-search-forward org-property-start-re end t)
16304 (setq beg (1+ (match-end 0)))
16305 (if force
16306 (save-excursion
16307 (org-insert-property-drawer)
16308 (setq end (progn (outline-next-heading) (point))))
16309 (throw 'exit nil))
16310 (goto-char beg)
16311 (if (re-search-forward org-property-start-re end t)
16312 (setq beg (1+ (match-end 0)))))
16313 (if (re-search-forward org-property-end-re end t)
16314 (setq end (match-beginning 0))
16315 (or force (throw 'exit nil))
16316 (goto-char beg)
16317 (setq end beg)
16318 (org-indent-line-function)
16319 (insert ":END:\n"))
16320 (cons beg end)))))
16322 (defun org-entry-properties (&optional pom which)
16323 "Get all properties of the entry at point-or-marker POM.
16324 This includes the TODO keyword, the tags, time strings for deadline,
16325 scheduled, and clocking, and any additional properties defined in the
16326 entry. The return value is an alist, keys may occur multiple times
16327 if the property key was used several times.
16328 POM may also be nil, in which case the current entry is used.
16329 If WHICH is nil or `all', get all properties. If WHICH is
16330 `special' or `standard', only get that subclass."
16331 (setq which (or which 'all))
16332 (org-with-point-at pom
16333 (let ((clockstr (substring org-clock-string 0 -1))
16334 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY"))
16335 beg end range props sum-props key value string clocksum)
16336 (save-excursion
16337 (when (condition-case nil (org-back-to-heading t) (error nil))
16338 (setq beg (point))
16339 (setq sum-props (get-text-property (point) 'org-summaries))
16340 (setq clocksum (get-text-property (point) :org-clock-minutes))
16341 (outline-next-heading)
16342 (setq end (point))
16343 (when (memq which '(all special))
16344 ;; Get the special properties, like TODO and tags
16345 (goto-char beg)
16346 (when (and (looking-at org-todo-line-regexp) (match-end 2))
16347 (push (cons "TODO" (org-match-string-no-properties 2)) props))
16348 (when (looking-at org-priority-regexp)
16349 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
16350 (when (and (setq value (org-get-tags-string))
16351 (string-match "\\S-" value))
16352 (push (cons "TAGS" value) props))
16353 (when (setq value (org-get-tags-at))
16354 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":") ":"))
16355 props))
16356 (while (re-search-forward org-maybe-keyword-time-regexp end t)
16357 (setq key (if (match-end 1) (substring (org-match-string-no-properties 1) 0 -1))
16358 string (if (equal key clockstr)
16359 (org-no-properties
16360 (org-trim
16361 (buffer-substring
16362 (match-beginning 3) (goto-char (point-at-eol)))))
16363 (substring (org-match-string-no-properties 3) 1 -1)))
16364 (unless key
16365 (if (= (char-after (match-beginning 3)) ?\[)
16366 (setq key "TIMESTAMP_IA")
16367 (setq key "TIMESTAMP")))
16368 (when (or (equal key clockstr) (not (assoc key props)))
16369 (push (cons key string) props)))
16373 (when (memq which '(all standard))
16374 ;; Get the standard properties, like :PORP: ...
16375 (setq range (org-get-property-block beg end))
16376 (when range
16377 (goto-char (car range))
16378 (while (re-search-forward
16379 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
16380 (cdr range) t)
16381 (setq key (org-match-string-no-properties 1)
16382 value (org-trim (or (org-match-string-no-properties 2) "")))
16383 (unless (member key excluded)
16384 (push (cons key (or value "")) props)))))
16385 (if clocksum
16386 (push (cons "CLOCKSUM"
16387 (org-column-number-to-string (/ (float clocksum) 60.)
16388 'add_times))
16389 props))
16390 (append sum-props (nreverse props)))))))
16392 (defun org-entry-get (pom property &optional inherit)
16393 "Get value of PROPERTY for entry at point-or-marker POM.
16394 If INHERIT is non-nil and the entry does not have the property,
16395 then also check higher levels of the hierarchy.
16396 If the property is present but empty, the return value is the empty string.
16397 If the property is not present at all, nil is returned."
16398 (org-with-point-at pom
16399 (if inherit
16400 (org-entry-get-with-inheritance property)
16401 (if (member property org-special-properties)
16402 ;; We need a special property. Use brute force, get all properties.
16403 (cdr (assoc property (org-entry-properties nil 'special)))
16404 (let ((range (org-get-property-block)))
16405 (if (and range
16406 (goto-char (car range))
16407 (re-search-forward
16408 (concat "^[ \t]*:" property ":[ \t]*\\(.*\\S-\\)?")
16409 (cdr range) t))
16410 ;; Found the property, return it.
16411 (if (match-end 1)
16412 (org-match-string-no-properties 1)
16413 "")))))))
16415 (defun org-entry-delete (pom property)
16416 "Delete the property PROPERTY from entry at point-or-marker POM."
16417 (org-with-point-at pom
16418 (if (member property org-special-properties)
16419 nil ; cannot delete these properties.
16420 (let ((range (org-get-property-block)))
16421 (if (and range
16422 (goto-char (car range))
16423 (re-search-forward
16424 (concat "^[ \t]*:" property ":[ \t]*\\(.*\\S-\\)")
16425 (cdr range) t))
16426 (progn
16427 (delete-region (match-beginning 0) (1+ (point-at-eol)))
16429 nil)))))
16431 ;; Multi-values properties are properties that contain multiple values
16432 ;; These values are assumed to be single words, separated by whitespace.
16433 (defun org-entry-add-to-multivalued-property (pom property value)
16434 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
16435 (let* ((old (org-entry-get pom property))
16436 (values (and old (org-split-string old "[ \t]"))))
16437 (unless (member value values)
16438 (setq values (cons value values))
16439 (org-entry-put pom property
16440 (mapconcat 'identity values " ")))))
16442 (defun org-entry-remove-from-multivalued-property (pom property value)
16443 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
16444 (let* ((old (org-entry-get pom property))
16445 (values (and old (org-split-string old "[ \t]"))))
16446 (when (member value values)
16447 (setq values (delete value values))
16448 (org-entry-put pom property
16449 (mapconcat 'identity values " ")))))
16451 (defun org-entry-member-in-multivalued-property (pom property value)
16452 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
16453 (let* ((old (org-entry-get pom property))
16454 (values (and old (org-split-string old "[ \t]"))))
16455 (member value values)))
16457 (defvar org-entry-property-inherited-from (make-marker))
16459 (defun org-entry-get-with-inheritance (property)
16460 "Get entry property, and search higher levels if not present."
16461 (let (tmp)
16462 (save-excursion
16463 (save-restriction
16464 (widen)
16465 (catch 'ex
16466 (while t
16467 (when (setq tmp (org-entry-get nil property))
16468 (org-back-to-heading t)
16469 (move-marker org-entry-property-inherited-from (point))
16470 (throw 'ex tmp))
16471 (or (org-up-heading-safe) (throw 'ex nil)))))
16472 (or tmp (cdr (assoc property org-local-properties))
16473 (cdr (assoc property org-global-properties))))))
16475 (defun org-entry-put (pom property value)
16476 "Set PROPERTY to VALUE for entry at point-or-marker POM."
16477 (org-with-point-at pom
16478 (org-back-to-heading t)
16479 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
16480 range)
16481 (cond
16482 ((equal property "TODO")
16483 (when (and (stringp value) (string-match "\\S-" value)
16484 (not (member value org-todo-keywords-1)))
16485 (error "\"%s\" is not a valid TODO state" value))
16486 (if (or (not value)
16487 (not (string-match "\\S-" value)))
16488 (setq value 'none))
16489 (org-todo value)
16490 (org-set-tags nil 'align))
16491 ((equal property "PRIORITY")
16492 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
16493 (string-to-char value) ?\ ))
16494 (org-set-tags nil 'align))
16495 ((equal property "SCHEDULED")
16496 (if (re-search-forward org-scheduled-time-regexp end t)
16497 (cond
16498 ((eq value 'earlier) (org-timestamp-change -1 'day))
16499 ((eq value 'later) (org-timestamp-change 1 'day))
16500 (t (call-interactively 'org-schedule)))
16501 (call-interactively 'org-schedule)))
16502 ((equal property "DEADLINE")
16503 (if (re-search-forward org-deadline-time-regexp end t)
16504 (cond
16505 ((eq value 'earlier) (org-timestamp-change -1 'day))
16506 ((eq value 'later) (org-timestamp-change 1 'day))
16507 (t (call-interactively 'org-deadline)))
16508 (call-interactively 'org-deadline)))
16509 ((member property org-special-properties)
16510 (error "The %s property can not yet be set with `org-entry-put'"
16511 property))
16512 (t ; a non-special property
16513 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
16514 (setq range (org-get-property-block beg end 'force))
16515 (goto-char (car range))
16516 (if (re-search-forward
16517 (concat "^[ \t]*:" property ":\\(.*\\)") (cdr range) t)
16518 (progn
16519 (delete-region (match-beginning 1) (match-end 1))
16520 (goto-char (match-beginning 1)))
16521 (goto-char (cdr range))
16522 (insert "\n")
16523 (backward-char 1)
16524 (org-indent-line-function)
16525 (insert ":" property ":"))
16526 (and value (insert " " value))
16527 (org-indent-line-function)))))))
16529 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
16530 "Get all property keys in the current buffer.
16531 With INCLUDE-SPECIALS, also list the special properties that relect things
16532 like tags and TODO state.
16533 With INCLUDE-DEFAULTS, also include properties that has special meaning
16534 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING.
16535 With INCLUDE-COLUMNS, also include property names given in COLUMN
16536 formats in the current buffer."
16537 (let (rtn range cfmt cols s p)
16538 (save-excursion
16539 (save-restriction
16540 (widen)
16541 (goto-char (point-min))
16542 (while (re-search-forward org-property-start-re nil t)
16543 (setq range (org-get-property-block))
16544 (goto-char (car range))
16545 (while (re-search-forward
16546 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
16547 (cdr range) t)
16548 (add-to-list 'rtn (org-match-string-no-properties 1)))
16549 (outline-next-heading))))
16551 (when include-specials
16552 (setq rtn (append org-special-properties rtn)))
16554 (when include-defaults
16555 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties))
16557 (when include-columns
16558 (save-excursion
16559 (save-restriction
16560 (widen)
16561 (goto-char (point-min))
16562 (while (re-search-forward
16563 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
16564 nil t)
16565 (setq cfmt (match-string 2) s 0)
16566 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
16567 cfmt s)
16568 (setq s (match-end 0)
16569 p (match-string 1 cfmt))
16570 (unless (or (equal p "ITEM")
16571 (member p org-special-properties))
16572 (add-to-list 'rtn (match-string 1 cfmt))))))))
16574 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
16576 (defun org-property-values (key)
16577 "Return a list of all values of property KEY."
16578 (save-excursion
16579 (save-restriction
16580 (widen)
16581 (goto-char (point-min))
16582 (let ((re (concat "^[ \t]*:" key ":[ \t]*\\(\\S-.*\\)"))
16583 values)
16584 (while (re-search-forward re nil t)
16585 (add-to-list 'values (org-trim (match-string 1))))
16586 (delete "" values)))))
16588 (defun org-insert-property-drawer ()
16589 "Insert a property drawer into the current entry."
16590 (interactive)
16591 (org-back-to-heading t)
16592 (looking-at outline-regexp)
16593 (let ((indent (- (match-end 0)(match-beginning 0)))
16594 (beg (point))
16595 (re (concat "^[ \t]*" org-keyword-time-regexp))
16596 end hiddenp)
16597 (outline-next-heading)
16598 (setq end (point))
16599 (goto-char beg)
16600 (while (re-search-forward re end t))
16601 (setq hiddenp (org-invisible-p))
16602 (end-of-line 1)
16603 (and (equal (char-after) ?\n) (forward-char 1))
16604 (org-skip-over-state-notes)
16605 (skip-chars-backward " \t\n\r")
16606 (if (eq (char-before) ?*) (forward-char 1))
16607 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
16608 (beginning-of-line 0)
16609 (indent-to-column indent)
16610 (beginning-of-line 2)
16611 (indent-to-column indent)
16612 (beginning-of-line 0)
16613 (if hiddenp
16614 (save-excursion
16615 (org-back-to-heading t)
16616 (hide-entry))
16617 (org-flag-drawer t))))
16619 (defun org-set-property (property value)
16620 "In the current entry, set PROPERTY to VALUE.
16621 When called interactively, this will prompt for a property name, offering
16622 completion on existing and default properties. And then it will prompt
16623 for a value, offering competion either on allowed values (via an inherited
16624 xxx_ALL property) or on existing values in other instances of this property
16625 in the current file."
16626 (interactive
16627 (let* ((prop (completing-read
16628 "Property: " (mapcar 'list (org-buffer-property-keys nil t t))))
16629 (cur (org-entry-get nil prop))
16630 (allowed (org-property-get-allowed-values nil prop 'table))
16631 (existing (mapcar 'list (org-property-values prop)))
16632 (val (if allowed
16633 (completing-read "Value: " allowed nil 'req-match)
16634 (completing-read
16635 (concat "Value" (if (and cur (string-match "\\S-" cur))
16636 (concat "[" cur "]") "")
16637 ": ")
16638 existing nil nil "" nil cur))))
16639 (list prop (if (equal val "") cur val))))
16640 (unless (equal (org-entry-get nil property) value)
16641 (org-entry-put nil property value)))
16643 (defun org-delete-property (property)
16644 "In the current entry, delete PROPERTY."
16645 (interactive
16646 (let* ((prop (completing-read
16647 "Property: " (org-entry-properties nil 'standard))))
16648 (list prop)))
16649 (message "Property %s %s" property
16650 (if (org-entry-delete nil property)
16651 "deleted"
16652 "was not present in the entry")))
16654 (defun org-delete-property-globally (property)
16655 "Remove PROPERTY globally, from all entries."
16656 (interactive
16657 (let* ((prop (completing-read
16658 "Globally remove property: "
16659 (mapcar 'list (org-buffer-property-keys)))))
16660 (list prop)))
16661 (save-excursion
16662 (save-restriction
16663 (widen)
16664 (goto-char (point-min))
16665 (let ((cnt 0))
16666 (while (re-search-forward
16667 (concat "^[ \t]*:" (regexp-quote property) ":.*\n?")
16668 nil t)
16669 (setq cnt (1+ cnt))
16670 (replace-match ""))
16671 (message "Property \"%s\" removed from %d entries" property cnt)))))
16673 (defvar org-columns-current-fmt-compiled) ; defined below
16675 (defun org-compute-property-at-point ()
16676 "Compute the property at point.
16677 This looks for an enclosing column format, extracts the operator and
16678 then applies it to the proerty in the column format's scope."
16679 (interactive)
16680 (unless (org-at-property-p)
16681 (error "Not at a property"))
16682 (let ((prop (org-match-string-no-properties 2)))
16683 (org-columns-get-format-and-top-level)
16684 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
16685 (error "No operator defined for property %s" prop))
16686 (org-columns-compute prop)))
16688 (defun org-property-get-allowed-values (pom property &optional table)
16689 "Get allowed values for the property PROPERTY.
16690 When TABLE is non-nil, return an alist that can directly be used for
16691 completion."
16692 (let (vals)
16693 (cond
16694 ((equal property "TODO")
16695 (setq vals (org-with-point-at pom
16696 (append org-todo-keywords-1 '("")))))
16697 ((equal property "PRIORITY")
16698 (let ((n org-lowest-priority))
16699 (while (>= n org-highest-priority)
16700 (push (char-to-string n) vals)
16701 (setq n (1- n)))))
16702 ((member property org-special-properties))
16704 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
16706 (when (and vals (string-match "\\S-" vals))
16707 (setq vals (car (read-from-string (concat "(" vals ")"))))
16708 (setq vals (mapcar (lambda (x)
16709 (cond ((stringp x) x)
16710 ((numberp x) (number-to-string x))
16711 ((symbolp x) (symbol-name x))
16712 (t "???")))
16713 vals)))))
16714 (if table (mapcar 'list vals) vals)))
16716 (defun org-property-previous-allowed-value (&optional previous)
16717 "Switch to the next allowed value for this property."
16718 (interactive)
16719 (org-property-next-allowed-value t))
16721 (defun org-property-next-allowed-value (&optional previous)
16722 "Switch to the next allowed value for this property."
16723 (interactive)
16724 (unless (org-at-property-p)
16725 (error "Not at a property"))
16726 (let* ((key (match-string 2))
16727 (value (match-string 3))
16728 (allowed (or (org-property-get-allowed-values (point) key)
16729 (and (member value '("[ ]" "[-]" "[X]"))
16730 '("[ ]" "[X]"))))
16731 nval)
16732 (unless allowed
16733 (error "Allowed values for this property have not been defined"))
16734 (if previous (setq allowed (reverse allowed)))
16735 (if (member value allowed)
16736 (setq nval (car (cdr (member value allowed)))))
16737 (setq nval (or nval (car allowed)))
16738 (if (equal nval value)
16739 (error "Only one allowed value for this property"))
16740 (org-at-property-p)
16741 (replace-match (concat " :" key ": " nval) t t)
16742 (org-indent-line-function)
16743 (beginning-of-line 1)
16744 (skip-chars-forward " \t")))
16746 (defun org-find-entry-with-id (ident)
16747 "Locate the entry that contains the ID property with exact value IDENT.
16748 IDENT can be a string, a symbol or a number, this function will search for
16749 the string representation of it.
16750 Return the position where this entry starts, or nil if there is no such entry."
16751 (let ((id (cond
16752 ((stringp ident) ident)
16753 ((symbol-name ident) (symbol-name ident))
16754 ((numberp ident) (number-to-string ident))
16755 (t (error "IDENT %s must be a string, symbol or number" ident))))
16756 (case-fold-search nil))
16757 (save-excursion
16758 (save-restriction
16759 (widen)
16760 (goto-char (point-min))
16761 (when (re-search-forward
16762 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
16763 nil t)
16764 (org-back-to-heading)
16765 (point))))))
16767 ;;; Column View
16769 (defvar org-columns-overlays nil
16770 "Holds the list of current column overlays.")
16772 (defvar org-columns-current-fmt nil
16773 "Local variable, holds the currently active column format.")
16774 (defvar org-columns-current-fmt-compiled nil
16775 "Local variable, holds the currently active column format.
16776 This is the compiled version of the format.")
16777 (defvar org-columns-current-widths nil
16778 "Loval variable, holds the currently widths of fields.")
16779 (defvar org-columns-current-maxwidths nil
16780 "Loval variable, holds the currently active maximum column widths.")
16781 (defvar org-columns-begin-marker (make-marker)
16782 "Points to the position where last a column creation command was called.")
16783 (defvar org-columns-top-level-marker (make-marker)
16784 "Points to the position where current columns region starts.")
16786 (defvar org-columns-map (make-sparse-keymap)
16787 "The keymap valid in column display.")
16789 (defun org-columns-content ()
16790 "Switch to contents view while in columns view."
16791 (interactive)
16792 (org-overview)
16793 (org-content))
16795 (org-defkey org-columns-map "c" 'org-columns-content)
16796 (org-defkey org-columns-map "o" 'org-overview)
16797 (org-defkey org-columns-map "e" 'org-columns-edit-value)
16798 (org-defkey org-columns-map "\C-c\C-t" 'org-columns-todo)
16799 (org-defkey org-columns-map "\C-c\C-c" 'org-columns-set-tags-or-toggle)
16800 (org-defkey org-columns-map "\C-c\C-o" 'org-columns-open-link)
16801 (org-defkey org-columns-map "v" 'org-columns-show-value)
16802 (org-defkey org-columns-map "q" 'org-columns-quit)
16803 (org-defkey org-columns-map "r" 'org-columns-redo)
16804 (org-defkey org-columns-map "g" 'org-columns-redo)
16805 (org-defkey org-columns-map [left] 'backward-char)
16806 (org-defkey org-columns-map "\M-b" 'backward-char)
16807 (org-defkey org-columns-map "a" 'org-columns-edit-allowed)
16808 (org-defkey org-columns-map "s" 'org-columns-edit-attributes)
16809 (org-defkey org-columns-map "\M-f" (lambda () (interactive) (goto-char (1+ (point)))))
16810 (org-defkey org-columns-map [right] (lambda () (interactive) (goto-char (1+ (point)))))
16811 (org-defkey org-columns-map [(shift right)] 'org-columns-next-allowed-value)
16812 (org-defkey org-columns-map "n" 'org-columns-next-allowed-value)
16813 (org-defkey org-columns-map [(shift left)] 'org-columns-previous-allowed-value)
16814 (org-defkey org-columns-map "p" 'org-columns-previous-allowed-value)
16815 (org-defkey org-columns-map "<" 'org-columns-narrow)
16816 (org-defkey org-columns-map ">" 'org-columns-widen)
16817 (org-defkey org-columns-map [(meta right)] 'org-columns-move-right)
16818 (org-defkey org-columns-map [(meta left)] 'org-columns-move-left)
16819 (org-defkey org-columns-map [(shift meta right)] 'org-columns-new)
16820 (org-defkey org-columns-map [(shift meta left)] 'org-columns-delete)
16822 (easy-menu-define org-columns-menu org-columns-map "Org Column Menu"
16823 '("Column"
16824 ["Edit property" org-columns-edit-value t]
16825 ["Next allowed value" org-columns-next-allowed-value t]
16826 ["Previous allowed value" org-columns-previous-allowed-value t]
16827 ["Show full value" org-columns-show-value t]
16828 ["Edit allowed values" org-columns-edit-allowed t]
16829 "--"
16830 ["Edit column attributes" org-columns-edit-attributes t]
16831 ["Increase column width" org-columns-widen t]
16832 ["Decrease column width" org-columns-narrow t]
16833 "--"
16834 ["Move column right" org-columns-move-right t]
16835 ["Move column left" org-columns-move-left t]
16836 ["Add column" org-columns-new t]
16837 ["Delete column" org-columns-delete t]
16838 "--"
16839 ["CONTENTS" org-columns-content t]
16840 ["OVERVIEW" org-overview t]
16841 ["Refresh columns display" org-columns-redo t]
16842 "--"
16843 ["Open link" org-columns-open-link t]
16844 "--"
16845 ["Quit" org-columns-quit t]))
16847 (defun org-columns-new-overlay (beg end &optional string face)
16848 "Create a new column overlay and add it to the list."
16849 (let ((ov (org-make-overlay beg end)))
16850 (org-overlay-put ov 'face (or face 'secondary-selection))
16851 (org-overlay-display ov string face)
16852 (push ov org-columns-overlays)
16853 ov))
16855 (defun org-columns-display-here (&optional props)
16856 "Overlay the current line with column display."
16857 (interactive)
16858 (let* ((fmt org-columns-current-fmt-compiled)
16859 (beg (point-at-bol))
16860 (level-face (save-excursion
16861 (beginning-of-line 1)
16862 (and (looking-at "\\(\\**\\)\\(\\* \\)")
16863 (org-get-level-face 2))))
16864 (color (list :foreground
16865 (face-attribute (or level-face 'default) :foreground)))
16866 props pom property ass width f string ov column val modval)
16867 ;; Check if the entry is in another buffer.
16868 (unless props
16869 (if (eq major-mode 'org-agenda-mode)
16870 (setq pom (or (get-text-property (point) 'org-hd-marker)
16871 (get-text-property (point) 'org-marker))
16872 props (if pom (org-entry-properties pom) nil))
16873 (setq props (org-entry-properties nil))))
16874 ;; Walk the format
16875 (while (setq column (pop fmt))
16876 (setq property (car column)
16877 ass (if (equal property "ITEM")
16878 (cons "ITEM"
16879 (save-match-data
16880 (org-no-properties
16881 (org-remove-tabs
16882 (buffer-substring-no-properties
16883 (point-at-bol) (point-at-eol))))))
16884 (assoc property props))
16885 width (or (cdr (assoc property org-columns-current-maxwidths))
16886 (nth 2 column)
16887 (length property))
16888 f (format "%%-%d.%ds | " width width)
16889 val (or (cdr ass) "")
16890 modval (if (equal property "ITEM")
16891 (org-columns-cleanup-item val org-columns-current-fmt-compiled))
16892 string (format f (or modval val)))
16893 ;; Create the overlay
16894 (org-unmodified
16895 (setq ov (org-columns-new-overlay
16896 beg (setq beg (1+ beg)) string
16897 (list color 'org-column)))
16898 ;;; (list (get-text-property (point-at-bol) 'face) 'org-column)))
16899 (org-overlay-put ov 'keymap org-columns-map)
16900 (org-overlay-put ov 'org-columns-key property)
16901 (org-overlay-put ov 'org-columns-value (cdr ass))
16902 (org-overlay-put ov 'org-columns-value-modified modval)
16903 (org-overlay-put ov 'org-columns-pom pom)
16904 (org-overlay-put ov 'org-columns-format f))
16905 (if (or (not (char-after beg))
16906 (equal (char-after beg) ?\n))
16907 (let ((inhibit-read-only t))
16908 (save-excursion
16909 (goto-char beg)
16910 (org-unmodified (insert " ")))))) ;; FIXME: add props and remove later?
16911 ;; Make the rest of the line disappear.
16912 (org-unmodified
16913 (setq ov (org-columns-new-overlay beg (point-at-eol)))
16914 (org-overlay-put ov 'invisible t)
16915 (org-overlay-put ov 'keymap org-columns-map)
16916 (org-overlay-put ov 'intangible t)
16917 (push ov org-columns-overlays)
16918 (setq ov (org-make-overlay (1- (point-at-eol)) (1+ (point-at-eol))))
16919 (org-overlay-put ov 'keymap org-columns-map)
16920 (push ov org-columns-overlays)
16921 (let ((inhibit-read-only t))
16922 (put-text-property (max (point-min) (1- (point-at-bol)))
16923 (min (point-max) (1+ (point-at-eol)))
16924 'read-only "Type `e' to edit property")))))
16926 (defvar org-previous-header-line-format nil
16927 "The header line format before column view was turned on.")
16928 (defvar org-columns-inhibit-recalculation nil
16929 "Inhibit recomputing of columns on column view startup.")
16932 (defvar header-line-format)
16933 (defun org-columns-display-here-title ()
16934 "Overlay the newline before the current line with the table title."
16935 (interactive)
16936 (let ((fmt org-columns-current-fmt-compiled)
16937 string (title "")
16938 property width f column str widths)
16939 (while (setq column (pop fmt))
16940 (setq property (car column)
16941 str (or (nth 1 column) property)
16942 width (or (cdr (assoc property org-columns-current-maxwidths))
16943 (nth 2 column)
16944 (length str))
16945 widths (push width widths)
16946 f (format "%%-%d.%ds | " width width)
16947 string (format f str)
16948 title (concat title string)))
16949 (setq title (concat
16950 (org-add-props " " nil 'display '(space :align-to 0))
16951 (org-add-props title nil 'face '(:weight bold :underline t))))
16952 (org-set-local 'org-previous-header-line-format header-line-format)
16953 (org-set-local 'org-columns-current-widths (nreverse widths))
16954 (setq header-line-format title)))
16956 (defun org-columns-remove-overlays ()
16957 "Remove all currently active column overlays."
16958 (interactive)
16959 (when (marker-buffer org-columns-begin-marker)
16960 (with-current-buffer (marker-buffer org-columns-begin-marker)
16961 (when (local-variable-p 'org-previous-header-line-format)
16962 (setq header-line-format org-previous-header-line-format)
16963 (kill-local-variable 'org-previous-header-line-format))
16964 (move-marker org-columns-begin-marker nil)
16965 (move-marker org-columns-top-level-marker nil)
16966 (org-unmodified
16967 (mapc 'org-delete-overlay org-columns-overlays)
16968 (setq org-columns-overlays nil)
16969 (let ((inhibit-read-only t))
16970 (remove-text-properties (point-min) (point-max) '(read-only t)))))))
16972 (defun org-columns-cleanup-item (item fmt)
16973 "Remove from ITEM what is a column in the format FMT."
16974 (if (not org-complex-heading-regexp)
16975 item
16976 (when (string-match org-complex-heading-regexp item)
16977 (concat
16978 (org-add-props (concat (match-string 1 item) " ") nil
16979 'org-whitespace (* 2 (1- (org-reduced-level (- (match-end 1) (match-beginning 1))))))
16980 (and (match-end 2) (not (assoc "TODO" fmt)) (concat " " (match-string 2 item)))
16981 (and (match-end 3) (not (assoc "PRIORITY" fmt)) (concat " " (match-string 3 item)))
16982 " " (match-string 4 item)
16983 (and (match-end 5) (not (assoc "TAGS" fmt)) (concat " " (match-string 5 item)))))))
16985 (defun org-columns-show-value ()
16986 "Show the full value of the property."
16987 (interactive)
16988 (let ((value (get-char-property (point) 'org-columns-value)))
16989 (message "Value is: %s" (or value ""))))
16991 (defun org-columns-quit ()
16992 "Remove the column overlays and in this way exit column editing."
16993 (interactive)
16994 (org-unmodified
16995 (org-columns-remove-overlays)
16996 (let ((inhibit-read-only t))
16997 (remove-text-properties (point-min) (point-max) '(read-only t))))
16998 (when (eq major-mode 'org-agenda-mode)
16999 (message
17000 "Modification not yet reflected in Agenda buffer, use `r' to refresh")))
17002 (defun org-columns-check-computed ()
17003 "Check if this column value is computed.
17004 If yes, throw an error indicating that changing it does not make sense."
17005 (let ((val (get-char-property (point) 'org-columns-value)))
17006 (when (and (stringp val)
17007 (get-char-property 0 'org-computed val))
17008 (error "This value is computed from the entry's children"))))
17010 (defun org-columns-todo (&optional arg)
17011 "Change the TODO state during column view."
17012 (interactive "P")
17013 (org-columns-edit-value "TODO"))
17015 (defun org-columns-set-tags-or-toggle (&optional arg)
17016 "Toggle checkbox at point, or set tags for current headline."
17017 (interactive "P")
17018 (if (string-match "\\`\\[[ xX-]\\]\\'"
17019 (get-char-property (point) 'org-columns-value))
17020 (org-columns-next-allowed-value)
17021 (org-columns-edit-value "TAGS")))
17023 (defun org-columns-edit-value (&optional key)
17024 "Edit the value of the property at point in column view.
17025 Where possible, use the standard interface for changing this line."
17026 (interactive)
17027 (org-columns-check-computed)
17028 (let* ((external-key key)
17029 (col (current-column))
17030 (key (or key (get-char-property (point) 'org-columns-key)))
17031 (value (get-char-property (point) 'org-columns-value))
17032 (bol (point-at-bol)) (eol (point-at-eol))
17033 (pom (or (get-text-property bol 'org-hd-marker)
17034 (point))) ; keep despite of compiler waring
17035 (line-overlays
17036 (delq nil (mapcar (lambda (x)
17037 (and (eq (overlay-buffer x) (current-buffer))
17038 (>= (overlay-start x) bol)
17039 (<= (overlay-start x) eol)
17041 org-columns-overlays)))
17042 nval eval allowed)
17043 (cond
17044 ((equal key "CLOCKSUM")
17045 (error "This special column cannot be edited"))
17046 ((equal key "ITEM")
17047 (setq eval '(org-with-point-at pom
17048 (org-edit-headline))))
17049 ((equal key "TODO")
17050 (setq eval '(org-with-point-at pom
17051 (let ((current-prefix-arg
17052 (if external-key current-prefix-arg '(4))))
17053 (call-interactively 'org-todo)))))
17054 ((equal key "PRIORITY")
17055 (setq eval '(org-with-point-at pom
17056 (call-interactively 'org-priority))))
17057 ((equal key "TAGS")
17058 (setq eval '(org-with-point-at pom
17059 (let ((org-fast-tag-selection-single-key
17060 (if (eq org-fast-tag-selection-single-key 'expert)
17061 t org-fast-tag-selection-single-key)))
17062 (call-interactively 'org-set-tags)))))
17063 ((equal key "DEADLINE")
17064 (setq eval '(org-with-point-at pom
17065 (call-interactively 'org-deadline))))
17066 ((equal key "SCHEDULED")
17067 (setq eval '(org-with-point-at pom
17068 (call-interactively 'org-schedule))))
17070 (setq allowed (org-property-get-allowed-values pom key 'table))
17071 (if allowed
17072 (setq nval (completing-read "Value: " allowed nil t))
17073 (setq nval (read-string "Edit: " value)))
17074 (setq nval (org-trim nval))
17075 (when (not (equal nval value))
17076 (setq eval '(org-entry-put pom key nval)))))
17077 (when eval
17078 (let ((inhibit-read-only t))
17079 (remove-text-properties (max (point-min) (1- bol)) eol '(read-only t))
17080 (unwind-protect
17081 (progn
17082 (setq org-columns-overlays
17083 (org-delete-all line-overlays org-columns-overlays))
17084 (mapc 'org-delete-overlay line-overlays)
17085 (org-columns-eval eval))
17086 (org-columns-display-here))))
17087 (move-to-column col)
17088 (if (and (org-mode-p)
17089 (nth 3 (assoc key org-columns-current-fmt-compiled)))
17090 (org-columns-update key))))
17092 (defun org-edit-headline () ; FIXME: this is not columns specific
17093 "Edit the current headline, the part without TODO keyword, TAGS."
17094 (org-back-to-heading)
17095 (when (looking-at org-todo-line-regexp)
17096 (let ((pre (buffer-substring (match-beginning 0) (match-beginning 3)))
17097 (txt (match-string 3))
17098 (post "")
17099 txt2)
17100 (if (string-match (org-re "[ \t]+:[[:alnum:]:_@]+:[ \t]*$") txt)
17101 (setq post (match-string 0 txt)
17102 txt (substring txt 0 (match-beginning 0))))
17103 (setq txt2 (read-string "Edit: " txt))
17104 (when (not (equal txt txt2))
17105 (beginning-of-line 1)
17106 (insert pre txt2 post)
17107 (delete-region (point) (point-at-eol))
17108 (org-set-tags nil t)))))
17110 (defun org-columns-edit-allowed ()
17111 "Edit the list of allowed values for the current property."
17112 (interactive)
17113 (let* ((key (get-char-property (point) 'org-columns-key))
17114 (key1 (concat key "_ALL"))
17115 (allowed (org-entry-get (point) key1 t))
17116 nval)
17117 ;; FIXME: Cover editing TODO, TAGS etc in-buffer settings.????
17118 (setq nval (read-string "Allowed: " allowed))
17119 (org-entry-put
17120 (cond ((marker-position org-entry-property-inherited-from)
17121 org-entry-property-inherited-from)
17122 ((marker-position org-columns-top-level-marker)
17123 org-columns-top-level-marker))
17124 key1 nval)))
17126 (defmacro org-no-warnings (&rest body)
17127 (cons (if (fboundp 'with-no-warnings) 'with-no-warnings 'progn) body))
17129 (defun org-columns-eval (form)
17130 (let (hidep)
17131 (save-excursion
17132 (beginning-of-line 1)
17133 ;; `next-line' is needed here, because it skips invisible line.
17134 (condition-case nil (org-no-warnings (next-line 1)) (error nil))
17135 (setq hidep (org-on-heading-p 1)))
17136 (eval form)
17137 (and hidep (hide-entry))))
17139 (defun org-columns-previous-allowed-value ()
17140 "Switch to the previous allowed value for this column."
17141 (interactive)
17142 (org-columns-next-allowed-value t))
17144 (defun org-columns-next-allowed-value (&optional previous)
17145 "Switch to the next allowed value for this column."
17146 (interactive)
17147 (org-columns-check-computed)
17148 (let* ((col (current-column))
17149 (key (get-char-property (point) 'org-columns-key))
17150 (value (get-char-property (point) 'org-columns-value))
17151 (bol (point-at-bol)) (eol (point-at-eol))
17152 (pom (or (get-text-property bol 'org-hd-marker)
17153 (point))) ; keep despite of compiler waring
17154 (line-overlays
17155 (delq nil (mapcar (lambda (x)
17156 (and (eq (overlay-buffer x) (current-buffer))
17157 (>= (overlay-start x) bol)
17158 (<= (overlay-start x) eol)
17160 org-columns-overlays)))
17161 (allowed (or (org-property-get-allowed-values pom key)
17162 (and (memq
17163 (nth 4 (assoc key org-columns-current-fmt-compiled))
17164 '(checkbox checkbox-n-of-m checkbox-percent))
17165 '("[ ]" "[X]"))))
17166 nval)
17167 (when (equal key "ITEM")
17168 (error "Cannot edit item headline from here"))
17169 (unless (or allowed (member key '("SCHEDULED" "DEADLINE")))
17170 (error "Allowed values for this property have not been defined"))
17171 (if (member key '("SCHEDULED" "DEADLINE"))
17172 (setq nval (if previous 'earlier 'later))
17173 (if previous (setq allowed (reverse allowed)))
17174 (if (member value allowed)
17175 (setq nval (car (cdr (member value allowed)))))
17176 (setq nval (or nval (car allowed)))
17177 (if (equal nval value)
17178 (error "Only one allowed value for this property")))
17179 (let ((inhibit-read-only t))
17180 (remove-text-properties (1- bol) eol '(read-only t))
17181 (unwind-protect
17182 (progn
17183 (setq org-columns-overlays
17184 (org-delete-all line-overlays org-columns-overlays))
17185 (mapc 'org-delete-overlay line-overlays)
17186 (org-columns-eval '(org-entry-put pom key nval)))
17187 (org-columns-display-here)))
17188 (move-to-column col)
17189 (if (and (org-mode-p)
17190 (nth 3 (assoc key org-columns-current-fmt-compiled)))
17191 (org-columns-update key))))
17193 (defun org-verify-version (task)
17194 (cond
17195 ((eq task 'columns)
17196 (if (or (featurep 'xemacs)
17197 (< emacs-major-version 22))
17198 (error "Emacs 22 is required for the columns feature")))))
17200 (defun org-columns-open-link (&optional arg)
17201 (interactive "P")
17202 (let ((value (get-char-property (point) 'org-columns-value)))
17203 (org-open-link-from-string value arg)))
17205 (defun org-open-link-from-string (s &optional arg)
17206 "Open a link in the string S, as if it was in Org-mode."
17207 (interactive)
17208 (with-temp-buffer
17209 (let ((org-inhibit-startup t))
17210 (org-mode)
17211 (insert s)
17212 (goto-char (point-min))
17213 (org-open-at-point arg))))
17215 (defun org-columns-get-format-and-top-level ()
17216 (let (fmt)
17217 (when (condition-case nil (org-back-to-heading) (error nil))
17218 (move-marker org-entry-property-inherited-from nil)
17219 (setq fmt (org-entry-get nil "COLUMNS" t)))
17220 (setq fmt (or fmt org-columns-default-format))
17221 (org-set-local 'org-columns-current-fmt fmt)
17222 (org-columns-compile-format fmt)
17223 (if (marker-position org-entry-property-inherited-from)
17224 (move-marker org-columns-top-level-marker
17225 org-entry-property-inherited-from)
17226 (move-marker org-columns-top-level-marker (point)))
17227 fmt))
17229 (defun org-columns ()
17230 "Turn on column view on an org-mode file."
17231 (interactive)
17232 (org-verify-version 'columns)
17233 (org-columns-remove-overlays)
17234 (move-marker org-columns-begin-marker (point))
17235 (let (beg end fmt cache maxwidths)
17236 (setq fmt (org-columns-get-format-and-top-level))
17237 (save-excursion
17238 (goto-char org-columns-top-level-marker)
17239 (setq beg (point))
17240 (unless org-columns-inhibit-recalculation
17241 (org-columns-compute-all))
17242 (setq end (or (condition-case nil (org-end-of-subtree t t) (error nil))
17243 (point-max)))
17244 ;; Get and cache the properties
17245 (goto-char beg)
17246 (when (assoc "CLOCKSUM" org-columns-current-fmt-compiled)
17247 (save-excursion
17248 (save-restriction
17249 (narrow-to-region beg end)
17250 (org-clock-sum))))
17251 (while (re-search-forward (concat "^" outline-regexp) end t)
17252 (push (cons (org-current-line) (org-entry-properties)) cache))
17253 (when cache
17254 (setq maxwidths (org-columns-get-autowidth-alist fmt cache))
17255 (org-set-local 'org-columns-current-maxwidths maxwidths)
17256 (org-columns-display-here-title)
17257 (mapc (lambda (x)
17258 (goto-line (car x))
17259 (org-columns-display-here (cdr x)))
17260 cache)))))
17262 (defun org-columns-new (&optional prop title width op fmt &rest rest)
17263 "Insert a new column, to the leeft o the current column."
17264 (interactive)
17265 (let ((editp (and prop (assoc prop org-columns-current-fmt-compiled)))
17266 cell)
17267 (setq prop (completing-read
17268 "Property: " (mapcar 'list (org-buffer-property-keys t nil t))
17269 nil nil prop))
17270 (setq title (read-string (concat "Column title [" prop "]: ") (or title prop)))
17271 (setq width (read-string "Column width: " (if width (number-to-string width))))
17272 (if (string-match "\\S-" width)
17273 (setq width (string-to-number width))
17274 (setq width nil))
17275 (setq fmt (completing-read "Summary [none]: "
17276 '(("none") ("add_numbers") ("currency") ("add_times") ("checkbox") ("checkbox-n-of-m") ("checkbox-percent"))
17277 nil t))
17278 (if (string-match "\\S-" fmt)
17279 (setq fmt (intern fmt))
17280 (setq fmt nil))
17281 (if (eq fmt 'none) (setq fmt nil))
17282 (if editp
17283 (progn
17284 (setcar editp prop)
17285 (setcdr editp (list title width nil fmt)))
17286 (setq cell (nthcdr (1- (current-column))
17287 org-columns-current-fmt-compiled))
17288 (setcdr cell (cons (list prop title width nil fmt)
17289 (cdr cell))))
17290 (org-columns-store-format)
17291 (org-columns-redo)))
17293 (defun org-columns-delete ()
17294 "Delete the column at point from columns view."
17295 (interactive)
17296 (let* ((n (current-column))
17297 (title (nth 1 (nth n org-columns-current-fmt-compiled))))
17298 (when (y-or-n-p
17299 (format "Are you sure you want to remove column \"%s\"? " title))
17300 (setq org-columns-current-fmt-compiled
17301 (delq (nth n org-columns-current-fmt-compiled)
17302 org-columns-current-fmt-compiled))
17303 (org-columns-store-format)
17304 (org-columns-redo)
17305 (if (>= (current-column) (length org-columns-current-fmt-compiled))
17306 (backward-char 1)))))
17308 (defun org-columns-edit-attributes ()
17309 "Edit the attributes of the current column."
17310 (interactive)
17311 (let* ((n (current-column))
17312 (info (nth n org-columns-current-fmt-compiled)))
17313 (apply 'org-columns-new info)))
17315 (defun org-columns-widen (arg)
17316 "Make the column wider by ARG characters."
17317 (interactive "p")
17318 (let* ((n (current-column))
17319 (entry (nth n org-columns-current-fmt-compiled))
17320 (width (or (nth 2 entry)
17321 (cdr (assoc (car entry) org-columns-current-maxwidths)))))
17322 (setq width (max 1 (+ width arg)))
17323 (setcar (nthcdr 2 entry) width)
17324 (org-columns-store-format)
17325 (org-columns-redo)))
17327 (defun org-columns-narrow (arg)
17328 "Make the column nrrower by ARG characters."
17329 (interactive "p")
17330 (org-columns-widen (- arg)))
17332 (defun org-columns-move-right ()
17333 "Swap this column with the one to the right."
17334 (interactive)
17335 (let* ((n (current-column))
17336 (cell (nthcdr n org-columns-current-fmt-compiled))
17338 (when (>= n (1- (length org-columns-current-fmt-compiled)))
17339 (error "Cannot shift this column further to the right"))
17340 (setq e (car cell))
17341 (setcar cell (car (cdr cell)))
17342 (setcdr cell (cons e (cdr (cdr cell))))
17343 (org-columns-store-format)
17344 (org-columns-redo)
17345 (forward-char 1)))
17347 (defun org-columns-move-left ()
17348 "Swap this column with the one to the left."
17349 (interactive)
17350 (let* ((n (current-column)))
17351 (when (= n 0)
17352 (error "Cannot shift this column further to the left"))
17353 (backward-char 1)
17354 (org-columns-move-right)
17355 (backward-char 1)))
17357 (defun org-columns-store-format ()
17358 "Store the text version of the current columns format in appropriate place.
17359 This is either in the COLUMNS property of the node starting the current column
17360 display, or in the #+COLUMNS line of the current buffer."
17361 (let (fmt (cnt 0))
17362 (setq fmt (org-columns-uncompile-format org-columns-current-fmt-compiled))
17363 (org-set-local 'org-columns-current-fmt fmt)
17364 (if (marker-position org-columns-top-level-marker)
17365 (save-excursion
17366 (goto-char org-columns-top-level-marker)
17367 (if (and (org-at-heading-p)
17368 (org-entry-get nil "COLUMNS"))
17369 (org-entry-put nil "COLUMNS" fmt)
17370 (goto-char (point-min))
17371 ;; Overwrite all #+COLUMNS lines....
17372 (while (re-search-forward "^#\\+COLUMNS:.*" nil t)
17373 (setq cnt (1+ cnt))
17374 (replace-match (concat "#+COLUMNS: " fmt) t t))
17375 (unless (> cnt 0)
17376 (goto-char (point-min))
17377 (or (org-on-heading-p t) (outline-next-heading))
17378 (let ((inhibit-read-only t))
17379 (insert-before-markers "#+COLUMNS: " fmt "\n")))
17380 (org-set-local 'org-columns-default-format fmt))))))
17382 (defvar org-overriding-columns-format nil
17383 "When set, overrides any other definition.")
17384 (defvar org-agenda-view-columns-initially nil
17385 "When set, switch to columns view immediately after creating the agenda.")
17387 (defun org-agenda-columns ()
17388 "Turn on column view in the agenda."
17389 (interactive)
17390 (org-verify-version 'columns)
17391 (org-columns-remove-overlays)
17392 (move-marker org-columns-begin-marker (point))
17393 (let (fmt cache maxwidths m)
17394 (cond
17395 ((and (local-variable-p 'org-overriding-columns-format)
17396 org-overriding-columns-format)
17397 (setq fmt org-overriding-columns-format))
17398 ((setq m (get-text-property (point-at-bol) 'org-hd-marker))
17399 (setq fmt (org-entry-get m "COLUMNS" t)))
17400 ((and (boundp 'org-columns-current-fmt)
17401 (local-variable-p 'org-columns-current-fmt)
17402 org-columns-current-fmt)
17403 (setq fmt org-columns-current-fmt))
17404 ((setq m (next-single-property-change (point-min) 'org-hd-marker))
17405 (setq m (get-text-property m 'org-hd-marker))
17406 (setq fmt (org-entry-get m "COLUMNS" t))))
17407 (setq fmt (or fmt org-columns-default-format))
17408 (org-set-local 'org-columns-current-fmt fmt)
17409 (org-columns-compile-format fmt)
17410 (save-excursion
17411 ;; Get and cache the properties
17412 (goto-char (point-min))
17413 (while (not (eobp))
17414 (when (setq m (or (get-text-property (point) 'org-hd-marker)
17415 (get-text-property (point) 'org-marker)))
17416 (push (cons (org-current-line) (org-entry-properties m)) cache))
17417 (beginning-of-line 2))
17418 (when cache
17419 (setq maxwidths (org-columns-get-autowidth-alist fmt cache))
17420 (org-set-local 'org-columns-current-maxwidths maxwidths)
17421 (org-columns-display-here-title)
17422 (mapc (lambda (x)
17423 (goto-line (car x))
17424 (org-columns-display-here (cdr x)))
17425 cache)))))
17427 (defun org-columns-get-autowidth-alist (s cache)
17428 "Derive the maximum column widths from the format and the cache."
17429 (let ((start 0) rtn)
17430 (while (string-match (org-re "%\\([[:alpha:]][[:alnum:]_-]*\\)") s start)
17431 (push (cons (match-string 1 s) 1) rtn)
17432 (setq start (match-end 0)))
17433 (mapc (lambda (x)
17434 (setcdr x (apply 'max
17435 (mapcar
17436 (lambda (y)
17437 (length (or (cdr (assoc (car x) (cdr y))) " ")))
17438 cache))))
17439 rtn)
17440 rtn))
17442 (defun org-columns-compute-all ()
17443 "Compute all columns that have operators defined."
17444 (org-unmodified
17445 (remove-text-properties (point-min) (point-max) '(org-summaries t)))
17446 (let ((columns org-columns-current-fmt-compiled) col)
17447 (while (setq col (pop columns))
17448 (when (nth 3 col)
17449 (save-excursion
17450 (org-columns-compute (car col)))))))
17452 (defun org-columns-update (property)
17453 "Recompute PROPERTY, and update the columns display for it."
17454 (org-columns-compute property)
17455 (let (fmt val pos)
17456 (save-excursion
17457 (mapc (lambda (ov)
17458 (when (equal (org-overlay-get ov 'org-columns-key) property)
17459 (setq pos (org-overlay-start ov))
17460 (goto-char pos)
17461 (when (setq val (cdr (assoc property
17462 (get-text-property
17463 (point-at-bol) 'org-summaries))))
17464 (setq fmt (org-overlay-get ov 'org-columns-format))
17465 (org-overlay-put ov 'org-columns-value val)
17466 (org-overlay-put ov 'display (format fmt val)))))
17467 org-columns-overlays))))
17469 (defun org-columns-compute (property)
17470 "Sum the values of property PROPERTY hierarchically, for the entire buffer."
17471 (interactive)
17472 (let* ((re (concat "^" outline-regexp))
17473 (lmax 30) ; Does anyone use deeper levels???
17474 (lsum (make-vector lmax 0))
17475 (lflag (make-vector lmax nil))
17476 (level 0)
17477 (ass (assoc property org-columns-current-fmt-compiled))
17478 (format (nth 4 ass))
17479 (printf (nth 5 ass))
17480 (beg org-columns-top-level-marker)
17481 last-level val valflag flag end sumpos sum-alist sum str str1 useval)
17482 (save-excursion
17483 ;; Find the region to compute
17484 (goto-char beg)
17485 (setq end (condition-case nil (org-end-of-subtree t) (error (point-max))))
17486 (goto-char end)
17487 ;; Walk the tree from the back and do the computations
17488 (while (re-search-backward re beg t)
17489 (setq sumpos (match-beginning 0)
17490 last-level level
17491 level (org-outline-level)
17492 val (org-entry-get nil property)
17493 valflag (and val (string-match "\\S-" val)))
17494 (cond
17495 ((< level last-level)
17496 ;; put the sum of lower levels here as a property
17497 (setq sum (aref lsum last-level) ; current sum
17498 flag (aref lflag last-level) ; any valid entries from children?
17499 str (org-column-number-to-string sum format printf)
17500 str1 (org-add-props (copy-sequence str) nil 'org-computed t 'face 'bold)
17501 useval (if flag str1 (if valflag val ""))
17502 sum-alist (get-text-property sumpos 'org-summaries))
17503 (if (assoc property sum-alist)
17504 (setcdr (assoc property sum-alist) useval)
17505 (push (cons property useval) sum-alist)
17506 (org-unmodified
17507 (add-text-properties sumpos (1+ sumpos)
17508 (list 'org-summaries sum-alist))))
17509 (when val
17510 (org-entry-put nil property (if flag str val)))
17511 ;; add current to current level accumulator
17512 (when (or flag valflag)
17513 (aset lsum level (+ (aref lsum level)
17514 (if flag sum (org-column-string-to-number
17515 (if flag str val) format))))
17516 (aset lflag level t))
17517 ;; clear accumulators for deeper levels
17518 (loop for l from (1+ level) to (1- lmax) do
17519 (aset lsum l 0)
17520 (aset lflag l nil)))
17521 ((>= level last-level)
17522 ;; add what we have here to the accumulator for this level
17523 (aset lsum level (+ (aref lsum level)
17524 (org-column-string-to-number (or val "0") format)))
17525 (and valflag (aset lflag level t)))
17526 (t (error "This should not happen")))))))
17528 (defun org-columns-redo ()
17529 "Construct the column display again."
17530 (interactive)
17531 (message "Recomputing columns...")
17532 (save-excursion
17533 (if (marker-position org-columns-begin-marker)
17534 (goto-char org-columns-begin-marker))
17535 (org-columns-remove-overlays)
17536 (if (org-mode-p)
17537 (call-interactively 'org-columns)
17538 (call-interactively 'org-agenda-columns)))
17539 (message "Recomputing columns...done"))
17541 (defun org-columns-not-in-agenda ()
17542 (if (eq major-mode 'org-agenda-mode)
17543 (error "This command is only allowed in Org-mode buffers")))
17546 (defun org-string-to-number (s)
17547 "Convert string to number, and interpret hh:mm:ss."
17548 (if (not (string-match ":" s))
17549 (string-to-number s)
17550 (let ((l (nreverse (org-split-string s ":"))) (sum 0.0))
17551 (while l
17552 (setq sum (+ (string-to-number (pop l)) (/ sum 60))))
17553 sum)))
17555 (defun org-column-number-to-string (n fmt &optional printf)
17556 "Convert a computed column number to a string value, according to FMT."
17557 (cond
17558 ((eq fmt 'add_times)
17559 (let* ((h (floor n)) (m (floor (+ 0.5 (* 60 (- n h))))))
17560 (format "%d:%02d" h m)))
17561 ((eq fmt 'checkbox)
17562 (cond ((= n (floor n)) "[X]")
17563 ((> n 1.) "[-]")
17564 (t "[ ]")))
17565 ((memq fmt '(checkbox-n-of-m checkbox-percent))
17566 (let* ((n1 (floor n)) (n2 (floor (+ .5 (* 1000000 (- n n1))))))
17567 (org-nofm-to-completion n1 (+ n2 n1) (eq fmt 'checkbox-percent))))
17568 (printf (format printf n))
17569 ((eq fmt 'currency)
17570 (format "%.2f" n))
17571 (t (number-to-string n))))
17573 (defun org-nofm-to-completion (n m &optional percent)
17574 (if (not percent)
17575 (format "[%d/%d]" n m)
17576 (format "[%d%%]"(floor (+ 0.5 (* 100. (/ (* 1.0 n) m)))))))
17578 (defun org-column-string-to-number (s fmt)
17579 "Convert a column value to a number that can be used for column computing."
17580 (cond
17581 ((string-match ":" s)
17582 (let ((l (nreverse (org-split-string s ":"))) (sum 0.0))
17583 (while l
17584 (setq sum (+ (string-to-number (pop l)) (/ sum 60))))
17585 sum))
17586 ((memq fmt '(checkbox checkbox-n-of-m checkbox-percent))
17587 (if (equal s "[X]") 1. 0.000001))
17588 (t (string-to-number s))))
17590 (defun org-columns-uncompile-format (cfmt)
17591 "Turn the compiled columns format back into a string representation."
17592 (let ((rtn "") e s prop title op width fmt printf)
17593 (while (setq e (pop cfmt))
17594 (setq prop (car e)
17595 title (nth 1 e)
17596 width (nth 2 e)
17597 op (nth 3 e)
17598 fmt (nth 4 e)
17599 printf (nth 5 e))
17600 (cond
17601 ((eq fmt 'add_times) (setq op ":"))
17602 ((eq fmt 'checkbox) (setq op "X"))
17603 ((eq fmt 'checkbox-n-of-m) (setq op "X/"))
17604 ((eq fmt 'checkbox-percent) (setq op "X%"))
17605 ((eq fmt 'add_numbers) (setq op "+"))
17606 ((eq fmt 'currency) (setq op "$")))
17607 (if (and op printf) (setq op (concat op ";" printf)))
17608 (if (equal title prop) (setq title nil))
17609 (setq s (concat "%" (if width (number-to-string width))
17610 prop
17611 (if title (concat "(" title ")"))
17612 (if op (concat "{" op "}"))))
17613 (setq rtn (concat rtn " " s)))
17614 (org-trim rtn)))
17616 (defun org-columns-compile-format (fmt)
17617 "Turn a column format string into an alist of specifications.
17618 The alist has one entry for each column in the format. The elements of
17619 that list are:
17620 property the property
17621 title the title field for the columns
17622 width the column width in characters, can be nil for automatic
17623 operator the operator if any
17624 format the output format for computed results, derived from operator
17625 printf a printf format for computed values"
17626 (let ((start 0) width prop title op f printf)
17627 (setq org-columns-current-fmt-compiled nil)
17628 (while (string-match
17629 (org-re "%\\([0-9]+\\)?\\([[:alnum:]_-]+\\)\\(?:(\\([^)]+\\))\\)?\\(?:{\\([^}]+\\)}\\)?\\s-*")
17630 fmt start)
17631 (setq start (match-end 0)
17632 width (match-string 1 fmt)
17633 prop (match-string 2 fmt)
17634 title (or (match-string 3 fmt) prop)
17635 op (match-string 4 fmt)
17636 f nil
17637 printf nil)
17638 (if width (setq width (string-to-number width)))
17639 (when (and op (string-match ";" op))
17640 (setq printf (substring op (match-end 0))
17641 op (substring op 0 (match-beginning 0))))
17642 (cond
17643 ((equal op "+") (setq f 'add_numbers))
17644 ((equal op "$") (setq f 'currency))
17645 ((equal op ":") (setq f 'add_times))
17646 ((equal op "X") (setq f 'checkbox))
17647 ((equal op "X/") (setq f 'checkbox-n-of-m))
17648 ((equal op "X%") (setq f 'checkbox-percent))
17650 (push (list prop title width op f printf) org-columns-current-fmt-compiled))
17651 (setq org-columns-current-fmt-compiled
17652 (nreverse org-columns-current-fmt-compiled))))
17655 ;;; Dynamic block for Column view
17657 (defun org-columns-capture-view (&optional maxlevel skip-empty-rows)
17658 "Get the column view of the current buffer or subtree.
17659 The first optional argument MAXLEVEL sets the level limit. A
17660 second optional argument SKIP-EMPTY-ROWS tells whether to skip
17661 empty rows, an empty row being one where all the column view
17662 specifiers except ITEM are empty. This function returns a list
17663 containing the title row and all other rows. Each row is a list
17664 of fields."
17665 (save-excursion
17666 (let* ((title (mapcar 'cadr org-columns-current-fmt-compiled))
17667 (n (length title)) row tbl)
17668 (goto-char (point-min))
17669 (while (and (re-search-forward "^\\(\\*+\\) " nil t)
17670 (or (null maxlevel)
17671 (>= maxlevel
17672 (if org-odd-levels-only
17673 (/ (1+ (length (match-string 1))) 2)
17674 (length (match-string 1))))))
17675 (when (get-char-property (match-beginning 0) 'org-columns-key)
17676 (setq row nil)
17677 (loop for i from 0 to (1- n) do
17678 (push (or (get-char-property (+ (match-beginning 0) i) 'org-columns-value-modified)
17679 (get-char-property (+ (match-beginning 0) i) 'org-columns-value)
17681 row))
17682 (setq row (nreverse row))
17683 (unless (and skip-empty-rows
17684 (eq 1 (length (delete "" (delete-dups row)))))
17685 (push row tbl))))
17686 (append (list title 'hline) (nreverse tbl)))))
17688 (defun org-dblock-write:columnview (params)
17689 "Write the column view table.
17690 PARAMS is a property list of parameters:
17692 :width enforce same column widths with <N> specifiers.
17693 :id the :ID: property of the entry where the columns view
17694 should be built, as a string. When `local', call locally.
17695 When `global' call column view with the cursor at the beginning
17696 of the buffer (usually this means that the whole buffer switches
17697 to column view).
17698 :hlines When t, insert a hline before each item. When a number, insert
17699 a hline before each level <= that number.
17700 :vlines When t, make each column a colgroup to enforce vertical lines.
17701 :maxlevel When set to a number, don't capture headlines below this level.
17702 :skip-empty-rows
17703 When t, skip rows where all specifiers other than ITEM are empty."
17704 (let ((pos (move-marker (make-marker) (point)))
17705 (hlines (plist-get params :hlines))
17706 (vlines (plist-get params :vlines))
17707 (maxlevel (plist-get params :maxlevel))
17708 (skip-empty-rows (plist-get params :skip-empty-rows))
17709 tbl id idpos nfields tmp)
17710 (save-excursion
17711 (save-restriction
17712 (when (setq id (plist-get params :id))
17713 (cond ((not id) nil)
17714 ((eq id 'global) (goto-char (point-min)))
17715 ((eq id 'local) nil)
17716 ((setq idpos (org-find-entry-with-id id))
17717 (goto-char idpos))
17718 (t (error "Cannot find entry with :ID: %s" id))))
17719 (org-columns)
17720 (setq tbl (org-columns-capture-view maxlevel skip-empty-rows))
17721 (setq nfields (length (car tbl)))
17722 (org-columns-quit)))
17723 (goto-char pos)
17724 (move-marker pos nil)
17725 (when tbl
17726 (when (plist-get params :hlines)
17727 (setq tmp nil)
17728 (while tbl
17729 (if (eq (car tbl) 'hline)
17730 (push (pop tbl) tmp)
17731 (if (string-match "\\` *\\(\\*+\\)" (caar tbl))
17732 (if (and (not (eq (car tmp) 'hline))
17733 (or (eq hlines t)
17734 (and (numberp hlines) (<= (- (match-end 1) (match-beginning 1)) hlines))))
17735 (push 'hline tmp)))
17736 (push (pop tbl) tmp)))
17737 (setq tbl (nreverse tmp)))
17738 (when vlines
17739 (setq tbl (mapcar (lambda (x)
17740 (if (eq 'hline x) x (cons "" x)))
17741 tbl))
17742 (setq tbl (append tbl (list (cons "/" (make-list nfields "<>"))))))
17743 (setq pos (point))
17744 (insert (org-listtable-to-string tbl))
17745 (when (plist-get params :width)
17746 (insert "\n|" (mapconcat (lambda (x) (format "<%d>" (max 3 x)))
17747 org-columns-current-widths "|")))
17748 (goto-char pos)
17749 (org-table-align))))
17751 (defun org-listtable-to-string (tbl)
17752 "Convert a listtable TBL to a string that contains the Org-mode table.
17753 The table still need to be alligned. The resulting string has no leading
17754 and tailing newline characters."
17755 (mapconcat
17756 (lambda (x)
17757 (cond
17758 ((listp x)
17759 (concat "|" (mapconcat 'identity x "|") "|"))
17760 ((eq x 'hline) "|-|")
17761 (t (error "Garbage in listtable: %s" x))))
17762 tbl "\n"))
17764 (defun org-insert-columns-dblock ()
17765 "Create a dynamic block capturing a column view table."
17766 (interactive)
17767 (let ((defaults '(:name "columnview" :hlines 1))
17768 (id (completing-read
17769 "Capture columns (local, global, entry with :ID: property) [local]: "
17770 (append '(("global") ("local"))
17771 (mapcar 'list (org-property-values "ID"))))))
17772 (if (equal id "") (setq id 'local))
17773 (if (equal id "global") (setq id 'global))
17774 (setq defaults (append defaults (list :id id)))
17775 (org-create-dblock defaults)
17776 (org-update-dblock)))
17778 ;;;; Timestamps
17780 (defvar org-last-changed-timestamp nil)
17781 (defvar org-time-was-given) ; dynamically scoped parameter
17782 (defvar org-end-time-was-given) ; dynamically scoped parameter
17783 (defvar org-ts-what) ; dynamically scoped parameter
17785 (defun org-time-stamp (arg)
17786 "Prompt for a date/time and insert a time stamp.
17787 If the user specifies a time like HH:MM, or if this command is called
17788 with a prefix argument, the time stamp will contain date and time.
17789 Otherwise, only the date will be included. All parts of a date not
17790 specified by the user will be filled in from the current date/time.
17791 So if you press just return without typing anything, the time stamp
17792 will represent the current date/time. If there is already a timestamp
17793 at the cursor, it will be modified."
17794 (interactive "P")
17795 (let* ((ts nil)
17796 (default-time
17797 ;; Default time is either today, or, when entering a range,
17798 ;; the range start.
17799 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
17800 (save-excursion
17801 (re-search-backward
17802 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
17803 (- (point) 20) t)))
17804 (apply 'encode-time (org-parse-time-string (match-string 1)))
17805 (current-time)))
17806 (default-input (and ts (org-get-compact-tod ts)))
17807 org-time-was-given org-end-time-was-given time)
17808 (cond
17809 ((and (org-at-timestamp-p)
17810 (eq last-command 'org-time-stamp)
17811 (eq this-command 'org-time-stamp))
17812 (insert "--")
17813 (setq time (let ((this-command this-command))
17814 (org-read-date arg 'totime nil nil default-time default-input)))
17815 (org-insert-time-stamp time (or org-time-was-given arg)))
17816 ((org-at-timestamp-p)
17817 (setq time (let ((this-command this-command))
17818 (org-read-date arg 'totime nil nil default-time default-input)))
17819 (when (org-at-timestamp-p) ; just to get the match data
17820 (replace-match "")
17821 (setq org-last-changed-timestamp
17822 (org-insert-time-stamp
17823 time (or org-time-was-given arg)
17824 nil nil nil (list org-end-time-was-given))))
17825 (message "Timestamp updated"))
17827 (setq time (let ((this-command this-command))
17828 (org-read-date arg 'totime nil nil default-time default-input)))
17829 (org-insert-time-stamp time (or org-time-was-given arg)
17830 nil nil nil (list org-end-time-was-given))))))
17832 ;; FIXME: can we use this for something else????
17833 ;; like computing time differences?????
17834 (defun org-get-compact-tod (s)
17835 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
17836 (let* ((t1 (match-string 1 s))
17837 (h1 (string-to-number (match-string 2 s)))
17838 (m1 (string-to-number (match-string 3 s)))
17839 (t2 (and (match-end 4) (match-string 5 s)))
17840 (h2 (and t2 (string-to-number (match-string 6 s))))
17841 (m2 (and t2 (string-to-number (match-string 7 s))))
17842 dh dm)
17843 (if (not t2)
17845 (setq dh (- h2 h1) dm (- m2 m1))
17846 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
17847 (concat t1 "+" (number-to-string dh)
17848 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
17850 (defun org-time-stamp-inactive (&optional arg)
17851 "Insert an inactive time stamp.
17852 An inactive time stamp is enclosed in square brackets instead of angle
17853 brackets. It is inactive in the sense that it does not trigger agenda entries,
17854 does not link to the calendar and cannot be changed with the S-cursor keys.
17855 So these are more for recording a certain time/date."
17856 (interactive "P")
17857 (let (org-time-was-given org-end-time-was-given time)
17858 (setq time (org-read-date arg 'totime))
17859 (org-insert-time-stamp time (or org-time-was-given arg) 'inactive
17860 nil nil (list org-end-time-was-given))))
17862 (defvar org-date-ovl (org-make-overlay 1 1))
17863 (org-overlay-put org-date-ovl 'face 'org-warning)
17864 (org-detach-overlay org-date-ovl)
17866 (defvar org-ans1) ; dynamically scoped parameter
17867 (defvar org-ans2) ; dynamically scoped parameter
17869 (defvar org-plain-time-of-day-regexp) ; defined below
17871 (defvar org-read-date-overlay nil)
17872 (defvar org-dcst nil) ; dynamically scoped
17874 (defun org-read-date (&optional with-time to-time from-string prompt
17875 default-time default-input)
17876 "Read a date, possibly a time, and make things smooth for the user.
17877 The prompt will suggest to enter an ISO date, but you can also enter anything
17878 which will at least partially be understood by `parse-time-string'.
17879 Unrecognized parts of the date will default to the current day, month, year,
17880 hour and minute. If this command is called to replace a timestamp at point,
17881 of to enter the second timestamp of a range, the default time is taken from the
17882 existing stamp. For example,
17883 3-2-5 --> 2003-02-05
17884 feb 15 --> currentyear-02-15
17885 sep 12 9 --> 2009-09-12
17886 12:45 --> today 12:45
17887 22 sept 0:34 --> currentyear-09-22 0:34
17888 12 --> currentyear-currentmonth-12
17889 Fri --> nearest Friday (today or later)
17890 etc.
17892 Furthermore you can specify a relative date by giving, as the *first* thing
17893 in the input: a plus/minus sign, a number and a letter [dwmy] to indicate
17894 change in days weeks, months, years.
17895 With a single plus or minus, the date is relative to today. With a double
17896 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
17897 +4d --> four days from today
17898 +4 --> same as above
17899 +2w --> two weeks from today
17900 ++5 --> five days from default date
17902 The function understands only English month and weekday abbreviations,
17903 but this can be configured with the variables `parse-time-months' and
17904 `parse-time-weekdays'.
17906 While prompting, a calendar is popped up - you can also select the
17907 date with the mouse (button 1). The calendar shows a period of three
17908 months. To scroll it to other months, use the keys `>' and `<'.
17909 If you don't like the calendar, turn it off with
17910 \(setq org-read-date-popup-calendar nil)
17912 With optional argument TO-TIME, the date will immediately be converted
17913 to an internal time.
17914 With an optional argument WITH-TIME, the prompt will suggest to also
17915 insert a time. Note that when WITH-TIME is not set, you can still
17916 enter a time, and this function will inform the calling routine about
17917 this change. The calling routine may then choose to change the format
17918 used to insert the time stamp into the buffer to include the time.
17919 With optional argument FROM-STRING, read from this string instead from
17920 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
17921 the time/date that is used for everything that is not specified by the
17922 user."
17923 (require 'parse-time)
17924 (let* ((org-time-stamp-rounding-minutes
17925 (if (equal with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
17926 (org-dcst org-display-custom-times)
17927 (ct (org-current-time))
17928 (def (or default-time ct))
17929 (defdecode (decode-time def))
17930 (dummy (progn
17931 (when (< (nth 2 defdecode) org-extend-today-until)
17932 (setcar (nthcdr 2 defdecode) -1)
17933 (setcar (nthcdr 1 defdecode) 59)
17934 (setq def (apply 'encode-time defdecode)
17935 defdecode (decode-time def)))))
17936 (calendar-move-hook nil)
17937 (view-diary-entries-initially nil)
17938 (view-calendar-holidays-initially nil)
17939 (timestr (format-time-string
17940 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") def))
17941 (prompt (concat (if prompt (concat prompt " ") "")
17942 (format "Date+time [%s]: " timestr)))
17943 ans (org-ans0 "") org-ans1 org-ans2 final)
17945 (cond
17946 (from-string (setq ans from-string))
17947 (org-read-date-popup-calendar
17948 (save-excursion
17949 (save-window-excursion
17950 (calendar)
17951 (calendar-forward-day (- (time-to-days def)
17952 (calendar-absolute-from-gregorian
17953 (calendar-current-date))))
17954 (org-eval-in-calendar nil t)
17955 (let* ((old-map (current-local-map))
17956 (map (copy-keymap calendar-mode-map))
17957 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
17958 (org-defkey map (kbd "RET") 'org-calendar-select)
17959 (org-defkey map (if (featurep 'xemacs) [button1] [mouse-1])
17960 'org-calendar-select-mouse)
17961 (org-defkey map (if (featurep 'xemacs) [button2] [mouse-2])
17962 'org-calendar-select-mouse)
17963 (org-defkey minibuffer-local-map [(meta shift left)]
17964 (lambda () (interactive)
17965 (org-eval-in-calendar '(calendar-backward-month 1))))
17966 (org-defkey minibuffer-local-map [(meta shift right)]
17967 (lambda () (interactive)
17968 (org-eval-in-calendar '(calendar-forward-month 1))))
17969 (org-defkey minibuffer-local-map [(meta shift up)]
17970 (lambda () (interactive)
17971 (org-eval-in-calendar '(calendar-backward-year 1))))
17972 (org-defkey minibuffer-local-map [(meta shift down)]
17973 (lambda () (interactive)
17974 (org-eval-in-calendar '(calendar-forward-year 1))))
17975 (org-defkey minibuffer-local-map [(shift up)]
17976 (lambda () (interactive)
17977 (org-eval-in-calendar '(calendar-backward-week 1))))
17978 (org-defkey minibuffer-local-map [(shift down)]
17979 (lambda () (interactive)
17980 (org-eval-in-calendar '(calendar-forward-week 1))))
17981 (org-defkey minibuffer-local-map [(shift left)]
17982 (lambda () (interactive)
17983 (org-eval-in-calendar '(calendar-backward-day 1))))
17984 (org-defkey minibuffer-local-map [(shift right)]
17985 (lambda () (interactive)
17986 (org-eval-in-calendar '(calendar-forward-day 1))))
17987 (org-defkey minibuffer-local-map ">"
17988 (lambda () (interactive)
17989 (org-eval-in-calendar '(scroll-calendar-left 1))))
17990 (org-defkey minibuffer-local-map "<"
17991 (lambda () (interactive)
17992 (org-eval-in-calendar '(scroll-calendar-right 1))))
17993 (unwind-protect
17994 (progn
17995 (use-local-map map)
17996 (add-hook 'post-command-hook 'org-read-date-display)
17997 (setq org-ans0 (read-string prompt default-input nil nil))
17998 ;; org-ans0: from prompt
17999 ;; org-ans1: from mouse click
18000 ;; org-ans2: from calendar motion
18001 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
18002 (remove-hook 'post-command-hook 'org-read-date-display)
18003 (use-local-map old-map)
18004 (when org-read-date-overlay
18005 (org-delete-overlay org-read-date-overlay)
18006 (setq org-read-date-overlay nil)))))))
18008 (t ; Naked prompt only
18009 (unwind-protect
18010 (setq ans (read-string prompt default-input nil timestr))
18011 (when org-read-date-overlay
18012 (org-delete-overlay org-read-date-overlay)
18013 (setq org-read-date-overlay nil)))))
18015 (setq final (org-read-date-analyze ans def defdecode))
18017 (if to-time
18018 (apply 'encode-time final)
18019 (if (and (boundp 'org-time-was-given) org-time-was-given)
18020 (format "%04d-%02d-%02d %02d:%02d"
18021 (nth 5 final) (nth 4 final) (nth 3 final)
18022 (nth 2 final) (nth 1 final))
18023 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
18024 (defvar def)
18025 (defvar defdecode)
18026 (defvar with-time)
18027 (defun org-read-date-display ()
18028 "Display the currrent date prompt interpretation in the minibuffer."
18029 (when org-read-date-display-live
18030 (when org-read-date-overlay
18031 (org-delete-overlay org-read-date-overlay))
18032 (let ((p (point)))
18033 (end-of-line 1)
18034 (while (not (equal (buffer-substring
18035 (max (point-min) (- (point) 4)) (point))
18036 " "))
18037 (insert " "))
18038 (goto-char p))
18039 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
18040 " " (or org-ans1 org-ans2)))
18041 (org-end-time-was-given nil)
18042 (f (org-read-date-analyze ans def defdecode))
18043 (fmts (if org-dcst
18044 org-time-stamp-custom-formats
18045 org-time-stamp-formats))
18046 (fmt (if (or with-time
18047 (and (boundp 'org-time-was-given) org-time-was-given))
18048 (cdr fmts)
18049 (car fmts)))
18050 (txt (concat "=> " (format-time-string fmt (apply 'encode-time f)))))
18051 (when (and org-end-time-was-given
18052 (string-match org-plain-time-of-day-regexp txt))
18053 (setq txt (concat (substring txt 0 (match-end 0)) "-"
18054 org-end-time-was-given
18055 (substring txt (match-end 0)))))
18056 (setq org-read-date-overlay
18057 (make-overlay (1- (point-at-eol)) (point-at-eol)))
18058 (org-overlay-display org-read-date-overlay txt 'secondary-selection))))
18060 (defun org-read-date-analyze (ans def defdecode)
18061 "Analyze the combined answer of the date prompt."
18062 ;; FIXME: cleanup and comment
18063 (let (delta deltan deltaw deltadef year month day
18064 hour minute second wday pm h2 m2 tl wday1)
18066 (when (setq delta (org-read-date-get-relative ans (current-time) def))
18067 (setq ans (replace-match "" t t ans)
18068 deltan (car delta)
18069 deltaw (nth 1 delta)
18070 deltadef (nth 2 delta)))
18072 ;; Help matching ISO dates with single digit month ot day, like 2006-8-11.
18073 (when (string-match
18074 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
18075 (setq year (if (match-end 2)
18076 (string-to-number (match-string 2 ans))
18077 (string-to-number (format-time-string "%Y")))
18078 month (string-to-number (match-string 3 ans))
18079 day (string-to-number (match-string 4 ans)))
18080 (if (< year 100) (setq year (+ 2000 year)))
18081 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
18082 t nil ans)))
18083 ;; Help matching am/pm times, because `parse-time-string' does not do that.
18084 ;; If there is a time with am/pm, and *no* time without it, we convert
18085 ;; so that matching will be successful.
18086 (loop for i from 1 to 2 do ; twice, for end time as well
18087 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
18088 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
18089 (setq hour (string-to-number (match-string 1 ans))
18090 minute (if (match-end 3)
18091 (string-to-number (match-string 3 ans))
18093 pm (equal ?p
18094 (string-to-char (downcase (match-string 4 ans)))))
18095 (if (and (= hour 12) (not pm))
18096 (setq hour 0)
18097 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
18098 (setq ans (replace-match (format "%02d:%02d" hour minute)
18099 t t ans))))
18101 ;; Check if a time range is given as a duration
18102 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
18103 (setq hour (string-to-number (match-string 1 ans))
18104 h2 (+ hour (string-to-number (match-string 3 ans)))
18105 minute (string-to-number (match-string 2 ans))
18106 m2 (+ minute (if (match-end 5) (string-to-number (match-string 5 ans))0)))
18107 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
18108 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2) t t ans)))
18110 ;; Check if there is a time range
18111 (when (boundp 'org-end-time-was-given)
18112 (setq org-time-was-given nil)
18113 (when (and (string-match org-plain-time-of-day-regexp ans)
18114 (match-end 8))
18115 (setq org-end-time-was-given (match-string 8 ans))
18116 (setq ans (concat (substring ans 0 (match-beginning 7))
18117 (substring ans (match-end 7))))))
18119 (setq tl (parse-time-string ans)
18120 day (or (nth 3 tl) (nth 3 defdecode))
18121 month (or (nth 4 tl)
18122 (if (and org-read-date-prefer-future
18123 (nth 3 tl) (< (nth 3 tl) (nth 3 defdecode)))
18124 (1+ (nth 4 defdecode))
18125 (nth 4 defdecode)))
18126 year (or (nth 5 tl)
18127 (if (and org-read-date-prefer-future
18128 (nth 4 tl) (< (nth 4 tl) (nth 4 defdecode)))
18129 (1+ (nth 5 defdecode))
18130 (nth 5 defdecode)))
18131 hour (or (nth 2 tl) (nth 2 defdecode))
18132 minute (or (nth 1 tl) (nth 1 defdecode))
18133 second (or (nth 0 tl) 0)
18134 wday (nth 6 tl))
18135 (when deltan
18136 (unless deltadef
18137 (let ((now (decode-time (current-time))))
18138 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
18139 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
18140 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
18141 ((equal deltaw "m") (setq month (+ month deltan)))
18142 ((equal deltaw "y") (setq year (+ year deltan)))))
18143 (when (and wday (not (nth 3 tl)))
18144 ;; Weekday was given, but no day, so pick that day in the week
18145 ;; on or after the derived date.
18146 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
18147 (unless (equal wday wday1)
18148 (setq day (+ day (% (- wday wday1 -7) 7)))))
18149 (if (and (boundp 'org-time-was-given)
18150 (nth 2 tl))
18151 (setq org-time-was-given t))
18152 (if (< year 100) (setq year (+ 2000 year)))
18153 (if (< year 1970) (setq year (nth 5 defdecode))) ; not representable
18154 (list second minute hour day month year)))
18156 (defvar parse-time-weekdays)
18158 (defun org-read-date-get-relative (s today default)
18159 "Check string S for special relative date string.
18160 TODAY and DEFAULT are internal times, for today and for a default.
18161 Return shift list (N what def-flag)
18162 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
18163 N is the number of WHATs to shift.
18164 DEF-FLAG is t when a double ++ or -- indicates shift relative to
18165 the DEFAULT date rather than TODAY."
18166 (when (string-match
18167 (concat
18168 "\\`[ \t]*\\([-+]\\{1,2\\}\\)"
18169 "\\([0-9]+\\)?"
18170 "\\([dwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
18171 "\\([ \t]\\|$\\)") s)
18172 (let* ((dir (if (match-end 1)
18173 (string-to-char (substring (match-string 1 s) -1))
18174 ?+))
18175 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
18176 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
18177 (what (if (match-end 3) (match-string 3 s) "d"))
18178 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
18179 (date (if rel default today))
18180 (wday (nth 6 (decode-time date)))
18181 delta)
18182 (if wday1
18183 (progn
18184 (setq delta (mod (+ 7 (- wday1 wday)) 7))
18185 (if (= dir ?-) (setq delta (- delta 7)))
18186 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
18187 (list delta "d" rel))
18188 (list (* n (if (= dir ?-) -1 1)) what rel)))))
18190 (defun org-eval-in-calendar (form &optional keepdate)
18191 "Eval FORM in the calendar window and return to current window.
18192 Also, store the cursor date in variable org-ans2."
18193 (let ((sw (selected-window)))
18194 (select-window (get-buffer-window "*Calendar*"))
18195 (eval form)
18196 (when (and (not keepdate) (calendar-cursor-to-date))
18197 (let* ((date (calendar-cursor-to-date))
18198 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
18199 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
18200 (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
18201 (select-window sw)))
18203 ; ;; Update the prompt to show new default date
18204 ; (save-excursion
18205 ; (goto-char (point-min))
18206 ; (when (and org-ans2
18207 ; (re-search-forward "\\[[-0-9]+\\]" nil t)
18208 ; (get-text-property (match-end 0) 'field))
18209 ; (let ((inhibit-read-only t))
18210 ; (replace-match (concat "[" org-ans2 "]") t t)
18211 ; (add-text-properties (point-min) (1+ (match-end 0))
18212 ; (text-properties-at (1+ (point-min)))))))))
18214 (defun org-calendar-select ()
18215 "Return to `org-read-date' with the date currently selected.
18216 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
18217 (interactive)
18218 (when (calendar-cursor-to-date)
18219 (let* ((date (calendar-cursor-to-date))
18220 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
18221 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
18222 (if (active-minibuffer-window) (exit-minibuffer))))
18224 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
18225 "Insert a date stamp for the date given by the internal TIME.
18226 WITH-HM means, use the stamp format that includes the time of the day.
18227 INACTIVE means use square brackets instead of angular ones, so that the
18228 stamp will not contribute to the agenda.
18229 PRE and POST are optional strings to be inserted before and after the
18230 stamp.
18231 The command returns the inserted time stamp."
18232 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
18233 stamp)
18234 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
18235 (insert-before-markers (or pre ""))
18236 (insert-before-markers (setq stamp (format-time-string fmt time)))
18237 (when (listp extra)
18238 (setq extra (car extra))
18239 (if (and (stringp extra)
18240 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
18241 (setq extra (format "-%02d:%02d"
18242 (string-to-number (match-string 1 extra))
18243 (string-to-number (match-string 2 extra))))
18244 (setq extra nil)))
18245 (when extra
18246 (backward-char 1)
18247 (insert-before-markers extra)
18248 (forward-char 1))
18249 (insert-before-markers (or post ""))
18250 stamp))
18252 (defun org-toggle-time-stamp-overlays ()
18253 "Toggle the use of custom time stamp formats."
18254 (interactive)
18255 (setq org-display-custom-times (not org-display-custom-times))
18256 (unless org-display-custom-times
18257 (let ((p (point-min)) (bmp (buffer-modified-p)))
18258 (while (setq p (next-single-property-change p 'display))
18259 (if (and (get-text-property p 'display)
18260 (eq (get-text-property p 'face) 'org-date))
18261 (remove-text-properties
18262 p (setq p (next-single-property-change p 'display))
18263 '(display t))))
18264 (set-buffer-modified-p bmp)))
18265 (if (featurep 'xemacs)
18266 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
18267 (org-restart-font-lock)
18268 (setq org-table-may-need-update t)
18269 (if org-display-custom-times
18270 (message "Time stamps are overlayed with custom format")
18271 (message "Time stamp overlays removed")))
18273 (defun org-display-custom-time (beg end)
18274 "Overlay modified time stamp format over timestamp between BED and END."
18275 (let* ((ts (buffer-substring beg end))
18276 t1 w1 with-hm tf time str w2 (off 0))
18277 (save-match-data
18278 (setq t1 (org-parse-time-string ts t))
18279 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[dwmy]\\)?\\'" ts)
18280 (setq off (- (match-end 0) (match-beginning 0)))))
18281 (setq end (- end off))
18282 (setq w1 (- end beg)
18283 with-hm (and (nth 1 t1) (nth 2 t1))
18284 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
18285 time (org-fix-decoded-time t1)
18286 str (org-add-props
18287 (format-time-string
18288 (substring tf 1 -1) (apply 'encode-time time))
18289 nil 'mouse-face 'highlight)
18290 w2 (length str))
18291 (if (not (= w2 w1))
18292 (add-text-properties (1+ beg) (+ 2 beg)
18293 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
18294 (if (featurep 'xemacs)
18295 (progn
18296 (put-text-property beg end 'invisible t)
18297 (put-text-property beg end 'end-glyph (make-glyph str)))
18298 (put-text-property beg end 'display str))))
18300 (defun org-translate-time (string)
18301 "Translate all timestamps in STRING to custom format.
18302 But do this only if the variable `org-display-custom-times' is set."
18303 (when org-display-custom-times
18304 (save-match-data
18305 (let* ((start 0)
18306 (re org-ts-regexp-both)
18307 t1 with-hm inactive tf time str beg end)
18308 (while (setq start (string-match re string start))
18309 (setq beg (match-beginning 0)
18310 end (match-end 0)
18311 t1 (save-match-data
18312 (org-parse-time-string (substring string beg end) t))
18313 with-hm (and (nth 1 t1) (nth 2 t1))
18314 inactive (equal (substring string beg (1+ beg)) "[")
18315 tf (funcall (if with-hm 'cdr 'car)
18316 org-time-stamp-custom-formats)
18317 time (org-fix-decoded-time t1)
18318 str (format-time-string
18319 (concat
18320 (if inactive "[" "<") (substring tf 1 -1)
18321 (if inactive "]" ">"))
18322 (apply 'encode-time time))
18323 string (replace-match str t t string)
18324 start (+ start (length str)))))))
18325 string)
18327 (defun org-fix-decoded-time (time)
18328 "Set 0 instead of nil for the first 6 elements of time.
18329 Don't touch the rest."
18330 (let ((n 0))
18331 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
18333 (defun org-days-to-time (timestamp-string)
18334 "Difference between TIMESTAMP-STRING and now in days."
18335 (- (time-to-days (org-time-string-to-time timestamp-string))
18336 (time-to-days (current-time))))
18338 (defun org-deadline-close (timestamp-string &optional ndays)
18339 "Is the time in TIMESTAMP-STRING close to the current date?"
18340 (setq ndays (or ndays (org-get-wdays timestamp-string)))
18341 (and (< (org-days-to-time timestamp-string) ndays)
18342 (not (org-entry-is-done-p))))
18344 (defun org-get-wdays (ts)
18345 "Get the deadline lead time appropriate for timestring TS."
18346 (cond
18347 ((<= org-deadline-warning-days 0)
18348 ;; 0 or negative, enforce this value no matter what
18349 (- org-deadline-warning-days))
18350 ((string-match "-\\([0-9]+\\)\\([dwmy]\\)\\(\\'\\|>\\)" ts)
18351 ;; lead time is specified.
18352 (floor (* (string-to-number (match-string 1 ts))
18353 (cdr (assoc (match-string 2 ts)
18354 '(("d" . 1) ("w" . 7)
18355 ("m" . 30.4) ("y" . 365.25)))))))
18356 ;; go for the default.
18357 (t org-deadline-warning-days)))
18359 (defun org-calendar-select-mouse (ev)
18360 "Return to `org-read-date' with the date currently selected.
18361 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
18362 (interactive "e")
18363 (mouse-set-point ev)
18364 (when (calendar-cursor-to-date)
18365 (let* ((date (calendar-cursor-to-date))
18366 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
18367 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
18368 (if (active-minibuffer-window) (exit-minibuffer))))
18370 (defun org-check-deadlines (ndays)
18371 "Check if there are any deadlines due or past due.
18372 A deadline is considered due if it happens within `org-deadline-warning-days'
18373 days from today's date. If the deadline appears in an entry marked DONE,
18374 it is not shown. The prefix arg NDAYS can be used to test that many
18375 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
18376 (interactive "P")
18377 (let* ((org-warn-days
18378 (cond
18379 ((equal ndays '(4)) 100000)
18380 (ndays (prefix-numeric-value ndays))
18381 (t (abs org-deadline-warning-days))))
18382 (case-fold-search nil)
18383 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
18384 (callback
18385 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
18387 (message "%d deadlines past-due or due within %d days"
18388 (org-occur regexp nil callback)
18389 org-warn-days)))
18391 (defun org-check-before-date (date)
18392 "Check if there are deadlines or scheduled entries before DATE."
18393 (interactive (list (org-read-date)))
18394 (let ((case-fold-search nil)
18395 (regexp (concat "\\<\\(" org-deadline-string
18396 "\\|" org-scheduled-string
18397 "\\) *<\\([^>]+\\)>"))
18398 (callback
18399 (lambda () (time-less-p
18400 (org-time-string-to-time (match-string 2))
18401 (org-time-string-to-time date)))))
18402 (message "%d entries before %s"
18403 (org-occur regexp nil callback) date)))
18405 (defun org-evaluate-time-range (&optional to-buffer)
18406 "Evaluate a time range by computing the difference between start and end.
18407 Normally the result is just printed in the echo area, but with prefix arg
18408 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
18409 If the time range is actually in a table, the result is inserted into the
18410 next column.
18411 For time difference computation, a year is assumed to be exactly 365
18412 days in order to avoid rounding problems."
18413 (interactive "P")
18415 (org-clock-update-time-maybe)
18416 (save-excursion
18417 (unless (org-at-date-range-p t)
18418 (goto-char (point-at-bol))
18419 (re-search-forward org-tr-regexp-both (point-at-eol) t))
18420 (if (not (org-at-date-range-p t))
18421 (error "Not at a time-stamp range, and none found in current line")))
18422 (let* ((ts1 (match-string 1))
18423 (ts2 (match-string 2))
18424 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
18425 (match-end (match-end 0))
18426 (time1 (org-time-string-to-time ts1))
18427 (time2 (org-time-string-to-time ts2))
18428 (t1 (time-to-seconds time1))
18429 (t2 (time-to-seconds time2))
18430 (diff (abs (- t2 t1)))
18431 (negative (< (- t2 t1) 0))
18432 ;; (ys (floor (* 365 24 60 60)))
18433 (ds (* 24 60 60))
18434 (hs (* 60 60))
18435 (fy "%dy %dd %02d:%02d")
18436 (fy1 "%dy %dd")
18437 (fd "%dd %02d:%02d")
18438 (fd1 "%dd")
18439 (fh "%02d:%02d")
18440 y d h m align)
18441 (if havetime
18442 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
18444 d (floor (/ diff ds)) diff (mod diff ds)
18445 h (floor (/ diff hs)) diff (mod diff hs)
18446 m (floor (/ diff 60)))
18447 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
18449 d (floor (+ (/ diff ds) 0.5))
18450 h 0 m 0))
18451 (if (not to-buffer)
18452 (message "%s" (org-make-tdiff-string y d h m))
18453 (if (org-at-table-p)
18454 (progn
18455 (goto-char match-end)
18456 (setq align t)
18457 (and (looking-at " *|") (goto-char (match-end 0))))
18458 (goto-char match-end))
18459 (if (looking-at
18460 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
18461 (replace-match ""))
18462 (if negative (insert " -"))
18463 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
18464 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
18465 (insert " " (format fh h m))))
18466 (if align (org-table-align))
18467 (message "Time difference inserted")))))
18469 (defun org-make-tdiff-string (y d h m)
18470 (let ((fmt "")
18471 (l nil))
18472 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
18473 l (push y l)))
18474 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
18475 l (push d l)))
18476 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
18477 l (push h l)))
18478 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
18479 l (push m l)))
18480 (apply 'format fmt (nreverse l))))
18482 (defun org-time-string-to-time (s)
18483 (apply 'encode-time (org-parse-time-string s)))
18485 (defun org-time-string-to-absolute (s &optional daynr prefer)
18486 "Convert a time stamp to an absolute day number.
18487 If there is a specifyer for a cyclic time stamp, get the closest date to
18488 DAYNR."
18489 (cond
18490 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
18491 (if (org-diary-sexp-entry (match-string 1 s) "" date)
18492 daynr
18493 (+ daynr 1000)))
18494 ((and daynr (string-match "\\+[0-9]+[dwmy]" s))
18495 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
18496 (time-to-days (current-time))) (match-string 0 s)
18497 prefer))
18498 (t (time-to-days (apply 'encode-time (org-parse-time-string s))))))
18500 (defun org-time-from-absolute (d)
18501 "Return the time corresponding to date D.
18502 D may be an absolute day number, or a calendar-type list (month day year)."
18503 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
18504 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
18506 (defun org-calendar-holiday ()
18507 "List of holidays, for Diary display in Org-mode."
18508 (require 'holidays)
18509 (let ((hl (funcall
18510 (if (fboundp 'calendar-check-holidays)
18511 'calendar-check-holidays 'check-calendar-holidays) date)))
18512 (if hl (mapconcat 'identity hl "; "))))
18514 (defun org-diary-sexp-entry (sexp entry date)
18515 "Process a SEXP diary ENTRY for DATE."
18516 (require 'diary-lib)
18517 (let ((result (if calendar-debug-sexp
18518 (let ((stack-trace-on-error t))
18519 (eval (car (read-from-string sexp))))
18520 (condition-case nil
18521 (eval (car (read-from-string sexp)))
18522 (error
18523 (beep)
18524 (message "Bad sexp at line %d in %s: %s"
18525 (org-current-line)
18526 (buffer-file-name) sexp)
18527 (sleep-for 2))))))
18528 (cond ((stringp result) result)
18529 ((and (consp result)
18530 (stringp (cdr result))) (cdr result))
18531 (result entry)
18532 (t nil))))
18534 (defun org-diary-to-ical-string (frombuf)
18535 "Get iCalendar entries from diary entries in buffer FROMBUF.
18536 This uses the icalendar.el library."
18537 (let* ((tmpdir (if (featurep 'xemacs)
18538 (temp-directory)
18539 temporary-file-directory))
18540 (tmpfile (make-temp-name
18541 (expand-file-name "orgics" tmpdir)))
18542 buf rtn b e)
18543 (save-excursion
18544 (set-buffer frombuf)
18545 (icalendar-export-region (point-min) (point-max) tmpfile)
18546 (setq buf (find-buffer-visiting tmpfile))
18547 (set-buffer buf)
18548 (goto-char (point-min))
18549 (if (re-search-forward "^BEGIN:VEVENT" nil t)
18550 (setq b (match-beginning 0)))
18551 (goto-char (point-max))
18552 (if (re-search-backward "^END:VEVENT" nil t)
18553 (setq e (match-end 0)))
18554 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
18555 (kill-buffer buf)
18556 (kill-buffer frombuf)
18557 (delete-file tmpfile)
18558 rtn))
18560 (defun org-closest-date (start current change prefer)
18561 "Find the date closest to CURRENT that is consistent with START and CHANGE.
18562 When PREFER is `past' return a date that is either CURRENT or past.
18563 When PREFER is `future', return a date that is either CURRENT or future."
18564 ;; Make the proper lists from the dates
18565 (catch 'exit
18566 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
18567 dn dw sday cday n1 n2
18568 d m y y1 y2 date1 date2 nmonths nm ny m2)
18570 (setq start (org-date-to-gregorian start)
18571 current (org-date-to-gregorian
18572 (if org-agenda-repeating-timestamp-show-all
18573 current
18574 (time-to-days (current-time))))
18575 sday (calendar-absolute-from-gregorian start)
18576 cday (calendar-absolute-from-gregorian current))
18578 (if (<= cday sday) (throw 'exit sday))
18580 (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
18581 (setq dn (string-to-number (match-string 1 change))
18582 dw (cdr (assoc (match-string 2 change) a1)))
18583 (error "Invalid change specifyer: %s" change))
18584 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
18585 (cond
18586 ((eq dw 'day)
18587 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
18588 n2 (+ n1 dn)))
18589 ((eq dw 'year)
18590 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
18591 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
18592 (setq date1 (list m d y1)
18593 n1 (calendar-absolute-from-gregorian date1)
18594 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
18595 n2 (calendar-absolute-from-gregorian date2)))
18596 ((eq dw 'month)
18597 ;; approx number of month between the tow dates
18598 (setq nmonths (floor (/ (- cday sday) 30.436875)))
18599 ;; How often does dn fit in there?
18600 (setq d (nth 1 start) m (car start) y (nth 2 start)
18601 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
18602 m (+ m nm)
18603 ny (floor (/ m 12))
18604 y (+ y ny)
18605 m (- m (* ny 12)))
18606 (while (> m 12) (setq m (- m 12) y (1+ y)))
18607 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
18608 (setq m2 (+ m dn) y2 y)
18609 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
18610 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
18611 (while (< n2 cday)
18612 (setq n1 n2 m m2 y y2)
18613 (setq m2 (+ m dn) y2 y)
18614 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
18615 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
18617 (if org-agenda-repeating-timestamp-show-all
18618 (cond
18619 ((eq prefer 'past) n1)
18620 ((eq prefer 'future) (if (= cday n1) n1 n2))
18621 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
18622 (cond
18623 ((eq prefer 'past) n1)
18624 ((eq prefer 'future) (if (= cday n1) n1 n2))
18625 (t (if (= cday n1) n1 n2)))))))
18627 (defun org-date-to-gregorian (date)
18628 "Turn any specification of DATE into a gregorian date for the calendar."
18629 (cond ((integerp date) (calendar-gregorian-from-absolute date))
18630 ((and (listp date) (= (length date) 3)) date)
18631 ((stringp date)
18632 (setq date (org-parse-time-string date))
18633 (list (nth 4 date) (nth 3 date) (nth 5 date)))
18634 ((listp date)
18635 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
18637 (defun org-parse-time-string (s &optional nodefault)
18638 "Parse the standard Org-mode time string.
18639 This should be a lot faster than the normal `parse-time-string'.
18640 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
18641 hour and minute fields will be nil if not given."
18642 (if (string-match org-ts-regexp0 s)
18643 (list 0
18644 (if (or (match-beginning 8) (not nodefault))
18645 (string-to-number (or (match-string 8 s) "0")))
18646 (if (or (match-beginning 7) (not nodefault))
18647 (string-to-number (or (match-string 7 s) "0")))
18648 (string-to-number (match-string 4 s))
18649 (string-to-number (match-string 3 s))
18650 (string-to-number (match-string 2 s))
18651 nil nil nil)
18652 (make-list 9 0)))
18654 (defun org-timestamp-up (&optional arg)
18655 "Increase the date item at the cursor by one.
18656 If the cursor is on the year, change the year. If it is on the month or
18657 the day, change that.
18658 With prefix ARG, change by that many units."
18659 (interactive "p")
18660 (org-timestamp-change (prefix-numeric-value arg)))
18662 (defun org-timestamp-down (&optional arg)
18663 "Decrease the date item at the cursor by one.
18664 If the cursor is on the year, change the year. If it is on the month or
18665 the day, change that.
18666 With prefix ARG, change by that many units."
18667 (interactive "p")
18668 (org-timestamp-change (- (prefix-numeric-value arg))))
18670 (defun org-timestamp-up-day (&optional arg)
18671 "Increase the date in the time stamp by one day.
18672 With prefix ARG, change that many days."
18673 (interactive "p")
18674 (if (and (not (org-at-timestamp-p t))
18675 (org-on-heading-p))
18676 (org-todo 'up)
18677 (org-timestamp-change (prefix-numeric-value arg) 'day)))
18679 (defun org-timestamp-down-day (&optional arg)
18680 "Decrease the date in the time stamp by one day.
18681 With prefix ARG, change that many days."
18682 (interactive "p")
18683 (if (and (not (org-at-timestamp-p t))
18684 (org-on-heading-p))
18685 (org-todo 'down)
18686 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
18688 (defsubst org-pos-in-match-range (pos n)
18689 (and (match-beginning n)
18690 (<= (match-beginning n) pos)
18691 (>= (match-end n) pos)))
18693 (defun org-at-timestamp-p (&optional inactive-ok)
18694 "Determine if the cursor is in or at a timestamp."
18695 (interactive)
18696 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
18697 (pos (point))
18698 (ans (or (looking-at tsr)
18699 (save-excursion
18700 (skip-chars-backward "^[<\n\r\t")
18701 (if (> (point) (point-min)) (backward-char 1))
18702 (and (looking-at tsr)
18703 (> (- (match-end 0) pos) -1))))))
18704 (and ans
18705 (boundp 'org-ts-what)
18706 (setq org-ts-what
18707 (cond
18708 ((= pos (match-beginning 0)) 'bracket)
18709 ((= pos (1- (match-end 0))) 'bracket)
18710 ((org-pos-in-match-range pos 2) 'year)
18711 ((org-pos-in-match-range pos 3) 'month)
18712 ((org-pos-in-match-range pos 7) 'hour)
18713 ((org-pos-in-match-range pos 8) 'minute)
18714 ((or (org-pos-in-match-range pos 4)
18715 (org-pos-in-match-range pos 5)) 'day)
18716 ((and (> pos (or (match-end 8) (match-end 5)))
18717 (< pos (match-end 0)))
18718 (- pos (or (match-end 8) (match-end 5))))
18719 (t 'day))))
18720 ans))
18722 (defun org-toggle-timestamp-type ()
18723 "Toggle the type (<active> or [inactive]) of a time stamp."
18724 (interactive)
18725 (when (org-at-timestamp-p t)
18726 (save-excursion
18727 (goto-char (match-beginning 0))
18728 (insert (if (equal (char-after) ?<) "[" "<")) (delete-char 1)
18729 (goto-char (1- (match-end 0)))
18730 (insert (if (equal (char-after) ?>) "]" ">")) (delete-char 1))
18731 (message "Timestamp is now %sactive"
18732 (if (equal (char-before) ?>) "in" ""))))
18734 (defun org-timestamp-change (n &optional what)
18735 "Change the date in the time stamp at point.
18736 The date will be changed by N times WHAT. WHAT can be `day', `month',
18737 `year', `minute', `second'. If WHAT is not given, the cursor position
18738 in the timestamp determines what will be changed."
18739 (let ((pos (point))
18740 with-hm inactive
18741 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
18742 org-ts-what
18743 extra rem
18744 ts time time0)
18745 (if (not (org-at-timestamp-p t))
18746 (error "Not at a timestamp"))
18747 (if (and (not what) (eq org-ts-what 'bracket))
18748 (org-toggle-timestamp-type)
18749 (if (and (not what) (not (eq org-ts-what 'day))
18750 org-display-custom-times
18751 (get-text-property (point) 'display)
18752 (not (get-text-property (1- (point)) 'display)))
18753 (setq org-ts-what 'day))
18754 (setq org-ts-what (or what org-ts-what)
18755 inactive (= (char-after (match-beginning 0)) ?\[)
18756 ts (match-string 0))
18757 (replace-match "")
18758 (if (string-match
18759 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[dwmy]\\)*\\)[]>]"
18761 (setq extra (match-string 1 ts)))
18762 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
18763 (setq with-hm t))
18764 (setq time0 (org-parse-time-string ts))
18765 (when (and (eq org-ts-what 'minute)
18766 (eq current-prefix-arg nil))
18767 (setq n (* dm (org-no-warnings (signum n))))
18768 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
18769 (setcar (cdr time0) (+ (nth 1 time0)
18770 (if (> n 0) (- rem) (- dm rem))))))
18771 (setq time
18772 (encode-time (or (car time0) 0)
18773 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
18774 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
18775 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
18776 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
18777 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
18778 (nthcdr 6 time0)))
18779 (when (integerp org-ts-what)
18780 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
18781 (if (eq what 'calendar)
18782 (let ((cal-date (org-get-date-from-calendar)))
18783 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
18784 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
18785 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
18786 (setcar time0 (or (car time0) 0))
18787 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
18788 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
18789 (setq time (apply 'encode-time time0))))
18790 (setq org-last-changed-timestamp
18791 (org-insert-time-stamp time with-hm inactive nil nil extra))
18792 (org-clock-update-time-maybe)
18793 (goto-char pos)
18794 ;; Try to recenter the calendar window, if any
18795 (if (and org-calendar-follow-timestamp-change
18796 (get-buffer-window "*Calendar*" t)
18797 (memq org-ts-what '(day month year)))
18798 (org-recenter-calendar (time-to-days time))))))
18800 ;; FIXME: does not yet work for lead times
18801 (defun org-modify-ts-extra (s pos n dm)
18802 "Change the different parts of the lead-time and repeat fields in timestamp."
18803 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
18804 ng h m new rem)
18805 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
18806 (cond
18807 ((or (org-pos-in-match-range pos 2)
18808 (org-pos-in-match-range pos 3))
18809 (setq m (string-to-number (match-string 3 s))
18810 h (string-to-number (match-string 2 s)))
18811 (if (org-pos-in-match-range pos 2)
18812 (setq h (+ h n))
18813 (setq n (* dm (org-no-warnings (signum n))))
18814 (when (not (= 0 (setq rem (% m dm))))
18815 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
18816 (setq m (+ m n)))
18817 (if (< m 0) (setq m (+ m 60) h (1- h)))
18818 (if (> m 59) (setq m (- m 60) h (1+ h)))
18819 (setq h (min 24 (max 0 h)))
18820 (setq ng 1 new (format "-%02d:%02d" h m)))
18821 ((org-pos-in-match-range pos 6)
18822 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
18823 ((org-pos-in-match-range pos 5)
18824 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
18826 ((org-pos-in-match-range pos 9)
18827 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
18828 ((org-pos-in-match-range pos 8)
18829 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
18831 (when ng
18832 (setq s (concat
18833 (substring s 0 (match-beginning ng))
18835 (substring s (match-end ng))))))
18838 (defun org-recenter-calendar (date)
18839 "If the calendar is visible, recenter it to DATE."
18840 (let* ((win (selected-window))
18841 (cwin (get-buffer-window "*Calendar*" t))
18842 (calendar-move-hook nil))
18843 (when cwin
18844 (select-window cwin)
18845 (calendar-goto-date (if (listp date) date
18846 (calendar-gregorian-from-absolute date)))
18847 (select-window win))))
18849 (defun org-goto-calendar (&optional arg)
18850 "Go to the Emacs calendar at the current date.
18851 If there is a time stamp in the current line, go to that date.
18852 A prefix ARG can be used to force the current date."
18853 (interactive "P")
18854 (let ((tsr org-ts-regexp) diff
18855 (calendar-move-hook nil)
18856 (view-calendar-holidays-initially nil)
18857 (view-diary-entries-initially nil))
18858 (if (or (org-at-timestamp-p)
18859 (save-excursion
18860 (beginning-of-line 1)
18861 (looking-at (concat ".*" tsr))))
18862 (let ((d1 (time-to-days (current-time)))
18863 (d2 (time-to-days
18864 (org-time-string-to-time (match-string 1)))))
18865 (setq diff (- d2 d1))))
18866 (calendar)
18867 (calendar-goto-today)
18868 (if (and diff (not arg)) (calendar-forward-day diff))))
18870 (defun org-get-date-from-calendar ()
18871 "Return a list (month day year) of date at point in calendar."
18872 (with-current-buffer "*Calendar*"
18873 (save-match-data
18874 (calendar-cursor-to-date))))
18876 (defun org-date-from-calendar ()
18877 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
18878 If there is already a time stamp at the cursor position, update it."
18879 (interactive)
18880 (if (org-at-timestamp-p t)
18881 (org-timestamp-change 0 'calendar)
18882 (let ((cal-date (org-get-date-from-calendar)))
18883 (org-insert-time-stamp
18884 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
18886 (defvar appt-time-msg-list)
18888 ;;;###autoload
18889 (defun org-agenda-to-appt (&optional refresh filter)
18890 "Activate appointments found in `org-agenda-files'.
18891 With a \\[universal-argument] prefix, refresh the list of
18892 appointements.
18894 If FILTER is t, interactively prompt the user for a regular
18895 expression, and filter out entries that don't match it.
18897 If FILTER is a string, use this string as a regular expression
18898 for filtering entries out.
18900 FILTER can also be an alist with the car of each cell being
18901 either 'headline or 'category. For example:
18903 '((headline \"IMPORTANT\")
18904 (category \"Work\"))
18906 will only add headlines containing IMPORTANT or headlines
18907 belonging to the \"Work\" category."
18908 (interactive "P")
18909 (require 'calendar)
18910 (if refresh (setq appt-time-msg-list nil))
18911 (if (eq filter t)
18912 (setq filter (read-from-minibuffer "Regexp filter: ")))
18913 (let* ((cnt 0) ; count added events
18914 (org-agenda-new-buffers nil)
18915 (org-deadline-warning-days 0)
18916 (today (org-date-to-gregorian
18917 (time-to-days (current-time))))
18918 (files (org-agenda-files)) entries file)
18919 ;; Get all entries which may contain an appt
18920 (while (setq file (pop files))
18921 (setq entries
18922 (append entries
18923 (org-agenda-get-day-entries
18924 file today :timestamp :scheduled :deadline))))
18925 (setq entries (delq nil entries))
18926 ;; Map thru entries and find if we should filter them out
18927 (mapc
18928 (lambda(x)
18929 (let* ((evt (org-trim (get-text-property 1 'txt x)))
18930 (cat (get-text-property 1 'org-category x))
18931 (tod (get-text-property 1 'time-of-day x))
18932 (ok (or (null filter)
18933 (and (stringp filter) (string-match filter evt))
18934 (and (listp filter)
18935 (or (string-match
18936 (cadr (assoc 'category filter)) cat)
18937 (string-match
18938 (cadr (assoc 'headline filter)) evt))))))
18939 ;; FIXME: Shall we remove text-properties for the appt text?
18940 ;; (setq evt (set-text-properties 0 (length evt) nil evt))
18941 (when (and ok tod)
18942 (setq tod (number-to-string tod)
18943 tod (when (string-match
18944 "\\([0-9]\\{1,2\\}\\)\\([0-9]\\{2\\}\\)" tod)
18945 (concat (match-string 1 tod) ":"
18946 (match-string 2 tod))))
18947 (appt-add tod evt)
18948 (setq cnt (1+ cnt))))) entries)
18949 (org-release-buffers org-agenda-new-buffers)
18950 (if (eq cnt 0)
18951 (message "No event to add")
18952 (message "Added %d event%s for today" cnt (if (> cnt 1) "s" "")))))
18954 ;;; The clock for measuring work time.
18956 (defvar org-mode-line-string "")
18957 (put 'org-mode-line-string 'risky-local-variable t)
18959 (defvar org-mode-line-timer nil)
18960 (defvar org-clock-heading "")
18961 (defvar org-clock-start-time "")
18963 (defun org-update-mode-line ()
18964 (let* ((delta (- (time-to-seconds (current-time))
18965 (time-to-seconds org-clock-start-time)))
18966 (h (floor delta 3600))
18967 (m (floor (- delta (* 3600 h)) 60)))
18968 (setq org-mode-line-string
18969 (propertize (format "-[%d:%02d (%s)]" h m org-clock-heading)
18970 'help-echo "Org-mode clock is running"))
18971 (force-mode-line-update)))
18973 (defvar org-clock-marker (make-marker)
18974 "Marker recording the last clock-in.")
18975 (defvar org-clock-mode-line-entry nil
18976 "Information for the modeline about the running clock.")
18978 (defun org-clock-in ()
18979 "Start the clock on the current item.
18980 If necessary, clock-out of the currently active clock."
18981 (interactive)
18982 (org-clock-out t)
18983 (let (ts)
18984 (save-excursion
18985 (org-back-to-heading t)
18986 (when (and org-clock-in-switch-to-state
18987 (not (looking-at (concat outline-regexp "[ \t]*"
18988 org-clock-in-switch-to-state
18989 "\\>"))))
18990 (org-todo org-clock-in-switch-to-state))
18991 (if (and org-clock-heading-function
18992 (functionp org-clock-heading-function))
18993 (setq org-clock-heading (funcall org-clock-heading-function))
18994 (if (looking-at org-complex-heading-regexp)
18995 (setq org-clock-heading (match-string 4))
18996 (setq org-clock-heading "???")))
18997 (setq org-clock-heading (propertize org-clock-heading 'face nil))
18998 (org-clock-find-position)
19000 (insert "\n") (backward-char 1)
19001 (indent-relative)
19002 (insert org-clock-string " ")
19003 (setq org-clock-start-time (current-time))
19004 (setq ts (org-insert-time-stamp (current-time) 'with-hm 'inactive))
19005 (move-marker org-clock-marker (point) (buffer-base-buffer))
19006 (or global-mode-string (setq global-mode-string '("")))
19007 (or (memq 'org-mode-line-string global-mode-string)
19008 (setq global-mode-string
19009 (append global-mode-string '(org-mode-line-string))))
19010 (org-update-mode-line)
19011 (setq org-mode-line-timer (run-with-timer 60 60 'org-update-mode-line))
19012 (message "Clock started at %s" ts))))
19014 (defun org-clock-find-position ()
19015 "Find the location where the next clock line should be inserted."
19016 (org-back-to-heading t)
19017 (catch 'exit
19018 (let ((beg (point-at-bol 2)) (end (progn (outline-next-heading) (point)))
19019 (re (concat "^[ \t]*" org-clock-string))
19020 (cnt 0)
19021 first last)
19022 (goto-char beg)
19023 (when (eobp) (newline) (setq end (max (point) end)))
19024 (when (re-search-forward "^[ \t]*:CLOCK:" end t)
19025 ;; we seem to have a CLOCK drawer, so go there.
19026 (beginning-of-line 2)
19027 (throw 'exit t))
19028 ;; Lets count the CLOCK lines
19029 (goto-char beg)
19030 (while (re-search-forward re end t)
19031 (setq first (or first (match-beginning 0))
19032 last (match-beginning 0)
19033 cnt (1+ cnt)))
19034 (when (and (integerp org-clock-into-drawer)
19035 (>= (1+ cnt) org-clock-into-drawer))
19036 ;; Wrap current entries into a new drawer
19037 (goto-char last)
19038 (beginning-of-line 2)
19039 (if (org-at-item-p) (org-end-of-item))
19040 (insert ":END:\n")
19041 (beginning-of-line 0)
19042 (org-indent-line-function)
19043 (goto-char first)
19044 (insert ":CLOCK:\n")
19045 (beginning-of-line 0)
19046 (org-indent-line-function)
19047 (org-flag-drawer t)
19048 (beginning-of-line 2)
19049 (throw 'exit nil))
19051 (goto-char beg)
19052 (while (and (looking-at (concat "[ \t]*" org-keyword-time-regexp))
19053 (not (equal (match-string 1) org-clock-string)))
19054 ;; Planning info, skip to after it
19055 (beginning-of-line 2)
19056 (or (bolp) (newline)))
19057 (when (eq t org-clock-into-drawer)
19058 (insert ":CLOCK:\n:END:\n")
19059 (beginning-of-line -1)
19060 (org-indent-line-function)
19061 (org-flag-drawer t)
19062 (beginning-of-line 2)
19063 (org-indent-line-function)))))
19065 (defun org-clock-out (&optional fail-quietly)
19066 "Stop the currently running clock.
19067 If there is no running clock, throw an error, unless FAIL-QUIETLY is set."
19068 (interactive)
19069 (catch 'exit
19070 (if (not (marker-buffer org-clock-marker))
19071 (if fail-quietly (throw 'exit t) (error "No active clock")))
19072 (let (ts te s h m)
19073 (save-excursion
19074 (set-buffer (marker-buffer org-clock-marker))
19075 (goto-char org-clock-marker)
19076 (beginning-of-line 1)
19077 (if (and (looking-at (concat "[ \t]*" org-keyword-time-regexp))
19078 (equal (match-string 1) org-clock-string))
19079 (setq ts (match-string 2))
19080 (if fail-quietly (throw 'exit nil) (error "Clock start time is gone")))
19081 (goto-char (match-end 0))
19082 (delete-region (point) (point-at-eol))
19083 (insert "--")
19084 (setq te (org-insert-time-stamp (current-time) 'with-hm 'inactive))
19085 (setq s (- (time-to-seconds (apply 'encode-time (org-parse-time-string te)))
19086 (time-to-seconds (apply 'encode-time (org-parse-time-string ts))))
19087 h (floor (/ s 3600))
19088 s (- s (* 3600 h))
19089 m (floor (/ s 60))
19090 s (- s (* 60 s)))
19091 (insert " => " (format "%2d:%02d" h m))
19092 (move-marker org-clock-marker nil)
19093 (when org-log-note-clock-out
19094 (org-add-log-maybe 'clock-out))
19095 (when org-mode-line-timer
19096 (cancel-timer org-mode-line-timer)
19097 (setq org-mode-line-timer nil))
19098 (setq global-mode-string
19099 (delq 'org-mode-line-string global-mode-string))
19100 (force-mode-line-update)
19101 (message "Clock stopped at %s after HH:MM = %d:%02d" te h m)))))
19103 (defun org-clock-cancel ()
19104 "Cancel the running clock be removing the start timestamp."
19105 (interactive)
19106 (if (not (marker-buffer org-clock-marker))
19107 (error "No active clock"))
19108 (save-excursion
19109 (set-buffer (marker-buffer org-clock-marker))
19110 (goto-char org-clock-marker)
19111 (delete-region (1- (point-at-bol)) (point-at-eol)))
19112 (setq global-mode-string
19113 (delq 'org-mode-line-string global-mode-string))
19114 (force-mode-line-update)
19115 (message "Clock canceled"))
19117 (defun org-clock-goto (&optional delete-windows)
19118 "Go to the currently clocked-in entry."
19119 (interactive "P")
19120 (if (not (marker-buffer org-clock-marker))
19121 (error "No active clock"))
19122 (switch-to-buffer-other-window
19123 (marker-buffer org-clock-marker))
19124 (if delete-windows (delete-other-windows))
19125 (goto-char org-clock-marker)
19126 (org-show-entry)
19127 (org-back-to-heading)
19128 (recenter))
19130 (defvar org-clock-file-total-minutes nil
19131 "Holds the file total time in minutes, after a call to `org-clock-sum'.")
19132 (make-variable-buffer-local 'org-clock-file-total-minutes)
19134 (defun org-clock-sum (&optional tstart tend)
19135 "Sum the times for each subtree.
19136 Puts the resulting times in minutes as a text property on each headline."
19137 (interactive)
19138 (let* ((bmp (buffer-modified-p))
19139 (re (concat "^\\(\\*+\\)[ \t]\\|^[ \t]*"
19140 org-clock-string
19141 "[ \t]*\\(?:\\(\\[.*?\\]\\)-+\\(\\[.*?\\]\\)\\|=>[ \t]+\\([0-9]+\\):\\([0-9]+\\)\\)"))
19142 (lmax 30)
19143 (ltimes (make-vector lmax 0))
19144 (t1 0)
19145 (level 0)
19146 ts te dt
19147 time)
19148 (remove-text-properties (point-min) (point-max) '(:org-clock-minutes t))
19149 (save-excursion
19150 (goto-char (point-max))
19151 (while (re-search-backward re nil t)
19152 (cond
19153 ((match-end 2)
19154 ;; Two time stamps
19155 (setq ts (match-string 2)
19156 te (match-string 3)
19157 ts (time-to-seconds
19158 (apply 'encode-time (org-parse-time-string ts)))
19159 te (time-to-seconds
19160 (apply 'encode-time (org-parse-time-string te)))
19161 ts (if tstart (max ts tstart) ts)
19162 te (if tend (min te tend) te)
19163 dt (- te ts)
19164 t1 (if (> dt 0) (+ t1 (floor (/ dt 60))) t1)))
19165 ((match-end 4)
19166 ;; A naket time
19167 (setq t1 (+ t1 (string-to-number (match-string 5))
19168 (* 60 (string-to-number (match-string 4))))))
19169 (t ;; A headline
19170 (setq level (- (match-end 1) (match-beginning 1)))
19171 (when (or (> t1 0) (> (aref ltimes level) 0))
19172 (loop for l from 0 to level do
19173 (aset ltimes l (+ (aref ltimes l) t1)))
19174 (setq t1 0 time (aref ltimes level))
19175 (loop for l from level to (1- lmax) do
19176 (aset ltimes l 0))
19177 (goto-char (match-beginning 0))
19178 (put-text-property (point) (point-at-eol) :org-clock-minutes time)))))
19179 (setq org-clock-file-total-minutes (aref ltimes 0)))
19180 (set-buffer-modified-p bmp)))
19182 (defun org-clock-display (&optional total-only)
19183 "Show subtree times in the entire buffer.
19184 If TOTAL-ONLY is non-nil, only show the total time for the entire file
19185 in the echo area."
19186 (interactive)
19187 (org-remove-clock-overlays)
19188 (let (time h m p)
19189 (org-clock-sum)
19190 (unless total-only
19191 (save-excursion
19192 (goto-char (point-min))
19193 (while (or (and (equal (setq p (point)) (point-min))
19194 (get-text-property p :org-clock-minutes))
19195 (setq p (next-single-property-change
19196 (point) :org-clock-minutes)))
19197 (goto-char p)
19198 (when (setq time (get-text-property p :org-clock-minutes))
19199 (org-put-clock-overlay time (funcall outline-level))))
19200 (setq h (/ org-clock-file-total-minutes 60)
19201 m (- org-clock-file-total-minutes (* 60 h)))
19202 ;; Arrange to remove the overlays upon next change.
19203 (when org-remove-highlights-with-change
19204 (org-add-hook 'before-change-functions 'org-remove-clock-overlays
19205 nil 'local))))
19206 (message "Total file time: %d:%02d (%d hours and %d minutes)" h m h m)))
19208 (defvar org-clock-overlays nil)
19209 (make-variable-buffer-local 'org-clock-overlays)
19211 (defun org-put-clock-overlay (time &optional level)
19212 "Put an overlays on the current line, displaying TIME.
19213 If LEVEL is given, prefix time with a corresponding number of stars.
19214 This creates a new overlay and stores it in `org-clock-overlays', so that it
19215 will be easy to remove."
19216 (let* ((c 60) (h (floor (/ time 60))) (m (- time (* 60 h)))
19217 (l (if level (org-get-valid-level level 0) 0))
19218 (off 0)
19219 ov tx)
19220 (move-to-column c)
19221 (unless (eolp) (skip-chars-backward "^ \t"))
19222 (skip-chars-backward " \t")
19223 (setq ov (org-make-overlay (1- (point)) (point-at-eol))
19224 tx (concat (buffer-substring (1- (point)) (point))
19225 (make-string (+ off (max 0 (- c (current-column)))) ?.)
19226 (org-add-props (format "%s %2d:%02d%s"
19227 (make-string l ?*) h m
19228 (make-string (- 16 l) ?\ ))
19229 '(face secondary-selection))
19230 ""))
19231 (if (not (featurep 'xemacs))
19232 (org-overlay-put ov 'display tx)
19233 (org-overlay-put ov 'invisible t)
19234 (org-overlay-put ov 'end-glyph (make-glyph tx)))
19235 (push ov org-clock-overlays)))
19237 (defun org-remove-clock-overlays (&optional beg end noremove)
19238 "Remove the occur highlights from the buffer.
19239 BEG and END are ignored. If NOREMOVE is nil, remove this function
19240 from the `before-change-functions' in the current buffer."
19241 (interactive)
19242 (unless org-inhibit-highlight-removal
19243 (mapc 'org-delete-overlay org-clock-overlays)
19244 (setq org-clock-overlays nil)
19245 (unless noremove
19246 (remove-hook 'before-change-functions
19247 'org-remove-clock-overlays 'local))))
19249 (defun org-clock-out-if-current ()
19250 "Clock out if the current entry contains the running clock.
19251 This is used to stop the clock after a TODO entry is marked DONE,
19252 and is only done if the variable `org-clock-out-when-done' is not nil."
19253 (when (and org-clock-out-when-done
19254 (member state org-done-keywords)
19255 (equal (marker-buffer org-clock-marker) (current-buffer))
19256 (< (point) org-clock-marker)
19257 (> (save-excursion (outline-next-heading) (point))
19258 org-clock-marker))
19259 ;; Clock out, but don't accept a logging message for this.
19260 (let ((org-log-note-clock-out nil))
19261 (org-clock-out))))
19263 (add-hook 'org-after-todo-state-change-hook
19264 'org-clock-out-if-current)
19266 (defun org-check-running-clock ()
19267 "Check if the current buffer contains the running clock.
19268 If yes, offer to stop it and to save the buffer with the changes."
19269 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
19270 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
19271 (buffer-name))))
19272 (org-clock-out)
19273 (when (y-or-n-p "Save changed buffer?")
19274 (save-buffer))))
19276 (defun org-clock-report (&optional arg)
19277 "Create a table containing a report about clocked time.
19278 If the cursor is inside an existing clocktable block, then the table
19279 will be updated. If not, a new clocktable will be inserted.
19280 When called with a prefix argument, move to the first clock table in the
19281 buffer and update it."
19282 (interactive "P")
19283 (org-remove-clock-overlays)
19284 (when arg
19285 (org-find-dblock "clocktable")
19286 (org-show-entry))
19287 (if (org-in-clocktable-p)
19288 (goto-char (org-in-clocktable-p))
19289 (org-create-dblock (list :name "clocktable"
19290 :maxlevel 2 :scope 'file)))
19291 (org-update-dblock))
19293 (defun org-in-clocktable-p ()
19294 "Check if the cursor is in a clocktable."
19295 (let ((pos (point)) start)
19296 (save-excursion
19297 (end-of-line 1)
19298 (and (re-search-backward "^#\\+BEGIN:[ \t]+clocktable" nil t)
19299 (setq start (match-beginning 0))
19300 (re-search-forward "^#\\+END:.*" nil t)
19301 (>= (match-end 0) pos)
19302 start))))
19304 (defun org-clock-update-time-maybe ()
19305 "If this is a CLOCK line, update it and return t.
19306 Otherwise, return nil."
19307 (interactive)
19308 (save-excursion
19309 (beginning-of-line 1)
19310 (skip-chars-forward " \t")
19311 (when (looking-at org-clock-string)
19312 (let ((re (concat "[ \t]*" org-clock-string
19313 " *[[<]\\([^]>]+\\)[]>]-+[[<]\\([^]>]+\\)[]>]"
19314 "\\([ \t]*=>.*\\)?"))
19315 ts te h m s)
19316 (if (not (looking-at re))
19318 (and (match-end 3) (delete-region (match-beginning 3) (match-end 3)))
19319 (end-of-line 1)
19320 (setq ts (match-string 1)
19321 te (match-string 2))
19322 (setq s (- (time-to-seconds
19323 (apply 'encode-time (org-parse-time-string te)))
19324 (time-to-seconds
19325 (apply 'encode-time (org-parse-time-string ts))))
19326 h (floor (/ s 3600))
19327 s (- s (* 3600 h))
19328 m (floor (/ s 60))
19329 s (- s (* 60 s)))
19330 (insert " => " (format "%2d:%02d" h m))
19331 t)))))
19333 (defun org-clock-special-range (key &optional time as-strings)
19334 "Return two times bordering a special time range.
19335 Key is a symbol specifying the range and can be one of `today', `yesterday',
19336 `thisweek', `lastweek', `thismonth', `lastmonth', `thisyear', `lastyear'.
19337 A week starts Monday 0:00 and ends Sunday 24:00.
19338 The range is determined relative to TIME. TIME defaults to the current time.
19339 The return value is a cons cell with two internal times like the ones
19340 returned by `current time' or `encode-time'. if AS-STRINGS is non-nil,
19341 the returned times will be formatted strings."
19342 (let* ((tm (decode-time (or time (current-time))))
19343 (s 0) (m (nth 1 tm)) (h (nth 2 tm))
19344 (d (nth 3 tm)) (month (nth 4 tm)) (y (nth 5 tm))
19345 (dow (nth 6 tm))
19346 s1 m1 h1 d1 month1 y1 diff ts te fm)
19347 (cond
19348 ((eq key 'today)
19349 (setq h 0 m 0 h1 24 m1 0))
19350 ((eq key 'yesterday)
19351 (setq d (1- d) h 0 m 0 h1 24 m1 0))
19352 ((eq key 'thisweek)
19353 (setq diff (if (= dow 0) 6 (1- dow))
19354 m 0 h 0 d (- d diff) d1 (+ 7 d)))
19355 ((eq key 'lastweek)
19356 (setq diff (+ 7 (if (= dow 0) 6 (1- dow)))
19357 m 0 h 0 d (- d diff) d1 (+ 7 d)))
19358 ((eq key 'thismonth)
19359 (setq d 1 h 0 m 0 d1 1 month1 (1+ month) h1 0 m1 0))
19360 ((eq key 'lastmonth)
19361 (setq d 1 h 0 m 0 d1 1 month (1- month) month1 (1+ month) h1 0 m1 0))
19362 ((eq key 'thisyear)
19363 (setq m 0 h 0 d 1 month 1 y1 (1+ y)))
19364 ((eq key 'lastyear)
19365 (setq m 0 h 0 d 1 month 1 y (1- y) y1 (1+ y)))
19366 (t (error "No such time block %s" key)))
19367 (setq ts (encode-time s m h d month y)
19368 te (encode-time (or s1 s) (or m1 m) (or h1 h)
19369 (or d1 d) (or month1 month) (or y1 y)))
19370 (setq fm (cdr org-time-stamp-formats))
19371 (if as-strings
19372 (cons (format-time-string fm ts) (format-time-string fm te))
19373 (cons ts te))))
19375 (defun org-dblock-write:clocktable (params)
19376 "Write the standard clocktable."
19377 (catch 'exit
19378 (let* ((hlchars '((1 . "*") (2 . "/")))
19379 (ins (make-marker))
19380 (total-time nil)
19381 (scope (plist-get params :scope))
19382 (tostring (plist-get params :tostring))
19383 (multifile (plist-get params :multifile))
19384 (header (plist-get params :header))
19385 (maxlevel (or (plist-get params :maxlevel) 3))
19386 (step (plist-get params :step))
19387 (emph (plist-get params :emphasize))
19388 (ts (plist-get params :tstart))
19389 (te (plist-get params :tend))
19390 (block (plist-get params :block))
19391 (link (plist-get params :link))
19392 ipos time h m p level hlc hdl
19393 cc beg end pos tbl)
19394 (when step
19395 (org-clocktable-steps params)
19396 (throw 'exit nil))
19397 (when block
19398 (setq cc (org-clock-special-range block nil t)
19399 ts (car cc) te (cdr cc)))
19400 (if ts (setq ts (time-to-seconds
19401 (apply 'encode-time (org-parse-time-string ts)))))
19402 (if te (setq te (time-to-seconds
19403 (apply 'encode-time (org-parse-time-string te)))))
19404 (move-marker ins (point))
19405 (setq ipos (point))
19407 ;; Get the right scope
19408 (setq pos (point))
19409 (save-restriction
19410 (cond
19411 ((not scope))
19412 ((eq scope 'file) (widen))
19413 ((eq scope 'subtree) (org-narrow-to-subtree))
19414 ((eq scope 'tree)
19415 (while (org-up-heading-safe))
19416 (org-narrow-to-subtree))
19417 ((and (symbolp scope) (string-match "^tree\\([0-9]+\\)$"
19418 (symbol-name scope)))
19419 (setq level (string-to-number (match-string 1 (symbol-name scope))))
19420 (catch 'exit
19421 (while (org-up-heading-safe)
19422 (looking-at outline-regexp)
19423 (if (<= (org-reduced-level (funcall outline-level)) level)
19424 (throw 'exit nil))))
19425 (org-narrow-to-subtree))
19426 ((or (listp scope) (eq scope 'agenda))
19427 (let* ((files (if (listp scope) scope (org-agenda-files)))
19428 (scope 'agenda)
19429 (p1 (copy-sequence params))
19430 file)
19431 (plist-put p1 :tostring t)
19432 (plist-put p1 :multifile t)
19433 (plist-put p1 :scope 'file)
19434 (org-prepare-agenda-buffers files)
19435 (while (setq file (pop files))
19436 (with-current-buffer (find-buffer-visiting file)
19437 (push (org-clocktable-add-file
19438 file (org-dblock-write:clocktable p1)) tbl)
19439 (setq total-time (+ (or total-time 0)
19440 org-clock-file-total-minutes)))))))
19441 (goto-char pos)
19443 (unless (eq scope 'agenda)
19444 (org-clock-sum ts te)
19445 (goto-char (point-min))
19446 (while (setq p (next-single-property-change (point) :org-clock-minutes))
19447 (goto-char p)
19448 (when (setq time (get-text-property p :org-clock-minutes))
19449 (save-excursion
19450 (beginning-of-line 1)
19451 (when (and (looking-at (org-re "\\(\\*+\\)[ \t]+\\(.*?\\)\\([ \t]+:[[:alnum:]_@:]+:\\)?[ \t]*$"))
19452 (setq level (org-reduced-level
19453 (- (match-end 1) (match-beginning 1))))
19454 (<= level maxlevel))
19455 (setq hlc (if emph (or (cdr (assoc level hlchars)) "") "")
19456 hdl (if (not link)
19457 (match-string 2)
19458 (org-make-link-string
19459 (format "file:%s::%s"
19460 (buffer-file-name)
19461 (save-match-data
19462 (org-make-org-heading-search-string
19463 (match-string 2))))
19464 (match-string 2)))
19465 h (/ time 60)
19466 m (- time (* 60 h)))
19467 (if (and (not multifile) (= level 1)) (push "|-" tbl))
19468 (push (concat
19469 "| " (int-to-string level) "|" hlc hdl hlc " |"
19470 (make-string (1- level) ?|)
19471 hlc (format "%d:%02d" h m) hlc
19472 " |") tbl))))))
19473 (setq tbl (nreverse tbl))
19474 (if tostring
19475 (if tbl (mapconcat 'identity tbl "\n") nil)
19476 (goto-char ins)
19477 (insert-before-markers
19478 (or header
19479 (concat
19480 "Clock summary at ["
19481 (substring
19482 (format-time-string (cdr org-time-stamp-formats))
19483 1 -1)
19484 "]."
19485 (if block
19486 (format " Considered range is /%s/." block)
19488 "\n\n"))
19489 (if (eq scope 'agenda) "|File" "")
19490 "|L|Headline|Time|\n")
19491 (setq total-time (or total-time org-clock-file-total-minutes)
19492 h (/ total-time 60)
19493 m (- total-time (* 60 h)))
19494 (insert-before-markers
19495 "|-\n|"
19496 (if (eq scope 'agenda) "|" "")
19498 "*Total time*| "
19499 (format "*%d:%02d*" h m)
19500 "|\n|-\n")
19501 (setq tbl (delq nil tbl))
19502 (if (and (stringp (car tbl)) (> (length (car tbl)) 1)
19503 (equal (substring (car tbl) 0 2) "|-"))
19504 (pop tbl))
19505 (insert-before-markers (mapconcat
19506 'identity (delq nil tbl)
19507 (if (eq scope 'agenda) "\n|-\n" "\n")))
19508 (backward-delete-char 1)
19509 (goto-char ipos)
19510 (skip-chars-forward "^|")
19511 (org-table-align))))))
19513 (defun org-clocktable-steps (params)
19514 (let* ((p1 (copy-sequence params))
19515 (ts (plist-get p1 :tstart))
19516 (te (plist-get p1 :tend))
19517 (step0 (plist-get p1 :step))
19518 (step (cdr (assoc step0 '((day . 86400) (week . 604800)))))
19519 (block (plist-get p1 :block))
19521 (when block
19522 (setq cc (org-clock-special-range block nil t)
19523 ts (car cc) te (cdr cc)))
19524 (if ts (setq ts (time-to-seconds
19525 (apply 'encode-time (org-parse-time-string ts)))))
19526 (if te (setq te (time-to-seconds
19527 (apply 'encode-time (org-parse-time-string te)))))
19528 (plist-put p1 :header "")
19529 (plist-put p1 :step nil)
19530 (plist-put p1 :block nil)
19531 (while (< ts te)
19532 (or (bolp) (insert "\n"))
19533 (plist-put p1 :tstart (format-time-string
19534 (car org-time-stamp-formats)
19535 (seconds-to-time ts)))
19536 (plist-put p1 :tend (format-time-string
19537 (car org-time-stamp-formats)
19538 (seconds-to-time (setq ts (+ ts step)))))
19539 (insert "\n" (if (eq step0 'day) "Daily report: " "Weekly report starting on: ")
19540 (plist-get p1 :tstart) "\n")
19541 (org-dblock-write:clocktable p1)
19542 (re-search-forward "#\\+END:")
19543 (end-of-line 0))))
19546 (defun org-clocktable-add-file (file table)
19547 (if table
19548 (let ((lines (org-split-string table "\n"))
19549 (ff (file-name-nondirectory file)))
19550 (mapconcat 'identity
19551 (mapcar (lambda (x)
19552 (if (string-match org-table-dataline-regexp x)
19553 (concat "|" ff x)
19555 lines)
19556 "\n"))))
19558 ;; FIXME: I don't think anybody uses this, ask David
19559 (defun org-collect-clock-time-entries ()
19560 "Return an internal list with clocking information.
19561 This list has one entry for each CLOCK interval.
19562 FIXME: describe the elements."
19563 (interactive)
19564 (let ((re (concat "^[ \t]*" org-clock-string
19565 " *\\[\\(.*?\\)\\]--\\[\\(.*?\\)\\]"))
19566 rtn beg end next cont level title total closedp leafp
19567 clockpos titlepos h m donep)
19568 (save-excursion
19569 (org-clock-sum)
19570 (goto-char (point-min))
19571 (while (re-search-forward re nil t)
19572 (setq clockpos (match-beginning 0)
19573 beg (match-string 1) end (match-string 2)
19574 cont (match-end 0))
19575 (setq beg (apply 'encode-time (org-parse-time-string beg))
19576 end (apply 'encode-time (org-parse-time-string end)))
19577 (org-back-to-heading t)
19578 (setq donep (org-entry-is-done-p))
19579 (setq titlepos (point)
19580 total (or (get-text-property (1+ (point)) :org-clock-minutes) 0)
19581 h (/ total 60) m (- total (* 60 h))
19582 total (cons h m))
19583 (looking-at "\\(\\*+\\) +\\(.*\\)")
19584 (setq level (- (match-end 1) (match-beginning 1))
19585 title (org-match-string-no-properties 2))
19586 (save-excursion (outline-next-heading) (setq next (point)))
19587 (setq closedp (re-search-forward org-closed-time-regexp next t))
19588 (goto-char next)
19589 (setq leafp (and (looking-at "^\\*+ ")
19590 (<= (- (match-end 0) (point)) level)))
19591 (push (list beg end clockpos closedp donep
19592 total title titlepos level leafp)
19593 rtn)
19594 (goto-char cont)))
19595 (nreverse rtn)))
19597 ;;;; Agenda, and Diary Integration
19599 ;;; Define the Org-agenda-mode
19601 (defvar org-agenda-mode-map (make-sparse-keymap)
19602 "Keymap for `org-agenda-mode'.")
19604 (defvar org-agenda-menu) ; defined later in this file.
19605 (defvar org-agenda-follow-mode nil)
19606 (defvar org-agenda-show-log nil)
19607 (defvar org-agenda-redo-command nil)
19608 (defvar org-agenda-query-string nil)
19609 (defvar org-agenda-mode-hook nil)
19610 (defvar org-agenda-type nil)
19611 (defvar org-agenda-force-single-file nil)
19613 (defun org-agenda-mode ()
19614 "Mode for time-sorted view on action items in Org-mode files.
19616 The following commands are available:
19618 \\{org-agenda-mode-map}"
19619 (interactive)
19620 (kill-all-local-variables)
19621 (setq org-agenda-undo-list nil
19622 org-agenda-pending-undo-list nil)
19623 (setq major-mode 'org-agenda-mode)
19624 ;; Keep global-font-lock-mode from turning on font-lock-mode
19625 (org-set-local 'font-lock-global-modes (list 'not major-mode))
19626 (setq mode-name "Org-Agenda")
19627 (use-local-map org-agenda-mode-map)
19628 (easy-menu-add org-agenda-menu)
19629 (if org-startup-truncated (setq truncate-lines t))
19630 (org-add-hook 'post-command-hook 'org-agenda-post-command-hook nil 'local)
19631 (org-add-hook 'pre-command-hook 'org-unhighlight nil 'local)
19632 ;; Make sure properties are removed when copying text
19633 (when (boundp 'buffer-substring-filters)
19634 (org-set-local 'buffer-substring-filters
19635 (cons (lambda (x)
19636 (set-text-properties 0 (length x) nil x) x)
19637 buffer-substring-filters)))
19638 (unless org-agenda-keep-modes
19639 (setq org-agenda-follow-mode org-agenda-start-with-follow-mode
19640 org-agenda-show-log nil))
19641 (easy-menu-change
19642 '("Agenda") "Agenda Files"
19643 (append
19644 (list
19645 (vector
19646 (if (get 'org-agenda-files 'org-restrict)
19647 "Restricted to single file"
19648 "Edit File List")
19649 '(org-edit-agenda-file-list)
19650 (not (get 'org-agenda-files 'org-restrict)))
19651 "--")
19652 (mapcar 'org-file-menu-entry (org-agenda-files))))
19653 (org-agenda-set-mode-name)
19654 (apply
19655 (if (fboundp 'run-mode-hooks) 'run-mode-hooks 'run-hooks)
19656 (list 'org-agenda-mode-hook)))
19658 (substitute-key-definition 'undo 'org-agenda-undo
19659 org-agenda-mode-map global-map)
19660 (org-defkey org-agenda-mode-map "\C-i" 'org-agenda-goto)
19661 (org-defkey org-agenda-mode-map [(tab)] 'org-agenda-goto)
19662 (org-defkey org-agenda-mode-map "\C-m" 'org-agenda-switch-to)
19663 (org-defkey org-agenda-mode-map "\C-k" 'org-agenda-kill)
19664 (org-defkey org-agenda-mode-map "\C-c$" 'org-agenda-archive)
19665 (org-defkey org-agenda-mode-map "\C-c\C-x\C-s" 'org-agenda-archive)
19666 (org-defkey org-agenda-mode-map "$" 'org-agenda-archive)
19667 (org-defkey org-agenda-mode-map "\C-c\C-o" 'org-agenda-open-link)
19668 (org-defkey org-agenda-mode-map " " 'org-agenda-show)
19669 (org-defkey org-agenda-mode-map "\C-c\C-t" 'org-agenda-todo)
19670 (org-defkey org-agenda-mode-map [(control shift right)] 'org-agenda-todo-nextset)
19671 (org-defkey org-agenda-mode-map [(control shift left)] 'org-agenda-todo-previousset)
19672 (org-defkey org-agenda-mode-map "\C-c\C-xb" 'org-agenda-tree-to-indirect-buffer)
19673 (org-defkey org-agenda-mode-map "b" 'org-agenda-tree-to-indirect-buffer)
19674 (org-defkey org-agenda-mode-map "o" 'delete-other-windows)
19675 (org-defkey org-agenda-mode-map "L" 'org-agenda-recenter)
19676 (org-defkey org-agenda-mode-map "t" 'org-agenda-todo)
19677 (org-defkey org-agenda-mode-map "a" 'org-agenda-toggle-archive-tag)
19678 (org-defkey org-agenda-mode-map ":" 'org-agenda-set-tags)
19679 (org-defkey org-agenda-mode-map "." 'org-agenda-goto-today)
19680 (org-defkey org-agenda-mode-map "j" 'org-agenda-goto-date)
19681 (org-defkey org-agenda-mode-map "d" 'org-agenda-day-view)
19682 (org-defkey org-agenda-mode-map "w" 'org-agenda-week-view)
19683 (org-defkey org-agenda-mode-map "m" 'org-agenda-month-view)
19684 (org-defkey org-agenda-mode-map "y" 'org-agenda-year-view)
19685 (org-defkey org-agenda-mode-map [(shift right)] 'org-agenda-date-later)
19686 (org-defkey org-agenda-mode-map [(shift left)] 'org-agenda-date-earlier)
19687 (org-defkey org-agenda-mode-map [?\C-c ?\C-x (right)] 'org-agenda-date-later)
19688 (org-defkey org-agenda-mode-map [?\C-c ?\C-x (left)] 'org-agenda-date-earlier)
19690 (org-defkey org-agenda-mode-map ">" 'org-agenda-date-prompt)
19691 (org-defkey org-agenda-mode-map "\C-c\C-s" 'org-agenda-schedule)
19692 (org-defkey org-agenda-mode-map "\C-c\C-d" 'org-agenda-deadline)
19693 (let ((l '(1 2 3 4 5 6 7 8 9 0)))
19694 (while l (org-defkey org-agenda-mode-map
19695 (int-to-string (pop l)) 'digit-argument)))
19697 (org-defkey org-agenda-mode-map "f" 'org-agenda-follow-mode)
19698 (org-defkey org-agenda-mode-map "l" 'org-agenda-log-mode)
19699 (org-defkey org-agenda-mode-map "D" 'org-agenda-toggle-diary)
19700 (org-defkey org-agenda-mode-map "G" 'org-agenda-toggle-time-grid)
19701 (org-defkey org-agenda-mode-map "r" 'org-agenda-redo)
19702 (org-defkey org-agenda-mode-map "g" 'org-agenda-redo)
19703 (org-defkey org-agenda-mode-map "e" 'org-agenda-execute)
19704 (org-defkey org-agenda-mode-map "q" 'org-agenda-quit)
19705 (org-defkey org-agenda-mode-map "x" 'org-agenda-exit)
19706 (org-defkey org-agenda-mode-map "\C-x\C-w" 'org-write-agenda)
19707 (org-defkey org-agenda-mode-map "s" 'org-save-all-org-buffers)
19708 (org-defkey org-agenda-mode-map "\C-x\C-s" 'org-save-all-org-buffers)
19709 (org-defkey org-agenda-mode-map "P" 'org-agenda-show-priority)
19710 (org-defkey org-agenda-mode-map "T" 'org-agenda-show-tags)
19711 (org-defkey org-agenda-mode-map "n" 'next-line)
19712 (org-defkey org-agenda-mode-map "p" 'previous-line)
19713 (org-defkey org-agenda-mode-map "\C-c\C-n" 'org-agenda-next-date-line)
19714 (org-defkey org-agenda-mode-map "\C-c\C-p" 'org-agenda-previous-date-line)
19715 (org-defkey org-agenda-mode-map "," 'org-agenda-priority)
19716 (org-defkey org-agenda-mode-map "\C-c," 'org-agenda-priority)
19717 (org-defkey org-agenda-mode-map "i" 'org-agenda-diary-entry)
19718 (org-defkey org-agenda-mode-map "c" 'org-agenda-goto-calendar)
19719 (eval-after-load "calendar"
19720 '(org-defkey calendar-mode-map org-calendar-to-agenda-key
19721 'org-calendar-goto-agenda))
19722 (org-defkey org-agenda-mode-map "C" 'org-agenda-convert-date)
19723 (org-defkey org-agenda-mode-map "M" 'org-agenda-phases-of-moon)
19724 (org-defkey org-agenda-mode-map "S" 'org-agenda-sunrise-sunset)
19725 (org-defkey org-agenda-mode-map "h" 'org-agenda-holidays)
19726 (org-defkey org-agenda-mode-map "H" 'org-agenda-holidays)
19727 (org-defkey org-agenda-mode-map "\C-c\C-x\C-i" 'org-agenda-clock-in)
19728 (org-defkey org-agenda-mode-map "I" 'org-agenda-clock-in)
19729 (org-defkey org-agenda-mode-map "\C-c\C-x\C-o" 'org-agenda-clock-out)
19730 (org-defkey org-agenda-mode-map "O" 'org-agenda-clock-out)
19731 (org-defkey org-agenda-mode-map "\C-c\C-x\C-x" 'org-agenda-clock-cancel)
19732 (org-defkey org-agenda-mode-map "X" 'org-agenda-clock-cancel)
19733 (org-defkey org-agenda-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
19734 (org-defkey org-agenda-mode-map "J" 'org-clock-goto)
19735 (org-defkey org-agenda-mode-map "+" 'org-agenda-priority-up)
19736 (org-defkey org-agenda-mode-map "-" 'org-agenda-priority-down)
19737 (org-defkey org-agenda-mode-map [(shift up)] 'org-agenda-priority-up)
19738 (org-defkey org-agenda-mode-map [(shift down)] 'org-agenda-priority-down)
19739 (org-defkey org-agenda-mode-map [?\C-c ?\C-x (up)] 'org-agenda-priority-up)
19740 (org-defkey org-agenda-mode-map [?\C-c ?\C-x (down)] 'org-agenda-priority-down)
19741 (org-defkey org-agenda-mode-map [(right)] 'org-agenda-later)
19742 (org-defkey org-agenda-mode-map [(left)] 'org-agenda-earlier)
19743 (org-defkey org-agenda-mode-map "\C-c\C-x\C-c" 'org-agenda-columns)
19745 (org-defkey org-agenda-mode-map "[" 'org-agenda-manipulate-query-add)
19746 (org-defkey org-agenda-mode-map "]" 'org-agenda-manipulate-query-subtract)
19747 (org-defkey org-agenda-mode-map "{" 'org-agenda-manipulate-query-add-re)
19748 (org-defkey org-agenda-mode-map "}" 'org-agenda-manipulate-query-subtract-re)
19750 (defvar org-agenda-keymap (copy-keymap org-agenda-mode-map)
19751 "Local keymap for agenda entries from Org-mode.")
19753 (org-defkey org-agenda-keymap
19754 (if (featurep 'xemacs) [(button2)] [(mouse-2)]) 'org-agenda-goto-mouse)
19755 (org-defkey org-agenda-keymap
19756 (if (featurep 'xemacs) [(button3)] [(mouse-3)]) 'org-agenda-show-mouse)
19757 (when org-agenda-mouse-1-follows-link
19758 (org-defkey org-agenda-keymap [follow-link] 'mouse-face))
19759 (easy-menu-define org-agenda-menu org-agenda-mode-map "Agenda menu"
19760 '("Agenda"
19761 ("Agenda Files")
19762 "--"
19763 ["Show" org-agenda-show t]
19764 ["Go To (other window)" org-agenda-goto t]
19765 ["Go To (this window)" org-agenda-switch-to t]
19766 ["Follow Mode" org-agenda-follow-mode
19767 :style toggle :selected org-agenda-follow-mode :active t]
19768 ["Tree to indirect frame" org-agenda-tree-to-indirect-buffer t]
19769 "--"
19770 ["Cycle TODO" org-agenda-todo t]
19771 ["Archive subtree" org-agenda-archive t]
19772 ["Delete subtree" org-agenda-kill t]
19773 "--"
19774 ["Goto Today" org-agenda-goto-today (org-agenda-check-type nil 'agenda 'timeline)]
19775 ["Next Dates" org-agenda-later (org-agenda-check-type nil 'agenda)]
19776 ["Previous Dates" org-agenda-earlier (org-agenda-check-type nil 'agenda)]
19777 ["Jump to date" org-agenda-goto-date (org-agenda-check-type nil 'agenda)]
19778 "--"
19779 ("Tags and Properties"
19780 ["Show all Tags" org-agenda-show-tags t]
19781 ["Set Tags current line" org-agenda-set-tags (not (org-region-active-p))]
19782 ["Change tag in region" org-agenda-set-tags (org-region-active-p)]
19783 "--"
19784 ["Column View" org-columns t])
19785 ("Date/Schedule"
19786 ["Schedule" org-agenda-schedule t]
19787 ["Set Deadline" org-agenda-deadline t]
19788 "--"
19789 ["Change Date +1 day" org-agenda-date-later (org-agenda-check-type nil 'agenda 'timeline)]
19790 ["Change Date -1 day" org-agenda-date-earlier (org-agenda-check-type nil 'agenda 'timeline)]
19791 ["Change Date to ..." org-agenda-date-prompt (org-agenda-check-type nil 'agenda 'timeline)])
19792 ("Clock"
19793 ["Clock in" org-agenda-clock-in t]
19794 ["Clock out" org-agenda-clock-out t]
19795 ["Clock cancel" org-agenda-clock-cancel t]
19796 ["Goto running clock" org-clock-goto t])
19797 ("Priority"
19798 ["Set Priority" org-agenda-priority t]
19799 ["Increase Priority" org-agenda-priority-up t]
19800 ["Decrease Priority" org-agenda-priority-down t]
19801 ["Show Priority" org-agenda-show-priority t])
19802 ("Calendar/Diary"
19803 ["New Diary Entry" org-agenda-diary-entry (org-agenda-check-type nil 'agenda 'timeline)]
19804 ["Goto Calendar" org-agenda-goto-calendar (org-agenda-check-type nil 'agenda 'timeline)]
19805 ["Phases of the Moon" org-agenda-phases-of-moon (org-agenda-check-type nil 'agenda 'timeline)]
19806 ["Sunrise/Sunset" org-agenda-sunrise-sunset (org-agenda-check-type nil 'agenda 'timeline)]
19807 ["Holidays" org-agenda-holidays (org-agenda-check-type nil 'agenda 'timeline)]
19808 ["Convert" org-agenda-convert-date (org-agenda-check-type nil 'agenda 'timeline)]
19809 "--"
19810 ["Create iCalendar file" org-export-icalendar-combine-agenda-files t])
19811 "--"
19812 ("View"
19813 ["Day View" org-agenda-day-view :active (org-agenda-check-type nil 'agenda)
19814 :style radio :selected (equal org-agenda-ndays 1)]
19815 ["Week View" org-agenda-week-view :active (org-agenda-check-type nil 'agenda)
19816 :style radio :selected (equal org-agenda-ndays 7)]
19817 ["Month View" org-agenda-month-view :active (org-agenda-check-type nil 'agenda)
19818 :style radio :selected (member org-agenda-ndays '(28 29 30 31))]
19819 ["Year View" org-agenda-year-view :active (org-agenda-check-type nil 'agenda)
19820 :style radio :selected (member org-agenda-ndays '(365 366))]
19821 "--"
19822 ["Show Logbook entries" org-agenda-log-mode
19823 :style toggle :selected org-agenda-show-log :active (org-agenda-check-type nil 'agenda 'timeline)]
19824 ["Include Diary" org-agenda-toggle-diary
19825 :style toggle :selected org-agenda-include-diary :active (org-agenda-check-type nil 'agenda)]
19826 ["Use Time Grid" org-agenda-toggle-time-grid
19827 :style toggle :selected org-agenda-use-time-grid :active (org-agenda-check-type nil 'agenda)])
19828 ["Write view to file" org-write-agenda t]
19829 ["Rebuild buffer" org-agenda-redo t]
19830 ["Save all Org-mode Buffers" org-save-all-org-buffers t]
19831 "--"
19832 ["Undo Remote Editing" org-agenda-undo org-agenda-undo-list]
19833 "--"
19834 ["Quit" org-agenda-quit t]
19835 ["Exit and Release Buffers" org-agenda-exit t]
19838 ;;; Agenda undo
19840 (defvar org-agenda-allow-remote-undo t
19841 "Non-nil means, allow remote undo from the agenda buffer.")
19842 (defvar org-agenda-undo-list nil
19843 "List of undoable operations in the agenda since last refresh.")
19844 (defvar org-agenda-undo-has-started-in nil
19845 "Buffers that have already seen `undo-start' in the current undo sequence.")
19846 (defvar org-agenda-pending-undo-list nil
19847 "In a series of undo commands, this is the list of remaning undo items.")
19849 (defmacro org-if-unprotected (&rest body)
19850 "Execute BODY if there is no `org-protected' text property at point."
19851 (declare (debug t))
19852 `(unless (get-text-property (point) 'org-protected)
19853 ,@body))
19855 (defmacro org-with-remote-undo (_buffer &rest _body)
19856 "Execute BODY while recording undo information in two buffers."
19857 (declare (indent 1) (debug t))
19858 `(let ((_cline (org-current-line))
19859 (_cmd this-command)
19860 (_buf1 (current-buffer))
19861 (_buf2 ,_buffer)
19862 (_undo1 buffer-undo-list)
19863 (_undo2 (with-current-buffer ,_buffer buffer-undo-list))
19864 _c1 _c2)
19865 ,@_body
19866 (when org-agenda-allow-remote-undo
19867 (setq _c1 (org-verify-change-for-undo
19868 _undo1 (with-current-buffer _buf1 buffer-undo-list))
19869 _c2 (org-verify-change-for-undo
19870 _undo2 (with-current-buffer _buf2 buffer-undo-list)))
19871 (when (or _c1 _c2)
19872 ;; make sure there are undo boundaries
19873 (and _c1 (with-current-buffer _buf1 (undo-boundary)))
19874 (and _c2 (with-current-buffer _buf2 (undo-boundary)))
19875 ;; remember which buffer to undo
19876 (push (list _cmd _cline _buf1 _c1 _buf2 _c2)
19877 org-agenda-undo-list)))))
19879 (defun org-agenda-undo ()
19880 "Undo a remote editing step in the agenda.
19881 This undoes changes both in the agenda buffer and in the remote buffer
19882 that have been changed along."
19883 (interactive)
19884 (or org-agenda-allow-remote-undo
19885 (error "Check the variable `org-agenda-allow-remote-undo' to activate remote undo."))
19886 (if (not (eq this-command last-command))
19887 (setq org-agenda-undo-has-started-in nil
19888 org-agenda-pending-undo-list org-agenda-undo-list))
19889 (if (not org-agenda-pending-undo-list)
19890 (error "No further undo information"))
19891 (let* ((entry (pop org-agenda-pending-undo-list))
19892 buf line cmd rembuf)
19893 (setq cmd (pop entry) line (pop entry))
19894 (setq rembuf (nth 2 entry))
19895 (org-with-remote-undo rembuf
19896 (while (bufferp (setq buf (pop entry)))
19897 (if (pop entry)
19898 (with-current-buffer buf
19899 (let ((last-undo-buffer buf)
19900 (inhibit-read-only t))
19901 (unless (memq buf org-agenda-undo-has-started-in)
19902 (push buf org-agenda-undo-has-started-in)
19903 (make-local-variable 'pending-undo-list)
19904 (undo-start))
19905 (while (and pending-undo-list
19906 (listp pending-undo-list)
19907 (not (car pending-undo-list)))
19908 (pop pending-undo-list))
19909 (undo-more 1))))))
19910 (goto-line line)
19911 (message "`%s' undone (buffer %s)" cmd (buffer-name rembuf))))
19913 (defun org-verify-change-for-undo (l1 l2)
19914 "Verify that a real change occurred between the undo lists L1 and L2."
19915 (while (and l1 (listp l1) (null (car l1))) (pop l1))
19916 (while (and l2 (listp l2) (null (car l2))) (pop l2))
19917 (not (eq l1 l2)))
19919 ;;; Agenda dispatch
19921 (defvar org-agenda-restrict nil)
19922 (defvar org-agenda-restrict-begin (make-marker))
19923 (defvar org-agenda-restrict-end (make-marker))
19924 (defvar org-agenda-last-dispatch-buffer nil)
19925 (defvar org-agenda-overriding-restriction nil)
19927 ;;;###autoload
19928 (defun org-agenda (arg &optional keys restriction)
19929 "Dispatch agenda commands to collect entries to the agenda buffer.
19930 Prompts for a command to execute. Any prefix arg will be passed
19931 on to the selected command. The default selections are:
19933 a Call `org-agenda-list' to display the agenda for current day or week.
19934 t Call `org-todo-list' to display the global todo list.
19935 T Call `org-todo-list' to display the global todo list, select only
19936 entries with a specific TODO keyword (the user gets a prompt).
19937 m Call `org-tags-view' to display headlines with tags matching
19938 a condition (the user is prompted for the condition).
19939 M Like `m', but select only TODO entries, no ordinary headlines.
19940 L Create a timeline for the current buffer.
19941 e Export views to associated files.
19943 More commands can be added by configuring the variable
19944 `org-agenda-custom-commands'. In particular, specific tags and TODO keyword
19945 searches can be pre-defined in this way.
19947 If the current buffer is in Org-mode and visiting a file, you can also
19948 first press `<' once to indicate that the agenda should be temporarily
19949 \(until the next use of \\[org-agenda]) restricted to the current file.
19950 Pressing `<' twice means to restrict to the current subtree or region
19951 \(if active)."
19952 (interactive "P")
19953 (catch 'exit
19954 (let* ((prefix-descriptions nil)
19955 (org-agenda-custom-commands-orig org-agenda-custom-commands)
19956 (org-agenda-custom-commands
19957 ;; normalize different versions
19958 (delq nil
19959 (mapcar
19960 (lambda (x)
19961 (cond ((stringp (cdr x))
19962 (push x prefix-descriptions)
19963 nil)
19964 ((stringp (nth 1 x)) x)
19965 ((not (nth 1 x)) (cons (car x) (cons "" (cddr x))))
19966 (t (cons (car x) (cons "" (cdr x))))))
19967 org-agenda-custom-commands)))
19968 (buf (current-buffer))
19969 (bfn (buffer-file-name (buffer-base-buffer)))
19970 entry key type match lprops ans)
19971 ;; Turn off restriction unless there is an overriding one
19972 (unless org-agenda-overriding-restriction
19973 (put 'org-agenda-files 'org-restrict nil)
19974 (setq org-agenda-restrict nil)
19975 (move-marker org-agenda-restrict-begin nil)
19976 (move-marker org-agenda-restrict-end nil))
19977 ;; Delete old local properties
19978 (put 'org-agenda-redo-command 'org-lprops nil)
19979 ;; Remember where this call originated
19980 (setq org-agenda-last-dispatch-buffer (current-buffer))
19981 (unless keys
19982 (setq ans (org-agenda-get-restriction-and-command prefix-descriptions)
19983 keys (car ans)
19984 restriction (cdr ans)))
19985 ;; Estabish the restriction, if any
19986 (when (and (not org-agenda-overriding-restriction) restriction)
19987 (put 'org-agenda-files 'org-restrict (list bfn))
19988 (cond
19989 ((eq restriction 'region)
19990 (setq org-agenda-restrict t)
19991 (move-marker org-agenda-restrict-begin (region-beginning))
19992 (move-marker org-agenda-restrict-end (region-end)))
19993 ((eq restriction 'subtree)
19994 (save-excursion
19995 (setq org-agenda-restrict t)
19996 (org-back-to-heading t)
19997 (move-marker org-agenda-restrict-begin (point))
19998 (move-marker org-agenda-restrict-end
19999 (progn (org-end-of-subtree t)))))))
20001 (require 'calendar) ; FIXME: can we avoid this for some commands?
20002 ;; For example the todo list should not need it (but does...)
20003 (cond
20004 ((setq entry (assoc keys org-agenda-custom-commands))
20005 (if (or (symbolp (nth 2 entry)) (functionp (nth 2 entry)))
20006 (progn
20007 (setq type (nth 2 entry) match (nth 3 entry) lprops (nth 4 entry))
20008 (put 'org-agenda-redo-command 'org-lprops lprops)
20009 (cond
20010 ((eq type 'agenda)
20011 (org-let lprops '(org-agenda-list current-prefix-arg)))
20012 ((eq type 'alltodo)
20013 (org-let lprops '(org-todo-list current-prefix-arg)))
20014 ((eq type 'search)
20015 (org-let lprops '(org-search-view current-prefix-arg match)))
20016 ((eq type 'stuck)
20017 (org-let lprops '(org-agenda-list-stuck-projects
20018 current-prefix-arg)))
20019 ((eq type 'tags)
20020 (org-let lprops '(org-tags-view current-prefix-arg match)))
20021 ((eq type 'tags-todo)
20022 (org-let lprops '(org-tags-view '(4) match)))
20023 ((eq type 'todo)
20024 (org-let lprops '(org-todo-list match)))
20025 ((eq type 'tags-tree)
20026 (org-check-for-org-mode)
20027 (org-let lprops '(org-tags-sparse-tree current-prefix-arg match)))
20028 ((eq type 'todo-tree)
20029 (org-check-for-org-mode)
20030 (org-let lprops
20031 '(org-occur (concat "^" outline-regexp "[ \t]*"
20032 (regexp-quote match) "\\>"))))
20033 ((eq type 'occur-tree)
20034 (org-check-for-org-mode)
20035 (org-let lprops '(org-occur match)))
20036 ((functionp type)
20037 (org-let lprops '(funcall type match)))
20038 ((fboundp type)
20039 (org-let lprops '(funcall type match)))
20040 (t (error "Invalid custom agenda command type %s" type))))
20041 (org-run-agenda-series (nth 1 entry) (cddr entry))))
20042 ((equal keys "C")
20043 (setq org-agenda-custom-commands org-agenda-custom-commands-orig)
20044 (customize-variable 'org-agenda-custom-commands))
20045 ((equal keys "a") (call-interactively 'org-agenda-list))
20046 ((equal keys "s") (call-interactively 'org-search-view))
20047 ((equal keys "t") (call-interactively 'org-todo-list))
20048 ((equal keys "T") (org-call-with-arg 'org-todo-list (or arg '(4))))
20049 ((equal keys "m") (call-interactively 'org-tags-view))
20050 ((equal keys "M") (org-call-with-arg 'org-tags-view (or arg '(4))))
20051 ((equal keys "e") (call-interactively 'org-store-agenda-views))
20052 ((equal keys "L")
20053 (unless (org-mode-p)
20054 (error "This is not an Org-mode file"))
20055 (unless restriction
20056 (put 'org-agenda-files 'org-restrict (list bfn))
20057 (org-call-with-arg 'org-timeline arg)))
20058 ((equal keys "#") (call-interactively 'org-agenda-list-stuck-projects))
20059 ((equal keys "/") (call-interactively 'org-occur-in-agenda-files))
20060 ((equal keys "!") (customize-variable 'org-stuck-projects))
20061 (t (error "Invalid agenda key"))))))
20063 (defun org-agenda-normalize-custom-commands (cmds)
20064 (delq nil
20065 (mapcar
20066 (lambda (x)
20067 (cond ((stringp (cdr x)) nil)
20068 ((stringp (nth 1 x)) x)
20069 ((not (nth 1 x)) (cons (car x) (cons "" (cddr x))))
20070 (t (cons (car x) (cons "" (cdr x))))))
20071 cmds)))
20073 (defun org-agenda-get-restriction-and-command (prefix-descriptions)
20074 "The user interface for selecting an agenda command."
20075 (catch 'exit
20076 (let* ((bfn (buffer-file-name (buffer-base-buffer)))
20077 (restrict-ok (and bfn (org-mode-p)))
20078 (region-p (org-region-active-p))
20079 (custom org-agenda-custom-commands)
20080 (selstring "")
20081 restriction second-time
20082 c entry key type match prefixes rmheader header-end custom1 desc)
20083 (save-window-excursion
20084 (delete-other-windows)
20085 (org-switch-to-buffer-other-window " *Agenda Commands*")
20086 (erase-buffer)
20087 (insert (eval-when-compile
20088 (let ((header
20090 Press key for an agenda command: < Buffer,subtree/region restriction
20091 -------------------------------- > Remove restriction
20092 a Agenda for current week or day e Export agenda views
20093 t List of all TODO entries T Entries with special TODO kwd
20094 m Match a TAGS query M Like m, but only TODO entries
20095 L Timeline for current buffer # List stuck projects (!=configure)
20096 s Search for keywords C Configure custom agenda commands
20097 / Multi-occur
20099 (start 0))
20100 (while (string-match
20101 "\\(^\\| \\|(\\)\\(\\S-\\)\\( \\|=\\)"
20102 header start)
20103 (setq start (match-end 0))
20104 (add-text-properties (match-beginning 2) (match-end 2)
20105 '(face bold) header))
20106 header)))
20107 (setq header-end (move-marker (make-marker) (point)))
20108 (while t
20109 (setq custom1 custom)
20110 (when (eq rmheader t)
20111 (goto-line 1)
20112 (re-search-forward ":" nil t)
20113 (delete-region (match-end 0) (point-at-eol))
20114 (forward-char 1)
20115 (looking-at "-+")
20116 (delete-region (match-end 0) (point-at-eol))
20117 (move-marker header-end (match-end 0)))
20118 (goto-char header-end)
20119 (delete-region (point) (point-max))
20120 (while (setq entry (pop custom1))
20121 (setq key (car entry) desc (nth 1 entry)
20122 type (nth 2 entry) match (nth 3 entry))
20123 (if (> (length key) 1)
20124 (add-to-list 'prefixes (string-to-char key))
20125 (insert
20126 (format
20127 "\n%-4s%-14s: %s"
20128 (org-add-props (copy-sequence key)
20129 '(face bold))
20130 (cond
20131 ((string-match "\\S-" desc) desc)
20132 ((eq type 'agenda) "Agenda for current week or day")
20133 ((eq type 'alltodo) "List of all TODO entries")
20134 ((eq type 'search) "Word search")
20135 ((eq type 'stuck) "List of stuck projects")
20136 ((eq type 'todo) "TODO keyword")
20137 ((eq type 'tags) "Tags query")
20138 ((eq type 'tags-todo) "Tags (TODO)")
20139 ((eq type 'tags-tree) "Tags tree")
20140 ((eq type 'todo-tree) "TODO kwd tree")
20141 ((eq type 'occur-tree) "Occur tree")
20142 ((functionp type) (if (symbolp type)
20143 (symbol-name type)
20144 "Lambda expression"))
20145 (t "???"))
20146 (cond
20147 ((stringp match)
20148 (org-add-props match nil 'face 'org-warning))
20149 (match
20150 (format "set of %d commands" (length match)))
20151 (t ""))))))
20152 (when prefixes
20153 (mapc (lambda (x)
20154 (insert
20155 (format "\n%s %s"
20156 (org-add-props (char-to-string x)
20157 nil 'face 'bold)
20158 (or (cdr (assoc (concat selstring (char-to-string x))
20159 prefix-descriptions))
20160 "Prefix key"))))
20161 prefixes))
20162 (goto-char (point-min))
20163 (when (fboundp 'fit-window-to-buffer)
20164 (if second-time
20165 (if (not (pos-visible-in-window-p (point-max)))
20166 (fit-window-to-buffer))
20167 (setq second-time t)
20168 (fit-window-to-buffer)))
20169 (message "Press key for agenda command%s:"
20170 (if (or restrict-ok org-agenda-overriding-restriction)
20171 (if org-agenda-overriding-restriction
20172 " (restriction lock active)"
20173 (if restriction
20174 (format " (restricted to %s)" restriction)
20175 " (unrestricted)"))
20176 ""))
20177 (setq c (read-char-exclusive))
20178 (message "")
20179 (cond
20180 ((assoc (char-to-string c) custom)
20181 (setq selstring (concat selstring (char-to-string c)))
20182 (throw 'exit (cons selstring restriction)))
20183 ((memq c prefixes)
20184 (setq selstring (concat selstring (char-to-string c))
20185 prefixes nil
20186 rmheader (or rmheader t)
20187 custom (delq nil (mapcar
20188 (lambda (x)
20189 (if (or (= (length (car x)) 1)
20190 (/= (string-to-char (car x)) c))
20192 (cons (substring (car x) 1) (cdr x))))
20193 custom))))
20194 ((and (not restrict-ok) (memq c '(?1 ?0 ?<)))
20195 (message "Restriction is only possible in Org-mode buffers")
20196 (ding) (sit-for 1))
20197 ((eq c ?1)
20198 (org-agenda-remove-restriction-lock 'noupdate)
20199 (setq restriction 'buffer))
20200 ((eq c ?0)
20201 (org-agenda-remove-restriction-lock 'noupdate)
20202 (setq restriction (if region-p 'region 'subtree)))
20203 ((eq c ?<)
20204 (org-agenda-remove-restriction-lock 'noupdate)
20205 (setq restriction
20206 (cond
20207 ((eq restriction 'buffer)
20208 (if region-p 'region 'subtree))
20209 ((memq restriction '(subtree region))
20210 nil)
20211 (t 'buffer))))
20212 ((eq c ?>)
20213 (org-agenda-remove-restriction-lock 'noupdate)
20214 (setq restriction nil))
20215 ((and (equal selstring "") (memq c '(?s ?a ?t ?m ?L ?C ?e ?T ?M ?# ?! ?/)))
20216 (throw 'exit (cons (setq selstring (char-to-string c)) restriction)))
20217 ((and (> (length selstring) 0) (eq c ?\d))
20218 (delete-window)
20219 (org-agenda-get-restriction-and-command prefix-descriptions))
20221 ((equal c ?q) (error "Abort"))
20222 (t (error "Invalid key %c" c))))))))
20224 (defun org-run-agenda-series (name series)
20225 (org-prepare-agenda name)
20226 (let* ((org-agenda-multi t)
20227 (redo (list 'org-run-agenda-series name (list 'quote series)))
20228 (cmds (car series))
20229 (gprops (nth 1 series))
20230 match ;; The byte compiler incorrectly complains about this. Keep it!
20231 cmd type lprops)
20232 (while (setq cmd (pop cmds))
20233 (setq type (car cmd) match (nth 1 cmd) lprops (nth 2 cmd))
20234 (cond
20235 ((eq type 'agenda)
20236 (org-let2 gprops lprops
20237 '(call-interactively 'org-agenda-list)))
20238 ((eq type 'alltodo)
20239 (org-let2 gprops lprops
20240 '(call-interactively 'org-todo-list)))
20241 ((eq type 'search)
20242 (org-let2 gprops lprops
20243 '(org-search-view current-prefix-arg match)))
20244 ((eq type 'stuck)
20245 (org-let2 gprops lprops
20246 '(call-interactively 'org-agenda-list-stuck-projects)))
20247 ((eq type 'tags)
20248 (org-let2 gprops lprops
20249 '(org-tags-view current-prefix-arg match)))
20250 ((eq type 'tags-todo)
20251 (org-let2 gprops lprops
20252 '(org-tags-view '(4) match)))
20253 ((eq type 'todo)
20254 (org-let2 gprops lprops
20255 '(org-todo-list match)))
20256 ((fboundp type)
20257 (org-let2 gprops lprops
20258 '(funcall type match)))
20259 (t (error "Invalid type in command series"))))
20260 (widen)
20261 (setq org-agenda-redo-command redo)
20262 (goto-char (point-min)))
20263 (org-finalize-agenda))
20265 ;;;###autoload
20266 (defmacro org-batch-agenda (cmd-key &rest parameters)
20267 "Run an agenda command in batch mode and send the result to STDOUT.
20268 If CMD-KEY is a string of length 1, it is used as a key in
20269 `org-agenda-custom-commands' and triggers this command. If it is a
20270 longer string it is used as a tags/todo match string.
20271 Paramters are alternating variable names and values that will be bound
20272 before running the agenda command."
20273 (let (pars)
20274 (while parameters
20275 (push (list (pop parameters) (if parameters (pop parameters))) pars))
20276 (if (> (length cmd-key) 2)
20277 (eval (list 'let (nreverse pars)
20278 (list 'org-tags-view nil cmd-key)))
20279 (eval (list 'let (nreverse pars) (list 'org-agenda nil cmd-key))))
20280 (set-buffer org-agenda-buffer-name)
20281 (princ (org-encode-for-stdout (buffer-string)))))
20283 (defun org-encode-for-stdout (string)
20284 (if (fboundp 'encode-coding-string)
20285 (encode-coding-string string buffer-file-coding-system)
20286 string))
20288 (defvar org-agenda-info nil)
20290 ;;;###autoload
20291 (defmacro org-batch-agenda-csv (cmd-key &rest parameters)
20292 "Run an agenda command in batch mode and send the result to STDOUT.
20293 If CMD-KEY is a string of length 1, it is used as a key in
20294 `org-agenda-custom-commands' and triggers this command. If it is a
20295 longer string it is used as a tags/todo match string.
20296 Paramters are alternating variable names and values that will be bound
20297 before running the agenda command.
20299 The output gives a line for each selected agenda item. Each
20300 item is a list of comma-separated values, like this:
20302 category,head,type,todo,tags,date,time,extra,priority-l,priority-n
20304 category The category of the item
20305 head The headline, without TODO kwd, TAGS and PRIORITY
20306 type The type of the agenda entry, can be
20307 todo selected in TODO match
20308 tagsmatch selected in tags match
20309 diary imported from diary
20310 deadline a deadline on given date
20311 scheduled scheduled on given date
20312 timestamp entry has timestamp on given date
20313 closed entry was closed on given date
20314 upcoming-deadline warning about deadline
20315 past-scheduled forwarded scheduled item
20316 block entry has date block including g. date
20317 todo The todo keyword, if any
20318 tags All tags including inherited ones, separated by colons
20319 date The relevant date, like 2007-2-14
20320 time The time, like 15:00-16:50
20321 extra Sting with extra planning info
20322 priority-l The priority letter if any was given
20323 priority-n The computed numerical priority
20324 agenda-day The day in the agenda where this is listed"
20326 (let (pars)
20327 (while parameters
20328 (push (list (pop parameters) (if parameters (pop parameters))) pars))
20329 (push (list 'org-agenda-remove-tags t) pars)
20330 (if (> (length cmd-key) 2)
20331 (eval (list 'let (nreverse pars)
20332 (list 'org-tags-view nil cmd-key)))
20333 (eval (list 'let (nreverse pars) (list 'org-agenda nil cmd-key))))
20334 (set-buffer org-agenda-buffer-name)
20335 (let* ((lines (org-split-string (buffer-string) "\n"))
20336 line)
20337 (while (setq line (pop lines))
20338 (catch 'next
20339 (if (not (get-text-property 0 'org-category line)) (throw 'next nil))
20340 (setq org-agenda-info
20341 (org-fix-agenda-info (text-properties-at 0 line)))
20342 (princ
20343 (org-encode-for-stdout
20344 (mapconcat 'org-agenda-export-csv-mapper
20345 '(org-category txt type todo tags date time-of-day extra
20346 priority-letter priority agenda-day)
20347 ",")))
20348 (princ "\n"))))))
20350 (defun org-fix-agenda-info (props)
20351 "Make sure all properties on an agenda item have a canonical form,
20352 so the export commands can easily use it."
20353 (let (tmp re)
20354 (when (setq tmp (plist-get props 'tags))
20355 (setq props (plist-put props 'tags (mapconcat 'identity tmp ":"))))
20356 (when (setq tmp (plist-get props 'date))
20357 (if (integerp tmp) (setq tmp (calendar-gregorian-from-absolute tmp)))
20358 (let ((calendar-date-display-form '(year "-" month "-" day)))
20359 '((format "%4d, %9s %2s, %4s" dayname monthname day year))
20361 (setq tmp (calendar-date-string tmp)))
20362 (setq props (plist-put props 'date tmp)))
20363 (when (setq tmp (plist-get props 'day))
20364 (if (integerp tmp) (setq tmp (calendar-gregorian-from-absolute tmp)))
20365 (let ((calendar-date-display-form '(year "-" month "-" day)))
20366 (setq tmp (calendar-date-string tmp)))
20367 (setq props (plist-put props 'day tmp))
20368 (setq props (plist-put props 'agenda-day tmp)))
20369 (when (setq tmp (plist-get props 'txt))
20370 (when (string-match "\\[#\\([A-Z0-9]\\)\\] ?" tmp)
20371 (plist-put props 'priority-letter (match-string 1 tmp))
20372 (setq tmp (replace-match "" t t tmp)))
20373 (when (and (setq re (plist-get props 'org-todo-regexp))
20374 (setq re (concat "\\`\\.*" re " ?"))
20375 (string-match re tmp))
20376 (plist-put props 'todo (match-string 1 tmp))
20377 (setq tmp (replace-match "" t t tmp)))
20378 (plist-put props 'txt tmp)))
20379 props)
20381 (defun org-agenda-export-csv-mapper (prop)
20382 (let ((res (plist-get org-agenda-info prop)))
20383 (setq res
20384 (cond
20385 ((not res) "")
20386 ((stringp res) res)
20387 (t (prin1-to-string res))))
20388 (while (string-match "," res)
20389 (setq res (replace-match ";" t t res)))
20390 (org-trim res)))
20393 ;;;###autoload
20394 (defun org-store-agenda-views (&rest parameters)
20395 (interactive)
20396 (eval (list 'org-batch-store-agenda-views)))
20398 ;; FIXME, why is this a macro?????
20399 ;;;###autoload
20400 (defmacro org-batch-store-agenda-views (&rest parameters)
20401 "Run all custom agenda commands that have a file argument."
20402 (let ((cmds (org-agenda-normalize-custom-commands org-agenda-custom-commands))
20403 (pop-up-frames nil)
20404 (dir default-directory)
20405 pars cmd thiscmdkey files opts)
20406 (while parameters
20407 (push (list (pop parameters) (if parameters (pop parameters))) pars))
20408 (setq pars (reverse pars))
20409 (save-window-excursion
20410 (while cmds
20411 (setq cmd (pop cmds)
20412 thiscmdkey (car cmd)
20413 opts (nth 4 cmd)
20414 files (nth 5 cmd))
20415 (if (stringp files) (setq files (list files)))
20416 (when files
20417 (eval (list 'let (append org-agenda-exporter-settings opts pars)
20418 (list 'org-agenda nil thiscmdkey)))
20419 (set-buffer org-agenda-buffer-name)
20420 (while files
20421 (eval (list 'let (append org-agenda-exporter-settings opts pars)
20422 (list 'org-write-agenda
20423 (expand-file-name (pop files) dir) t))))
20424 (and (get-buffer org-agenda-buffer-name)
20425 (kill-buffer org-agenda-buffer-name)))))))
20427 (defun org-write-agenda (file &optional nosettings)
20428 "Write the current buffer (an agenda view) as a file.
20429 Depending on the extension of the file name, plain text (.txt),
20430 HTML (.html or .htm) or Postscript (.ps) is produced.
20431 If the extension is .ics, run icalendar export over all files used
20432 to construct the agenda and limit the export to entries listed in the
20433 agenda now.
20434 If NOSETTINGS is given, do not scope the settings of
20435 `org-agenda-exporter-settings' into the export commands. This is used when
20436 the settings have already been scoped and we do not wish to overrule other,
20437 higher priority settings."
20438 (interactive "FWrite agenda to file: ")
20439 (if (not (file-writable-p file))
20440 (error "Cannot write agenda to file %s" file))
20441 (cond
20442 ((string-match "\\.html?\\'" file) (require 'htmlize))
20443 ((string-match "\\.ps\\'" file) (require 'ps-print)))
20444 (org-let (if nosettings nil org-agenda-exporter-settings)
20445 '(save-excursion
20446 (save-window-excursion
20447 (cond
20448 ((string-match "\\.html?\\'" file)
20449 (set-buffer (htmlize-buffer (current-buffer)))
20451 (when (and org-agenda-export-html-style
20452 (string-match "<style>" org-agenda-export-html-style))
20453 ;; replace <style> section with org-agenda-export-html-style
20454 (goto-char (point-min))
20455 (kill-region (- (search-forward "<style") 6)
20456 (search-forward "</style>"))
20457 (insert org-agenda-export-html-style))
20458 (write-file file)
20459 (kill-buffer (current-buffer))
20460 (message "HTML written to %s" file))
20461 ((string-match "\\.ps\\'" file)
20462 (ps-print-buffer-with-faces file)
20463 (message "Postscript written to %s" file))
20464 ((string-match "\\.ics\\'" file)
20465 (let ((org-agenda-marker-table
20466 (org-create-marker-find-array
20467 (org-agenda-collect-markers)))
20468 (org-icalendar-verify-function 'org-check-agenda-marker-table)
20469 (org-combined-agenda-icalendar-file file))
20470 (apply 'org-export-icalendar 'combine (org-agenda-files))))
20472 (let ((bs (buffer-string)))
20473 (find-file file)
20474 (insert bs)
20475 (save-buffer 0)
20476 (kill-buffer (current-buffer))
20477 (message "Plain text written to %s" file))))))
20478 (set-buffer org-agenda-buffer-name)))
20480 (defun org-agenda-collect-markers ()
20481 "Collect the markers pointing to entries in the agenda buffer."
20482 (let (m markers)
20483 (save-excursion
20484 (goto-char (point-min))
20485 (while (not (eobp))
20486 (when (setq m (or (get-text-property (point) 'org-hd-marker)
20487 (get-text-property (point) 'org-marker)))
20488 (push m markers))
20489 (beginning-of-line 2)))
20490 (nreverse markers)))
20492 (defun org-create-marker-find-array (marker-list)
20493 "Create a alist of files names with all marker positions in that file."
20494 (let (f tbl m a p)
20495 (while (setq m (pop marker-list))
20496 (setq p (marker-position m)
20497 f (buffer-file-name (or (buffer-base-buffer
20498 (marker-buffer m))
20499 (marker-buffer m))))
20500 (if (setq a (assoc f tbl))
20501 (push (marker-position m) (cdr a))
20502 (push (list f p) tbl)))
20503 (mapcar (lambda (x) (setcdr x (sort (copy-sequence (cdr x)) '<)) x)
20504 tbl)))
20506 (defvar org-agenda-marker-table nil) ; dyamically scoped parameter
20507 (defun org-check-agenda-marker-table ()
20508 "Check of the current entry is on the marker list."
20509 (let ((file (buffer-file-name (or (buffer-base-buffer) (current-buffer))))
20511 (and (setq a (assoc file org-agenda-marker-table))
20512 (save-match-data
20513 (save-excursion
20514 (org-back-to-heading t)
20515 (member (point) (cdr a)))))))
20517 (defmacro org-no-read-only (&rest body)
20518 "Inhibit read-only for BODY."
20519 `(let ((inhibit-read-only t)) ,@body))
20521 (defun org-check-for-org-mode ()
20522 "Make sure current buffer is in org-mode. Error if not."
20523 (or (org-mode-p)
20524 (error "Cannot execute org-mode agenda command on buffer in %s."
20525 major-mode)))
20527 (defun org-fit-agenda-window ()
20528 "Fit the window to the buffer size."
20529 (and (memq org-agenda-window-setup '(reorganize-frame))
20530 (fboundp 'fit-window-to-buffer)
20531 (fit-window-to-buffer
20533 (floor (* (frame-height) (cdr org-agenda-window-frame-fractions)))
20534 (floor (* (frame-height) (car org-agenda-window-frame-fractions))))))
20536 ;;; Agenda file list
20538 (defun org-agenda-files (&optional unrestricted)
20539 "Get the list of agenda files.
20540 Optional UNRESTRICTED means return the full list even if a restriction
20541 is currently in place."
20542 (let ((files
20543 (cond
20544 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
20545 ((stringp org-agenda-files) (org-read-agenda-file-list))
20546 ((listp org-agenda-files) org-agenda-files)
20547 (t (error "Invalid value of `org-agenda-files'")))))
20548 (setq files (apply 'append
20549 (mapcar (lambda (f)
20550 (if (file-directory-p f)
20551 (directory-files f t
20552 org-agenda-file-regexp)
20553 (list f)))
20554 files)))
20555 (if org-agenda-skip-unavailable-files
20556 (delq nil
20557 (mapcar (function
20558 (lambda (file)
20559 (and (file-readable-p file) file)))
20560 files))
20561 files))) ; `org-check-agenda-file' will remove them from the list
20563 (defun org-edit-agenda-file-list ()
20564 "Edit the list of agenda files.
20565 Depending on setup, this either uses customize to edit the variable
20566 `org-agenda-files', or it visits the file that is holding the list. In the
20567 latter case, the buffer is set up in a way that saving it automatically kills
20568 the buffer and restores the previous window configuration."
20569 (interactive)
20570 (if (stringp org-agenda-files)
20571 (let ((cw (current-window-configuration)))
20572 (find-file org-agenda-files)
20573 (org-set-local 'org-window-configuration cw)
20574 (org-add-hook 'after-save-hook
20575 (lambda ()
20576 (set-window-configuration
20577 (prog1 org-window-configuration
20578 (kill-buffer (current-buffer))))
20579 (org-install-agenda-files-menu)
20580 (message "New agenda file list installed"))
20581 nil 'local)
20582 (message "%s" (substitute-command-keys
20583 "Edit list and finish with \\[save-buffer]")))
20584 (customize-variable 'org-agenda-files)))
20586 (defun org-store-new-agenda-file-list (list)
20587 "Set new value for the agenda file list and save it correcly."
20588 (if (stringp org-agenda-files)
20589 (let ((f org-agenda-files) b)
20590 (while (setq b (find-buffer-visiting f)) (kill-buffer b))
20591 (with-temp-file f
20592 (insert (mapconcat 'identity list "\n") "\n")))
20593 (let ((org-mode-hook nil) (default-major-mode 'fundamental-mode))
20594 (setq org-agenda-files list)
20595 (customize-save-variable 'org-agenda-files org-agenda-files))))
20597 (defun org-read-agenda-file-list ()
20598 "Read the list of agenda files from a file."
20599 (when (stringp org-agenda-files)
20600 (with-temp-buffer
20601 (insert-file-contents org-agenda-files)
20602 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*"))))
20605 ;;;###autoload
20606 (defun org-cycle-agenda-files ()
20607 "Cycle through the files in `org-agenda-files'.
20608 If the current buffer visits an agenda file, find the next one in the list.
20609 If the current buffer does not, find the first agenda file."
20610 (interactive)
20611 (let* ((fs (org-agenda-files t))
20612 (files (append fs (list (car fs))))
20613 (tcf (if buffer-file-name (file-truename buffer-file-name)))
20614 file)
20615 (unless files (error "No agenda files"))
20616 (catch 'exit
20617 (while (setq file (pop files))
20618 (if (equal (file-truename file) tcf)
20619 (when (car files)
20620 (find-file (car files))
20621 (throw 'exit t))))
20622 (find-file (car fs)))
20623 (if (buffer-base-buffer) (switch-to-buffer (buffer-base-buffer)))))
20625 (defun org-agenda-file-to-front (&optional to-end)
20626 "Move/add the current file to the top of the agenda file list.
20627 If the file is not present in the list, it is added to the front. If it is
20628 present, it is moved there. With optional argument TO-END, add/move to the
20629 end of the list."
20630 (interactive "P")
20631 (let ((org-agenda-skip-unavailable-files nil)
20632 (file-alist (mapcar (lambda (x)
20633 (cons (file-truename x) x))
20634 (org-agenda-files t)))
20635 (ctf (file-truename buffer-file-name))
20636 x had)
20637 (setq x (assoc ctf file-alist) had x)
20639 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
20640 (if to-end
20641 (setq file-alist (append (delq x file-alist) (list x)))
20642 (setq file-alist (cons x (delq x file-alist))))
20643 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
20644 (org-install-agenda-files-menu)
20645 (message "File %s to %s of agenda file list"
20646 (if had "moved" "added") (if to-end "end" "front"))))
20648 (defun org-remove-file (&optional file)
20649 "Remove current file from the list of files in variable `org-agenda-files'.
20650 These are the files which are being checked for agenda entries.
20651 Optional argument FILE means, use this file instead of the current."
20652 (interactive)
20653 (let* ((org-agenda-skip-unavailable-files nil)
20654 (file (or file buffer-file-name))
20655 (true-file (file-truename file))
20656 (afile (abbreviate-file-name file))
20657 (files (delq nil (mapcar
20658 (lambda (x)
20659 (if (equal true-file
20660 (file-truename x))
20661 nil x))
20662 (org-agenda-files t)))))
20663 (if (not (= (length files) (length (org-agenda-files t))))
20664 (progn
20665 (org-store-new-agenda-file-list files)
20666 (org-install-agenda-files-menu)
20667 (message "Removed file: %s" afile))
20668 (message "File was not in list: %s (not removed)" afile))))
20670 (defun org-file-menu-entry (file)
20671 (vector file (list 'find-file file) t))
20673 (defun org-check-agenda-file (file)
20674 "Make sure FILE exists. If not, ask user what to do."
20675 (when (not (file-exists-p file))
20676 (message "non-existent file %s. [R]emove from list or [A]bort?"
20677 (abbreviate-file-name file))
20678 (let ((r (downcase (read-char-exclusive))))
20679 (cond
20680 ((equal r ?r)
20681 (org-remove-file file)
20682 (throw 'nextfile t))
20683 (t (error "Abort"))))))
20685 ;;; Agenda prepare and finalize
20687 (defvar org-agenda-multi nil) ; dynammically scoped
20688 (defvar org-agenda-buffer-name "*Org Agenda*")
20689 (defvar org-pre-agenda-window-conf nil)
20690 (defvar org-agenda-name nil)
20691 (defun org-prepare-agenda (&optional name)
20692 (setq org-todo-keywords-for-agenda nil)
20693 (setq org-done-keywords-for-agenda nil)
20694 (if org-agenda-multi
20695 (progn
20696 (setq buffer-read-only nil)
20697 (goto-char (point-max))
20698 (unless (or (bobp) org-agenda-compact-blocks)
20699 (insert "\n" (make-string (window-width) ?=) "\n"))
20700 (narrow-to-region (point) (point-max)))
20701 (org-agenda-reset-markers)
20702 (org-prepare-agenda-buffers (org-agenda-files))
20703 (setq org-todo-keywords-for-agenda
20704 (org-uniquify org-todo-keywords-for-agenda))
20705 (setq org-done-keywords-for-agenda
20706 (org-uniquify org-done-keywords-for-agenda))
20707 (let* ((abuf (get-buffer-create org-agenda-buffer-name))
20708 (awin (get-buffer-window abuf)))
20709 (cond
20710 ((equal (current-buffer) abuf) nil)
20711 (awin (select-window awin))
20712 ((not (setq org-pre-agenda-window-conf (current-window-configuration))))
20713 ((equal org-agenda-window-setup 'current-window)
20714 (switch-to-buffer abuf))
20715 ((equal org-agenda-window-setup 'other-window)
20716 (org-switch-to-buffer-other-window abuf))
20717 ((equal org-agenda-window-setup 'other-frame)
20718 (switch-to-buffer-other-frame abuf))
20719 ((equal org-agenda-window-setup 'reorganize-frame)
20720 (delete-other-windows)
20721 (org-switch-to-buffer-other-window abuf))))
20722 (setq buffer-read-only nil)
20723 (erase-buffer)
20724 (org-agenda-mode)
20725 (and name (not org-agenda-name)
20726 (org-set-local 'org-agenda-name name)))
20727 (setq buffer-read-only nil))
20729 (defun org-finalize-agenda ()
20730 "Finishing touch for the agenda buffer, called just before displaying it."
20731 (unless org-agenda-multi
20732 (save-excursion
20733 (let ((inhibit-read-only t))
20734 (goto-char (point-min))
20735 (while (org-activate-bracket-links (point-max))
20736 (add-text-properties (match-beginning 0) (match-end 0)
20737 '(face org-link)))
20738 (org-agenda-align-tags)
20739 (unless org-agenda-with-colors
20740 (remove-text-properties (point-min) (point-max) '(face nil))))
20741 (if (and (boundp 'org-overriding-columns-format)
20742 org-overriding-columns-format)
20743 (org-set-local 'org-overriding-columns-format
20744 org-overriding-columns-format))
20745 (if (and (boundp 'org-agenda-view-columns-initially)
20746 org-agenda-view-columns-initially)
20747 (org-agenda-columns))
20748 (when org-agenda-fontify-priorities
20749 (org-fontify-priorities))
20750 (run-hooks 'org-finalize-agenda-hook)
20751 (setq org-agenda-type (get-text-property (point) 'org-agenda-type))
20754 (defun org-fontify-priorities ()
20755 "Make highest priority lines bold, and lowest italic."
20756 (interactive)
20757 (mapc (lambda (o) (if (eq (org-overlay-get o 'org-type) 'org-priority)
20758 (org-delete-overlay o)))
20759 (org-overlays-in (point-min) (point-max)))
20760 (save-excursion
20761 (let ((inhibit-read-only t)
20762 b e p ov h l)
20763 (goto-char (point-min))
20764 (while (re-search-forward "\\[#\\(.\\)\\]" nil t)
20765 (setq h (or (get-char-property (point) 'org-highest-priority)
20766 org-highest-priority)
20767 l (or (get-char-property (point) 'org-lowest-priority)
20768 org-lowest-priority)
20769 p (string-to-char (match-string 1))
20770 b (match-beginning 0) e (point-at-eol)
20771 ov (org-make-overlay b e))
20772 (org-overlay-put
20773 ov 'face
20774 (cond ((listp org-agenda-fontify-priorities)
20775 (cdr (assoc p org-agenda-fontify-priorities)))
20776 ((equal p l) 'italic)
20777 ((equal p h) 'bold)))
20778 (org-overlay-put ov 'org-type 'org-priority)))))
20780 (defun org-prepare-agenda-buffers (files)
20781 "Create buffers for all agenda files, protect archived trees and comments."
20782 (interactive)
20783 (let ((pa '(:org-archived t))
20784 (pc '(:org-comment t))
20785 (pall '(:org-archived t :org-comment t))
20786 (inhibit-read-only t)
20787 (rea (concat ":" org-archive-tag ":"))
20788 bmp file re)
20789 (save-excursion
20790 (save-restriction
20791 (while (setq file (pop files))
20792 (if (bufferp file)
20793 (set-buffer file)
20794 (org-check-agenda-file file)
20795 (set-buffer (org-get-agenda-file-buffer file)))
20796 (widen)
20797 (setq bmp (buffer-modified-p))
20798 (org-refresh-category-properties)
20799 (setq org-todo-keywords-for-agenda
20800 (append org-todo-keywords-for-agenda org-todo-keywords-1))
20801 (setq org-done-keywords-for-agenda
20802 (append org-done-keywords-for-agenda org-done-keywords))
20803 (save-excursion
20804 (remove-text-properties (point-min) (point-max) pall)
20805 (when org-agenda-skip-archived-trees
20806 (goto-char (point-min))
20807 (while (re-search-forward rea nil t)
20808 (if (org-on-heading-p t)
20809 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
20810 (goto-char (point-min))
20811 (setq re (concat "^\\*+ +" org-comment-string "\\>"))
20812 (while (re-search-forward re nil t)
20813 (add-text-properties
20814 (match-beginning 0) (org-end-of-subtree t) pc)))
20815 (set-buffer-modified-p bmp))))))
20817 (defvar org-agenda-skip-function nil
20818 "Function to be called at each match during agenda construction.
20819 If this function returns nil, the current match should not be skipped.
20820 Otherwise, the function must return a position from where the search
20821 should be continued.
20822 This may also be a Lisp form, it will be evaluated.
20823 Never set this variable using `setq' or so, because then it will apply
20824 to all future agenda commands. Instead, bind it with `let' to scope
20825 it dynamically into the agenda-constructing command. A good way to set
20826 it is through options in org-agenda-custom-commands.")
20828 (defun org-agenda-skip ()
20829 "Throw to `:skip' in places that should be skipped.
20830 Also moves point to the end of the skipped region, so that search can
20831 continue from there."
20832 (let ((p (point-at-bol)) to fp)
20833 (and org-agenda-skip-archived-trees
20834 (get-text-property p :org-archived)
20835 (org-end-of-subtree t)
20836 (throw :skip t))
20837 (and (get-text-property p :org-comment)
20838 (org-end-of-subtree t)
20839 (throw :skip t))
20840 (if (equal (char-after p) ?#) (throw :skip t))
20841 (when (and (or (setq fp (functionp org-agenda-skip-function))
20842 (consp org-agenda-skip-function))
20843 (setq to (save-excursion
20844 (save-match-data
20845 (if fp
20846 (funcall org-agenda-skip-function)
20847 (eval org-agenda-skip-function))))))
20848 (goto-char to)
20849 (throw :skip t))))
20851 (defvar org-agenda-markers nil
20852 "List of all currently active markers created by `org-agenda'.")
20853 (defvar org-agenda-last-marker-time (time-to-seconds (current-time))
20854 "Creation time of the last agenda marker.")
20856 (defun org-agenda-new-marker (&optional pos)
20857 "Return a new agenda marker.
20858 Org-mode keeps a list of these markers and resets them when they are
20859 no longer in use."
20860 (let ((m (copy-marker (or pos (point)))))
20861 (setq org-agenda-last-marker-time (time-to-seconds (current-time)))
20862 (push m org-agenda-markers)
20865 (defun org-agenda-reset-markers ()
20866 "Reset markers created by `org-agenda'."
20867 (while org-agenda-markers
20868 (move-marker (pop org-agenda-markers) nil)))
20870 (defun org-get-agenda-file-buffer (file)
20871 "Get a buffer visiting FILE. If the buffer needs to be created, add
20872 it to the list of buffers which might be released later."
20873 (let ((buf (org-find-base-buffer-visiting file)))
20874 (if buf
20875 buf ; just return it
20876 ;; Make a new buffer and remember it
20877 (setq buf (find-file-noselect file))
20878 (if buf (push buf org-agenda-new-buffers))
20879 buf)))
20881 (defun org-release-buffers (blist)
20882 "Release all buffers in list, asking the user for confirmation when needed.
20883 When a buffer is unmodified, it is just killed. When modified, it is saved
20884 \(if the user agrees) and then killed."
20885 (let (buf file)
20886 (while (setq buf (pop blist))
20887 (setq file (buffer-file-name buf))
20888 (when (and (buffer-modified-p buf)
20889 file
20890 (y-or-n-p (format "Save file %s? " file)))
20891 (with-current-buffer buf (save-buffer)))
20892 (kill-buffer buf))))
20894 (defun org-get-category (&optional pos)
20895 "Get the category applying to position POS."
20896 (get-text-property (or pos (point)) 'org-category))
20898 ;;; Agenda timeline
20900 (defvar org-agenda-only-exact-dates nil) ; dynamically scoped
20902 (defun org-timeline (&optional include-all)
20903 "Show a time-sorted view of the entries in the current org file.
20904 Only entries with a time stamp of today or later will be listed. With
20905 \\[universal-argument] prefix, all unfinished TODO items will also be shown,
20906 under the current date.
20907 If the buffer contains an active region, only check the region for
20908 dates."
20909 (interactive "P")
20910 (require 'calendar)
20911 (org-compile-prefix-format 'timeline)
20912 (org-set-sorting-strategy 'timeline)
20913 (let* ((dopast t)
20914 (dotodo include-all)
20915 (doclosed org-agenda-show-log)
20916 (entry buffer-file-name)
20917 (date (calendar-current-date))
20918 (beg (if (org-region-active-p) (region-beginning) (point-min)))
20919 (end (if (org-region-active-p) (region-end) (point-max)))
20920 (day-numbers (org-get-all-dates beg end 'no-ranges
20921 t doclosed ; always include today
20922 org-timeline-show-empty-dates))
20923 (org-deadline-warning-days 0)
20924 (org-agenda-only-exact-dates t)
20925 (today (time-to-days (current-time)))
20926 (past t)
20927 args
20928 s e rtn d emptyp)
20929 (setq org-agenda-redo-command
20930 (list 'progn
20931 (list 'org-switch-to-buffer-other-window (current-buffer))
20932 (list 'org-timeline (list 'quote include-all))))
20933 (if (not dopast)
20934 ;; Remove past dates from the list of dates.
20935 (setq day-numbers (delq nil (mapcar (lambda(x)
20936 (if (>= x today) x nil))
20937 day-numbers))))
20938 (org-prepare-agenda (concat "Timeline "
20939 (file-name-nondirectory buffer-file-name)))
20940 (if doclosed (push :closed args))
20941 (push :timestamp args)
20942 (push :deadline args)
20943 (push :scheduled args)
20944 (push :sexp args)
20945 (if dotodo (push :todo args))
20946 (while (setq d (pop day-numbers))
20947 (if (and (listp d) (eq (car d) :omitted))
20948 (progn
20949 (setq s (point))
20950 (insert (format "\n[... %d empty days omitted]\n\n" (cdr d)))
20951 (put-text-property s (1- (point)) 'face 'org-agenda-structure))
20952 (if (listp d) (setq d (car d) emptyp t) (setq emptyp nil))
20953 (if (and (>= d today)
20954 dopast
20955 past)
20956 (progn
20957 (setq past nil)
20958 (insert (make-string 79 ?-) "\n")))
20959 (setq date (calendar-gregorian-from-absolute d))
20960 (setq s (point))
20961 (setq rtn (and (not emptyp)
20962 (apply 'org-agenda-get-day-entries entry
20963 date args)))
20964 (if (or rtn (equal d today) org-timeline-show-empty-dates)
20965 (progn
20966 (insert
20967 (if (stringp org-agenda-format-date)
20968 (format-time-string org-agenda-format-date
20969 (org-time-from-absolute date))
20970 (funcall org-agenda-format-date date))
20971 "\n")
20972 (put-text-property s (1- (point)) 'face 'org-agenda-structure)
20973 (put-text-property s (1- (point)) 'org-date-line t)
20974 (if (equal d today)
20975 (put-text-property s (1- (point)) 'org-today t))
20976 (and rtn (insert (org-finalize-agenda-entries rtn) "\n"))
20977 (put-text-property s (1- (point)) 'day d)))))
20978 (goto-char (point-min))
20979 (goto-char (or (text-property-any (point-min) (point-max) 'org-today t)
20980 (point-min)))
20981 (add-text-properties (point-min) (point-max) '(org-agenda-type timeline))
20982 (org-finalize-agenda)
20983 (setq buffer-read-only t)))
20985 (defun org-get-all-dates (beg end &optional no-ranges force-today inactive empty pre-re)
20986 "Return a list of all relevant day numbers from BEG to END buffer positions.
20987 If NO-RANGES is non-nil, include only the start and end dates of a range,
20988 not every single day in the range. If FORCE-TODAY is non-nil, make
20989 sure that TODAY is included in the list. If INACTIVE is non-nil, also
20990 inactive time stamps (those in square brackets) are included.
20991 When EMPTY is non-nil, also include days without any entries."
20992 (let ((re (concat
20993 (if pre-re pre-re "")
20994 (if inactive org-ts-regexp-both org-ts-regexp)))
20995 dates dates1 date day day1 day2 ts1 ts2)
20996 (if force-today
20997 (setq dates (list (time-to-days (current-time)))))
20998 (save-excursion
20999 (goto-char beg)
21000 (while (re-search-forward re end t)
21001 (setq day (time-to-days (org-time-string-to-time
21002 (substring (match-string 1) 0 10))))
21003 (or (memq day dates) (push day dates)))
21004 (unless no-ranges
21005 (goto-char beg)
21006 (while (re-search-forward org-tr-regexp end t)
21007 (setq ts1 (substring (match-string 1) 0 10)
21008 ts2 (substring (match-string 2) 0 10)
21009 day1 (time-to-days (org-time-string-to-time ts1))
21010 day2 (time-to-days (org-time-string-to-time ts2)))
21011 (while (< (setq day1 (1+ day1)) day2)
21012 (or (memq day1 dates) (push day1 dates)))))
21013 (setq dates (sort dates '<))
21014 (when empty
21015 (while (setq day (pop dates))
21016 (setq day2 (car dates))
21017 (push day dates1)
21018 (when (and day2 empty)
21019 (if (or (eq empty t)
21020 (and (numberp empty) (<= (- day2 day) empty)))
21021 (while (< (setq day (1+ day)) day2)
21022 (push (list day) dates1))
21023 (push (cons :omitted (- day2 day)) dates1))))
21024 (setq dates (nreverse dates1)))
21025 dates)))
21027 ;;; Agenda Daily/Weekly
21029 (defvar org-agenda-overriding-arguments nil) ; dynamically scoped parameter
21030 (defvar org-agenda-start-day nil) ; dynamically scoped parameter
21031 (defvar org-agenda-last-arguments nil
21032 "The arguments of the previous call to org-agenda")
21033 (defvar org-starting-day nil) ; local variable in the agenda buffer
21034 (defvar org-agenda-span nil) ; local variable in the agenda buffer
21035 (defvar org-include-all-loc nil) ; local variable
21036 (defvar org-agenda-remove-date nil) ; dynamically scoped FIXME: not used???
21038 ;;;###autoload
21039 (defun org-agenda-list (&optional include-all start-day ndays)
21040 "Produce a daily/weekly view from all files in variable `org-agenda-files'.
21041 The view will be for the current day or week, but from the overview buffer
21042 you will be able to go to other days/weeks.
21044 With one \\[universal-argument] prefix argument INCLUDE-ALL,
21045 all unfinished TODO items will also be shown, before the agenda.
21046 This feature is considered obsolete, please use the TODO list or a block
21047 agenda instead.
21049 With a numeric prefix argument in an interactive call, the agenda will
21050 span INCLUDE-ALL days. Lisp programs should instead specify NDAYS to change
21051 the number of days. NDAYS defaults to `org-agenda-ndays'.
21053 START-DAY defaults to TODAY, or to the most recent match for the weekday
21054 given in `org-agenda-start-on-weekday'."
21055 (interactive "P")
21056 (if (and (integerp include-all) (> include-all 0))
21057 (setq ndays include-all include-all nil))
21058 (setq ndays (or ndays org-agenda-ndays)
21059 start-day (or start-day org-agenda-start-day))
21060 (if org-agenda-overriding-arguments
21061 (setq include-all (car org-agenda-overriding-arguments)
21062 start-day (nth 1 org-agenda-overriding-arguments)
21063 ndays (nth 2 org-agenda-overriding-arguments)))
21064 (if (stringp start-day)
21065 ;; Convert to an absolute day number
21066 (setq start-day (time-to-days (org-read-date nil t start-day))))
21067 (setq org-agenda-last-arguments (list include-all start-day ndays))
21068 (org-compile-prefix-format 'agenda)
21069 (org-set-sorting-strategy 'agenda)
21070 (require 'calendar)
21071 (let* ((org-agenda-start-on-weekday
21072 (if (or (equal ndays 7) (and (null ndays) (equal 7 org-agenda-ndays)))
21073 org-agenda-start-on-weekday nil))
21074 (thefiles (org-agenda-files))
21075 (files thefiles)
21076 (today (time-to-days
21077 (time-subtract (current-time)
21078 (list 0 (* 3600 org-extend-today-until) 0))))
21079 (sd (or start-day today))
21080 (start (if (or (null org-agenda-start-on-weekday)
21081 (< org-agenda-ndays 7))
21083 (let* ((nt (calendar-day-of-week
21084 (calendar-gregorian-from-absolute sd)))
21085 (n1 org-agenda-start-on-weekday)
21086 (d (- nt n1)))
21087 (- sd (+ (if (< d 0) 7 0) d)))))
21088 (day-numbers (list start))
21089 (day-cnt 0)
21090 (inhibit-redisplay (not debug-on-error))
21091 s e rtn rtnall file date d start-pos end-pos todayp nd)
21092 (setq org-agenda-redo-command
21093 (list 'org-agenda-list (list 'quote include-all) start-day ndays))
21094 ;; Make the list of days
21095 (setq ndays (or ndays org-agenda-ndays)
21096 nd ndays)
21097 (while (> ndays 1)
21098 (push (1+ (car day-numbers)) day-numbers)
21099 (setq ndays (1- ndays)))
21100 (setq day-numbers (nreverse day-numbers))
21101 (org-prepare-agenda "Day/Week")
21102 (org-set-local 'org-starting-day (car day-numbers))
21103 (org-set-local 'org-include-all-loc include-all)
21104 (org-set-local 'org-agenda-span
21105 (org-agenda-ndays-to-span nd))
21106 (when (and (or include-all org-agenda-include-all-todo)
21107 (member today day-numbers))
21108 (setq files thefiles
21109 rtnall nil)
21110 (while (setq file (pop files))
21111 (catch 'nextfile
21112 (org-check-agenda-file file)
21113 (setq date (calendar-gregorian-from-absolute today)
21114 rtn (org-agenda-get-day-entries
21115 file date :todo))
21116 (setq rtnall (append rtnall rtn))))
21117 (when rtnall
21118 (insert "ALL CURRENTLY OPEN TODO ITEMS:\n")
21119 (add-text-properties (point-min) (1- (point))
21120 (list 'face 'org-agenda-structure))
21121 (insert (org-finalize-agenda-entries rtnall) "\n")))
21122 (unless org-agenda-compact-blocks
21123 (setq s (point))
21124 (insert (capitalize (symbol-name (org-agenda-ndays-to-span nd)))
21125 "-agenda:\n")
21126 (add-text-properties s (1- (point)) (list 'face 'org-agenda-structure
21127 'org-date-line t)))
21128 (while (setq d (pop day-numbers))
21129 (setq date (calendar-gregorian-from-absolute d)
21130 s (point))
21131 (if (or (setq todayp (= d today))
21132 (and (not start-pos) (= d sd)))
21133 (setq start-pos (point))
21134 (if (and start-pos (not end-pos))
21135 (setq end-pos (point))))
21136 (setq files thefiles
21137 rtnall nil)
21138 (while (setq file (pop files))
21139 (catch 'nextfile
21140 (org-check-agenda-file file)
21141 (if org-agenda-show-log
21142 (setq rtn (org-agenda-get-day-entries
21143 file date
21144 :deadline :scheduled :timestamp :sexp :closed))
21145 (setq rtn (org-agenda-get-day-entries
21146 file date
21147 :deadline :scheduled :sexp :timestamp)))
21148 (setq rtnall (append rtnall rtn))))
21149 (if org-agenda-include-diary
21150 (progn
21151 (require 'diary-lib)
21152 (setq rtn (org-get-entries-from-diary date))
21153 (setq rtnall (append rtnall rtn))))
21154 (if (or rtnall org-agenda-show-all-dates)
21155 (progn
21156 (setq day-cnt (1+ day-cnt))
21157 (insert
21158 (if (stringp org-agenda-format-date)
21159 (format-time-string org-agenda-format-date
21160 (org-time-from-absolute date))
21161 (funcall org-agenda-format-date date))
21162 "\n")
21163 (put-text-property s (1- (point)) 'face 'org-agenda-structure)
21164 (put-text-property s (1- (point)) 'org-date-line t)
21165 (put-text-property s (1- (point)) 'org-day-cnt day-cnt)
21166 (if todayp (put-text-property s (1- (point)) 'org-today t))
21167 (if rtnall (insert
21168 (org-finalize-agenda-entries
21169 (org-agenda-add-time-grid-maybe
21170 rtnall nd todayp))
21171 "\n"))
21172 (put-text-property s (1- (point)) 'day d)
21173 (put-text-property s (1- (point)) 'org-day-cnt day-cnt))))
21174 (goto-char (point-min))
21175 (org-fit-agenda-window)
21176 (unless (and (pos-visible-in-window-p (point-min))
21177 (pos-visible-in-window-p (point-max)))
21178 (goto-char (1- (point-max)))
21179 (recenter -1)
21180 (if (not (pos-visible-in-window-p (or start-pos 1)))
21181 (progn
21182 (goto-char (or start-pos 1))
21183 (recenter 1))))
21184 (goto-char (or start-pos 1))
21185 (add-text-properties (point-min) (point-max) '(org-agenda-type agenda))
21186 (org-finalize-agenda)
21187 (setq buffer-read-only t)
21188 (message "")))
21190 (defun org-agenda-ndays-to-span (n)
21191 (cond ((< n 7) 'day) ((= n 7) 'week) ((< n 32) 'month) (t 'year)))
21193 ;;; Agenda word search
21195 (defvar org-agenda-search-history nil)
21197 ;;;###autoload
21198 (defun org-search-view (&optional arg string)
21199 "Show all entries that contain words or regular expressions.
21200 If the first character of the search string is an asterisks,
21201 search only the headlines.
21203 The search string is broken into \"words\" by splitting at whitespace.
21204 The individual words are then interpreted as a boolean expression with
21205 logical AND. Words prefixed with a minus must not occur in the entry.
21206 Words without a prefix or prefixed with a plus must occur in the entry.
21207 Matching is case-insensitive and the words are enclosed by word delimiters.
21209 Words enclosed by curly braces are interpreted as regular expressions
21210 that must or must not match in the entry.
21212 This command searches the agenda files, and in addition the files listed
21213 in `org-agenda-text-search-extra-files'."
21214 (interactive "P")
21215 (org-compile-prefix-format 'search)
21216 (org-set-sorting-strategy 'search)
21217 (org-prepare-agenda "SEARCH")
21218 (let* ((props (list 'face nil
21219 'done-face 'org-done
21220 'org-not-done-regexp org-not-done-regexp
21221 'org-todo-regexp org-todo-regexp
21222 'mouse-face 'highlight
21223 'keymap org-agenda-keymap
21224 'help-echo (format "mouse-2 or RET jump to location")))
21225 regexp rtn rtnall files file pos
21226 marker priority category tags c neg re
21227 ee txt beg end words regexps+ regexps- hdl-only buffer beg1 str)
21228 (unless (and (not arg)
21229 (stringp string)
21230 (string-match "\\S-" string))
21231 (setq string (read-string "[+-]Word/{Regexp} ...: "
21232 (cond
21233 ((integerp arg) (cons string arg))
21234 (arg string))
21235 'org-agenda-search-history)))
21236 (setq org-agenda-redo-command
21237 (list 'org-search-view 'current-prefix-arg string))
21238 (setq org-agenda-query-string string)
21240 (if (equal (string-to-char string) ?*)
21241 (setq hdl-only t
21242 words (substring string 1))
21243 (setq words string))
21244 (setq words (org-split-string words))
21245 (mapc (lambda (w)
21246 (setq c (string-to-char w))
21247 (if (equal c ?-)
21248 (setq neg t w (substring w 1))
21249 (if (equal c ?+)
21250 (setq neg nil w (substring w 1))
21251 (setq neg nil)))
21252 (if (string-match "\\`{.*}\\'" w)
21253 (setq re (substring w 1 -1))
21254 (setq re (concat "\\<" (regexp-quote (downcase w)) "\\>")))
21255 (if neg (push re regexps-) (push re regexps+)))
21256 words)
21257 (setq regexps+ (sort regexps+ (lambda (a b) (> (length a) (length b)))))
21258 (if (not regexps+)
21259 (setq regexp (concat "^" org-outline-regexp))
21260 (setq regexp (pop regexps+))
21261 (if hdl-only (setq regexp (concat "^" org-outline-regexp ".*?"
21262 regexp))))
21263 (setq files (append (org-agenda-files) org-agenda-text-search-extra-files)
21264 rtnall nil)
21265 (while (setq file (pop files))
21266 (setq ee nil)
21267 (catch 'nextfile
21268 (org-check-agenda-file file)
21269 (setq buffer (if (file-exists-p file)
21270 (org-get-agenda-file-buffer file)
21271 (error "No such file %s" file)))
21272 (if (not buffer)
21273 ;; If file does not exist, make sure an error message is sent
21274 (setq rtn (list (format "ORG-AGENDA-ERROR: No such org-file %s"
21275 file))))
21276 (with-current-buffer buffer
21277 (unless (org-mode-p)
21278 (error "Agenda file %s is not in `org-mode'" file))
21279 (let ((case-fold-search t))
21280 (save-excursion
21281 (save-restriction
21282 (if org-agenda-restrict
21283 (narrow-to-region org-agenda-restrict-begin
21284 org-agenda-restrict-end)
21285 (widen))
21286 (goto-char (point-min))
21287 (unless (or (org-on-heading-p)
21288 (outline-next-heading))
21289 (throw 'nextfile t))
21290 (goto-char (max (point-min) (1- (point))))
21291 (while (re-search-forward regexp nil t)
21292 (org-back-to-heading t)
21293 (skip-chars-forward "* ")
21294 (setq beg (point-at-bol)
21295 beg1 (point)
21296 end (progn (outline-next-heading) (point)))
21297 (catch :skip
21298 (goto-char beg)
21299 (org-agenda-skip)
21300 (setq str (buffer-substring-no-properties
21301 (point-at-bol)
21302 (if hdl-only (point-at-eol) end)))
21303 (mapc (lambda (wr) (when (string-match wr str)
21304 (goto-char (1- end))
21305 (throw :skip t)))
21306 regexps-)
21307 (mapc (lambda (wr) (unless (string-match wr str)
21308 (goto-char (1- end))
21309 (throw :skip t)))
21310 regexps+)
21311 (goto-char beg)
21312 (setq marker (org-agenda-new-marker (point))
21313 category (org-get-category)
21314 tags (org-get-tags-at (point))
21315 txt (org-format-agenda-item
21317 (buffer-substring-no-properties
21318 beg1 (point-at-eol))
21319 category tags))
21320 (org-add-props txt props
21321 'org-marker marker 'org-hd-marker marker
21322 'priority 1000 'org-category category
21323 'type "search")
21324 (push txt ee)
21325 (goto-char (1- end)))))))))
21326 (setq rtn (nreverse ee))
21327 (setq rtnall (append rtnall rtn)))
21328 (if org-agenda-overriding-header
21329 (insert (org-add-props (copy-sequence org-agenda-overriding-header)
21330 nil 'face 'org-agenda-structure) "\n")
21331 (insert "Search words: ")
21332 (add-text-properties (point-min) (1- (point))
21333 (list 'face 'org-agenda-structure))
21334 (setq pos (point))
21335 (insert string "\n")
21336 (add-text-properties pos (1- (point)) (list 'face 'org-warning))
21337 (setq pos (point))
21338 (unless org-agenda-multi
21339 (insert "Press `[', `]' to add/sub word, `{', `}' to add/sub regexp, `C-u r' to edit\n")
21340 (add-text-properties pos (1- (point))
21341 (list 'face 'org-agenda-structure))))
21342 (when rtnall
21343 (insert (org-finalize-agenda-entries rtnall) "\n"))
21344 (goto-char (point-min))
21345 (org-fit-agenda-window)
21346 (add-text-properties (point-min) (point-max) '(org-agenda-type search))
21347 (org-finalize-agenda)
21348 (setq buffer-read-only t)))
21350 ;;; Agenda TODO list
21352 (defvar org-select-this-todo-keyword nil)
21353 (defvar org-last-arg nil)
21355 ;;;###autoload
21356 (defun org-todo-list (arg)
21357 "Show all TODO entries from all agenda file in a single list.
21358 The prefix arg can be used to select a specific TODO keyword and limit
21359 the list to these. When using \\[universal-argument], you will be prompted
21360 for a keyword. A numeric prefix directly selects the Nth keyword in
21361 `org-todo-keywords-1'."
21362 (interactive "P")
21363 (require 'calendar)
21364 (org-compile-prefix-format 'todo)
21365 (org-set-sorting-strategy 'todo)
21366 (org-prepare-agenda "TODO")
21367 (let* ((today (time-to-days (current-time)))
21368 (date (calendar-gregorian-from-absolute today))
21369 (kwds org-todo-keywords-for-agenda)
21370 (completion-ignore-case t)
21371 (org-select-this-todo-keyword
21372 (if (stringp arg) arg
21373 (and arg (integerp arg) (> arg 0)
21374 (nth (1- arg) kwds))))
21375 rtn rtnall files file pos)
21376 (when (equal arg '(4))
21377 (setq org-select-this-todo-keyword
21378 (completing-read "Keyword (or KWD1|K2D2|...): "
21379 (mapcar 'list kwds) nil nil)))
21380 (and (equal 0 arg) (setq org-select-this-todo-keyword nil))
21381 (org-set-local 'org-last-arg arg)
21382 (setq org-agenda-redo-command
21383 '(org-todo-list (or current-prefix-arg org-last-arg)))
21384 (setq files (org-agenda-files)
21385 rtnall nil)
21386 (while (setq file (pop files))
21387 (catch 'nextfile
21388 (org-check-agenda-file file)
21389 (setq rtn (org-agenda-get-day-entries file date :todo))
21390 (setq rtnall (append rtnall rtn))))
21391 (if org-agenda-overriding-header
21392 (insert (org-add-props (copy-sequence org-agenda-overriding-header)
21393 nil 'face 'org-agenda-structure) "\n")
21394 (insert "Global list of TODO items of type: ")
21395 (add-text-properties (point-min) (1- (point))
21396 (list 'face 'org-agenda-structure))
21397 (setq pos (point))
21398 (insert (or org-select-this-todo-keyword "ALL") "\n")
21399 (add-text-properties pos (1- (point)) (list 'face 'org-warning))
21400 (setq pos (point))
21401 (unless org-agenda-multi
21402 (insert "Available with `N r': (0)ALL")
21403 (let ((n 0) s)
21404 (mapc (lambda (x)
21405 (setq s (format "(%d)%s" (setq n (1+ n)) x))
21406 (if (> (+ (current-column) (string-width s) 1) (frame-width))
21407 (insert "\n "))
21408 (insert " " s))
21409 kwds))
21410 (insert "\n"))
21411 (add-text-properties pos (1- (point)) (list 'face 'org-agenda-structure)))
21412 (when rtnall
21413 (insert (org-finalize-agenda-entries rtnall) "\n"))
21414 (goto-char (point-min))
21415 (org-fit-agenda-window)
21416 (add-text-properties (point-min) (point-max) '(org-agenda-type todo))
21417 (org-finalize-agenda)
21418 (setq buffer-read-only t)))
21420 ;;; Agenda tags match
21422 ;;;###autoload
21423 (defun org-tags-view (&optional todo-only match)
21424 "Show all headlines for all `org-agenda-files' matching a TAGS criterion.
21425 The prefix arg TODO-ONLY limits the search to TODO entries."
21426 (interactive "P")
21427 (org-compile-prefix-format 'tags)
21428 (org-set-sorting-strategy 'tags)
21429 (let* ((org-tags-match-list-sublevels
21430 (if todo-only t org-tags-match-list-sublevels))
21431 (completion-ignore-case t)
21432 rtn rtnall files file pos matcher
21433 buffer)
21434 (setq matcher (org-make-tags-matcher match)
21435 match (car matcher) matcher (cdr matcher))
21436 (org-prepare-agenda (concat "TAGS " match))
21437 (setq org-agenda-query-string match)
21438 (setq org-agenda-redo-command
21439 (list 'org-tags-view (list 'quote todo-only)
21440 (list 'if 'current-prefix-arg nil 'org-agenda-query-string)))
21441 (setq files (org-agenda-files)
21442 rtnall nil)
21443 (while (setq file (pop files))
21444 (catch 'nextfile
21445 (org-check-agenda-file file)
21446 (setq buffer (if (file-exists-p file)
21447 (org-get-agenda-file-buffer file)
21448 (error "No such file %s" file)))
21449 (if (not buffer)
21450 ;; If file does not exist, merror message to agenda
21451 (setq rtn (list
21452 (format "ORG-AGENDA-ERROR: No such org-file %s" file))
21453 rtnall (append rtnall rtn))
21454 (with-current-buffer buffer
21455 (unless (org-mode-p)
21456 (error "Agenda file %s is not in `org-mode'" file))
21457 (save-excursion
21458 (save-restriction
21459 (if org-agenda-restrict
21460 (narrow-to-region org-agenda-restrict-begin
21461 org-agenda-restrict-end)
21462 (widen))
21463 (setq rtn (org-scan-tags 'agenda matcher todo-only))
21464 (setq rtnall (append rtnall rtn))))))))
21465 (if org-agenda-overriding-header
21466 (insert (org-add-props (copy-sequence org-agenda-overriding-header)
21467 nil 'face 'org-agenda-structure) "\n")
21468 (insert "Headlines with TAGS match: ")
21469 (add-text-properties (point-min) (1- (point))
21470 (list 'face 'org-agenda-structure))
21471 (setq pos (point))
21472 (insert match "\n")
21473 (add-text-properties pos (1- (point)) (list 'face 'org-warning))
21474 (setq pos (point))
21475 (unless org-agenda-multi
21476 (insert "Press `C-u r' to search again with new search string\n"))
21477 (add-text-properties pos (1- (point)) (list 'face 'org-agenda-structure)))
21478 (when rtnall
21479 (insert (org-finalize-agenda-entries rtnall) "\n"))
21480 (goto-char (point-min))
21481 (org-fit-agenda-window)
21482 (add-text-properties (point-min) (point-max) '(org-agenda-type tags))
21483 (org-finalize-agenda)
21484 (setq buffer-read-only t)))
21486 ;;; Agenda Finding stuck projects
21488 (defvar org-agenda-skip-regexp nil
21489 "Regular expression used in skipping subtrees for the agenda.
21490 This is basically a temporary global variable that can be set and then
21491 used by user-defined selections using `org-agenda-skip-function'.")
21493 (defvar org-agenda-overriding-header nil
21494 "When this is set during todo and tags searches, will replace header.")
21496 (defun org-agenda-skip-subtree-when-regexp-matches ()
21497 "Checks if the current subtree contains match for `org-agenda-skip-regexp'.
21498 If yes, it returns the end position of this tree, causing agenda commands
21499 to skip this subtree. This is a function that can be put into
21500 `org-agenda-skip-function' for the duration of a command."
21501 (let ((end (save-excursion (org-end-of-subtree t)))
21502 skip)
21503 (save-excursion
21504 (setq skip (re-search-forward org-agenda-skip-regexp end t)))
21505 (and skip end)))
21507 (defun org-agenda-skip-entry-if (&rest conditions)
21508 "Skip entry if any of CONDITIONS is true.
21509 See `org-agenda-skip-if' for details."
21510 (org-agenda-skip-if nil conditions))
21512 (defun org-agenda-skip-subtree-if (&rest conditions)
21513 "Skip entry if any of CONDITIONS is true.
21514 See `org-agenda-skip-if' for details."
21515 (org-agenda-skip-if t conditions))
21517 (defun org-agenda-skip-if (subtree conditions)
21518 "Checks current entity for CONDITIONS.
21519 If SUBTREE is non-nil, the entire subtree is checked. Otherwise, only
21520 the entry, i.e. the text before the next heading is checked.
21522 CONDITIONS is a list of symbols, boolean OR is used to combine the results
21523 from different tests. Valid conditions are:
21525 scheduled Check if there is a scheduled cookie
21526 notscheduled Check if there is no scheduled cookie
21527 deadline Check if there is a deadline
21528 notdeadline Check if there is no deadline
21529 regexp Check if regexp matches
21530 notregexp Check if regexp does not match.
21532 The regexp is taken from the conditions list, it must come right after
21533 the `regexp' or `notregexp' element.
21535 If any of these conditions is met, this function returns the end point of
21536 the entity, causing the search to continue from there. This is a function
21537 that can be put into `org-agenda-skip-function' for the duration of a command."
21538 (let (beg end m)
21539 (org-back-to-heading t)
21540 (setq beg (point)
21541 end (if subtree
21542 (progn (org-end-of-subtree t) (point))
21543 (progn (outline-next-heading) (1- (point)))))
21544 (goto-char beg)
21545 (and
21547 (and (memq 'scheduled conditions)
21548 (re-search-forward org-scheduled-time-regexp end t))
21549 (and (memq 'notscheduled conditions)
21550 (not (re-search-forward org-scheduled-time-regexp end t)))
21551 (and (memq 'deadline conditions)
21552 (re-search-forward org-deadline-time-regexp end t))
21553 (and (memq 'notdeadline conditions)
21554 (not (re-search-forward org-deadline-time-regexp end t)))
21555 (and (setq m (memq 'regexp conditions))
21556 (stringp (nth 1 m))
21557 (re-search-forward (nth 1 m) end t))
21558 (and (setq m (memq 'notregexp conditions))
21559 (stringp (nth 1 m))
21560 (not (re-search-forward (nth 1 m) end t))))
21561 end)))
21563 ;;;###autoload
21564 (defun org-agenda-list-stuck-projects (&rest ignore)
21565 "Create agenda view for projects that are stuck.
21566 Stuck projects are project that have no next actions. For the definitions
21567 of what a project is and how to check if it stuck, customize the variable
21568 `org-stuck-projects'.
21569 MATCH is being ignored."
21570 (interactive)
21571 (let* ((org-agenda-skip-function 'org-agenda-skip-subtree-when-regexp-matches)
21572 ;; FIXME: we could have used org-agenda-skip-if here.
21573 (org-agenda-overriding-header "List of stuck projects: ")
21574 (matcher (nth 0 org-stuck-projects))
21575 (todo (nth 1 org-stuck-projects))
21576 (todo-wds (if (member "*" todo)
21577 (progn
21578 (org-prepare-agenda-buffers (org-agenda-files))
21579 (org-delete-all
21580 org-done-keywords-for-agenda
21581 (copy-sequence org-todo-keywords-for-agenda)))
21582 todo))
21583 (todo-re (concat "^\\*+[ \t]+\\("
21584 (mapconcat 'identity todo-wds "\\|")
21585 "\\)\\>"))
21586 (tags (nth 2 org-stuck-projects))
21587 (tags-re (if (member "*" tags)
21588 (org-re "^\\*+ .*:[[:alnum:]_@]+:[ \t]*$")
21589 (concat "^\\*+ .*:\\("
21590 (mapconcat 'identity tags "\\|")
21591 (org-re "\\):[[:alnum:]_@:]*[ \t]*$"))))
21592 (gen-re (nth 3 org-stuck-projects))
21593 (re-list
21594 (delq nil
21595 (list
21596 (if todo todo-re)
21597 (if tags tags-re)
21598 (and gen-re (stringp gen-re) (string-match "\\S-" gen-re)
21599 gen-re)))))
21600 (setq org-agenda-skip-regexp
21601 (if re-list
21602 (mapconcat 'identity re-list "\\|")
21603 (error "No information how to identify unstuck projects")))
21604 (org-tags-view nil matcher)
21605 (with-current-buffer org-agenda-buffer-name
21606 (setq org-agenda-redo-command
21607 '(org-agenda-list-stuck-projects
21608 (or current-prefix-arg org-last-arg))))))
21610 ;;; Diary integration
21612 (defvar org-disable-agenda-to-diary nil) ;Dynamically-scoped param.
21613 (defvar list-diary-entries-hook)
21615 (defun org-get-entries-from-diary (date)
21616 "Get the (Emacs Calendar) diary entries for DATE."
21617 (require 'diary-lib)
21618 (let* ((fancy-diary-buffer "*temporary-fancy-diary-buffer*")
21619 (diary-display-hook '(fancy-diary-display))
21620 (pop-up-frames nil)
21621 (list-diary-entries-hook
21622 (cons 'org-diary-default-entry list-diary-entries-hook))
21623 (diary-file-name-prefix-function nil) ; turn this feature off
21624 (diary-modify-entry-list-string-function 'org-modify-diary-entry-string)
21625 entries
21626 (org-disable-agenda-to-diary t))
21627 (save-excursion
21628 (save-window-excursion
21629 (funcall (if (fboundp 'diary-list-entries)
21630 'diary-list-entries 'list-diary-entries)
21631 date 1)))
21632 (if (not (get-buffer fancy-diary-buffer))
21633 (setq entries nil)
21634 (with-current-buffer fancy-diary-buffer
21635 (setq buffer-read-only nil)
21636 (if (zerop (buffer-size))
21637 ;; No entries
21638 (setq entries nil)
21639 ;; Omit the date and other unnecessary stuff
21640 (org-agenda-cleanup-fancy-diary)
21641 ;; Add prefix to each line and extend the text properties
21642 (if (zerop (buffer-size))
21643 (setq entries nil)
21644 (setq entries (buffer-substring (point-min) (- (point-max) 1)))))
21645 (set-buffer-modified-p nil)
21646 (kill-buffer fancy-diary-buffer)))
21647 (when entries
21648 (setq entries (org-split-string entries "\n"))
21649 (setq entries
21650 (mapcar
21651 (lambda (x)
21652 (setq x (org-format-agenda-item "" x "Diary" nil 'time))
21653 ;; Extend the text properties to the beginning of the line
21654 (org-add-props x (text-properties-at (1- (length x)) x)
21655 'type "diary" 'date date))
21656 entries)))))
21658 (defun org-agenda-cleanup-fancy-diary ()
21659 "Remove unwanted stuff in buffer created by `fancy-diary-display'.
21660 This gets rid of the date, the underline under the date, and
21661 the dummy entry installed by `org-mode' to ensure non-empty diary for each
21662 date. It also removes lines that contain only whitespace."
21663 (goto-char (point-min))
21664 (if (looking-at ".*?:[ \t]*")
21665 (progn
21666 (replace-match "")
21667 (re-search-forward "\n=+$" nil t)
21668 (replace-match "")
21669 (while (re-search-backward "^ +\n?" nil t) (replace-match "")))
21670 (re-search-forward "\n=+$" nil t)
21671 (delete-region (point-min) (min (point-max) (1+ (match-end 0)))))
21672 (goto-char (point-min))
21673 (while (re-search-forward "^ +\n" nil t)
21674 (replace-match ""))
21675 (goto-char (point-min))
21676 (if (re-search-forward "^Org-mode dummy\n?" nil t)
21677 (replace-match "")))
21679 ;; Make sure entries from the diary have the right text properties.
21680 (eval-after-load "diary-lib"
21681 '(if (boundp 'diary-modify-entry-list-string-function)
21682 ;; We can rely on the hook, nothing to do
21684 ;; Hook not avaiable, must use advice to make this work
21685 (defadvice add-to-diary-list (before org-mark-diary-entry activate)
21686 "Make the position visible."
21687 (if (and org-disable-agenda-to-diary ;; called from org-agenda
21688 (stringp string)
21689 buffer-file-name)
21690 (setq string (org-modify-diary-entry-string string))))))
21692 (defun org-modify-diary-entry-string (string)
21693 "Add text properties to string, allowing org-mode to act on it."
21694 (org-add-props string nil
21695 'mouse-face 'highlight
21696 'keymap org-agenda-keymap
21697 'help-echo (if buffer-file-name
21698 (format "mouse-2 or RET jump to diary file %s"
21699 (abbreviate-file-name buffer-file-name))
21701 'org-agenda-diary-link t
21702 'org-marker (org-agenda-new-marker (point-at-bol))))
21704 (defun org-diary-default-entry ()
21705 "Add a dummy entry to the diary.
21706 Needed to avoid empty dates which mess up holiday display."
21707 ;; Catch the error if dealing with the new add-to-diary-alist
21708 (when org-disable-agenda-to-diary
21709 (condition-case nil
21710 (add-to-diary-list original-date "Org-mode dummy" "")
21711 (error
21712 (add-to-diary-list original-date "Org-mode dummy" "" nil)))))
21714 ;;;###autoload
21715 (defun org-diary (&rest args)
21716 "Return diary information from org-files.
21717 This function can be used in a \"sexp\" diary entry in the Emacs calendar.
21718 It accesses org files and extracts information from those files to be
21719 listed in the diary. The function accepts arguments specifying what
21720 items should be listed. The following arguments are allowed:
21722 :timestamp List the headlines of items containing a date stamp or
21723 date range matching the selected date. Deadlines will
21724 also be listed, on the expiration day.
21726 :sexp List entries resulting from diary-like sexps.
21728 :deadline List any deadlines past due, or due within
21729 `org-deadline-warning-days'. The listing occurs only
21730 in the diary for *today*, not at any other date. If
21731 an entry is marked DONE, it is no longer listed.
21733 :scheduled List all items which are scheduled for the given date.
21734 The diary for *today* also contains items which were
21735 scheduled earlier and are not yet marked DONE.
21737 :todo List all TODO items from the org-file. This may be a
21738 long list - so this is not turned on by default.
21739 Like deadlines, these entries only show up in the
21740 diary for *today*, not at any other date.
21742 The call in the diary file should look like this:
21744 &%%(org-diary) ~/path/to/some/orgfile.org
21746 Use a separate line for each org file to check. Or, if you omit the file name,
21747 all files listed in `org-agenda-files' will be checked automatically:
21749 &%%(org-diary)
21751 If you don't give any arguments (as in the example above), the default
21752 arguments (:deadline :scheduled :timestamp :sexp) are used.
21753 So the example above may also be written as
21755 &%%(org-diary :deadline :timestamp :sexp :scheduled)
21757 The function expects the lisp variables `entry' and `date' to be provided
21758 by the caller, because this is how the calendar works. Don't use this
21759 function from a program - use `org-agenda-get-day-entries' instead."
21760 (when (> (- (time-to-seconds (current-time))
21761 org-agenda-last-marker-time)
21763 (org-agenda-reset-markers))
21764 (org-compile-prefix-format 'agenda)
21765 (org-set-sorting-strategy 'agenda)
21766 (setq args (or args '(:deadline :scheduled :timestamp :sexp)))
21767 (let* ((files (if (and entry (stringp entry) (string-match "\\S-" entry))
21768 (list entry)
21769 (org-agenda-files t)))
21770 file rtn results)
21771 (org-prepare-agenda-buffers files)
21772 ;; If this is called during org-agenda, don't return any entries to
21773 ;; the calendar. Org Agenda will list these entries itself.
21774 (if org-disable-agenda-to-diary (setq files nil))
21775 (while (setq file (pop files))
21776 (setq rtn (apply 'org-agenda-get-day-entries file date args))
21777 (setq results (append results rtn)))
21778 (if results
21779 (concat (org-finalize-agenda-entries results) "\n"))))
21781 ;;; Agenda entry finders
21783 (defun org-agenda-get-day-entries (file date &rest args)
21784 "Does the work for `org-diary' and `org-agenda'.
21785 FILE is the path to a file to be checked for entries. DATE is date like
21786 the one returned by `calendar-current-date'. ARGS are symbols indicating
21787 which kind of entries should be extracted. For details about these, see
21788 the documentation of `org-diary'."
21789 (setq args (or args '(:deadline :scheduled :timestamp :sexp)))
21790 (let* ((org-startup-folded nil)
21791 (org-startup-align-all-tables nil)
21792 (buffer (if (file-exists-p file)
21793 (org-get-agenda-file-buffer file)
21794 (error "No such file %s" file)))
21795 arg results rtn)
21796 (if (not buffer)
21797 ;; If file does not exist, make sure an error message ends up in diary
21798 (list (format "ORG-AGENDA-ERROR: No such org-file %s" file))
21799 (with-current-buffer buffer
21800 (unless (org-mode-p)
21801 (error "Agenda file %s is not in `org-mode'" file))
21802 (let ((case-fold-search nil))
21803 (save-excursion
21804 (save-restriction
21805 (if org-agenda-restrict
21806 (narrow-to-region org-agenda-restrict-begin
21807 org-agenda-restrict-end)
21808 (widen))
21809 ;; The way we repeatedly append to `results' makes it O(n^2) :-(
21810 (while (setq arg (pop args))
21811 (cond
21812 ((and (eq arg :todo)
21813 (equal date (calendar-current-date)))
21814 (setq rtn (org-agenda-get-todos))
21815 (setq results (append results rtn)))
21816 ((eq arg :timestamp)
21817 (setq rtn (org-agenda-get-blocks))
21818 (setq results (append results rtn))
21819 (setq rtn (org-agenda-get-timestamps))
21820 (setq results (append results rtn)))
21821 ((eq arg :sexp)
21822 (setq rtn (org-agenda-get-sexps))
21823 (setq results (append results rtn)))
21824 ((eq arg :scheduled)
21825 (setq rtn (org-agenda-get-scheduled))
21826 (setq results (append results rtn)))
21827 ((eq arg :closed)
21828 (setq rtn (org-agenda-get-closed))
21829 (setq results (append results rtn)))
21830 ((eq arg :deadline)
21831 (setq rtn (org-agenda-get-deadlines))
21832 (setq results (append results rtn))))))))
21833 results))))
21835 (defun org-entry-is-todo-p ()
21836 (member (org-get-todo-state) org-not-done-keywords))
21838 (defun org-entry-is-done-p ()
21839 (member (org-get-todo-state) org-done-keywords))
21841 (defun org-get-todo-state ()
21842 (save-excursion
21843 (org-back-to-heading t)
21844 (and (looking-at org-todo-line-regexp)
21845 (match-end 2)
21846 (match-string 2))))
21848 (defun org-at-date-range-p (&optional inactive-ok)
21849 "Is the cursor inside a date range?"
21850 (interactive)
21851 (save-excursion
21852 (catch 'exit
21853 (let ((pos (point)))
21854 (skip-chars-backward "^[<\r\n")
21855 (skip-chars-backward "<[")
21856 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
21857 (>= (match-end 0) pos)
21858 (throw 'exit t))
21859 (skip-chars-backward "^<[\r\n")
21860 (skip-chars-backward "<[")
21861 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
21862 (>= (match-end 0) pos)
21863 (throw 'exit t)))
21864 nil)))
21866 (defun org-agenda-get-todos ()
21867 "Return the TODO information for agenda display."
21868 (let* ((props (list 'face nil
21869 'done-face 'org-done
21870 'org-not-done-regexp org-not-done-regexp
21871 'org-todo-regexp org-todo-regexp
21872 'mouse-face 'highlight
21873 'keymap org-agenda-keymap
21874 'help-echo
21875 (format "mouse-2 or RET jump to org file %s"
21876 (abbreviate-file-name buffer-file-name))))
21877 ;; FIXME: get rid of the \n at some point but watch out
21878 (regexp (concat "^\\*+[ \t]+\\("
21879 (if org-select-this-todo-keyword
21880 (if (equal org-select-this-todo-keyword "*")
21881 org-todo-regexp
21882 (concat "\\<\\("
21883 (mapconcat 'identity (org-split-string org-select-this-todo-keyword "|") "\\|")
21884 "\\)\\>"))
21885 org-not-done-regexp)
21886 "[^\n\r]*\\)"))
21887 marker priority category tags
21888 ee txt beg end)
21889 (goto-char (point-min))
21890 (while (re-search-forward regexp nil t)
21891 (catch :skip
21892 (save-match-data
21893 (beginning-of-line)
21894 (setq beg (point) end (progn (outline-next-heading) (point)))
21895 (when (or (and org-agenda-todo-ignore-with-date (goto-char beg)
21896 (re-search-forward org-ts-regexp end t))
21897 (and org-agenda-todo-ignore-scheduled (goto-char beg)
21898 (re-search-forward org-scheduled-time-regexp end t))
21899 (and org-agenda-todo-ignore-deadlines (goto-char beg)
21900 (re-search-forward org-deadline-time-regexp end t)
21901 (org-deadline-close (match-string 1))))
21902 (goto-char (1+ beg))
21903 (or org-agenda-todo-list-sublevels (org-end-of-subtree 'invisible))
21904 (throw :skip nil)))
21905 (goto-char beg)
21906 (org-agenda-skip)
21907 (goto-char (match-beginning 1))
21908 (setq marker (org-agenda-new-marker (match-beginning 0))
21909 category (org-get-category)
21910 tags (org-get-tags-at (point))
21911 txt (org-format-agenda-item "" (match-string 1) category tags)
21912 priority (1+ (org-get-priority txt)))
21913 (org-add-props txt props
21914 'org-marker marker 'org-hd-marker marker
21915 'priority priority 'org-category category
21916 'type "todo")
21917 (push txt ee)
21918 (if org-agenda-todo-list-sublevels
21919 (goto-char (match-end 1))
21920 (org-end-of-subtree 'invisible))))
21921 (nreverse ee)))
21923 (defconst org-agenda-no-heading-message
21924 "No heading for this item in buffer or region.")
21926 (defun org-agenda-get-timestamps ()
21927 "Return the date stamp information for agenda display."
21928 (let* ((props (list 'face nil
21929 'org-not-done-regexp org-not-done-regexp
21930 'org-todo-regexp org-todo-regexp
21931 'mouse-face 'highlight
21932 'keymap org-agenda-keymap
21933 'help-echo
21934 (format "mouse-2 or RET jump to org file %s"
21935 (abbreviate-file-name buffer-file-name))))
21936 (d1 (calendar-absolute-from-gregorian date))
21937 (remove-re
21938 (concat
21939 (regexp-quote
21940 (format-time-string
21941 "<%Y-%m-%d"
21942 (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
21943 ".*?>"))
21944 (regexp
21945 (concat
21946 (regexp-quote
21947 (substring
21948 (format-time-string
21949 (car org-time-stamp-formats)
21950 (apply 'encode-time ; DATE bound by calendar
21951 (list 0 0 0 (nth 1 date) (car date) (nth 2 date))))
21952 0 11))
21953 "\\|\\(<[0-9]+-[0-9]+-[0-9]+[^>\n]+?\\+[0-9]+[dwmy]>\\)"
21954 "\\|\\(<%%\\(([^>\n]+)\\)>\\)"))
21955 marker hdmarker deadlinep scheduledp donep tmp priority category
21956 ee txt timestr tags b0 b3 e3 head)
21957 (goto-char (point-min))
21958 (while (re-search-forward regexp nil t)
21959 (setq b0 (match-beginning 0)
21960 b3 (match-beginning 3) e3 (match-end 3))
21961 (catch :skip
21962 (and (org-at-date-range-p) (throw :skip nil))
21963 (org-agenda-skip)
21964 (if (and (match-end 1)
21965 (not (= d1 (org-time-string-to-absolute (match-string 1) d1))))
21966 (throw :skip nil))
21967 (if (and e3
21968 (not (org-diary-sexp-entry (buffer-substring b3 e3) "" date)))
21969 (throw :skip nil))
21970 (setq marker (org-agenda-new-marker b0)
21971 category (org-get-category b0)
21972 tmp (buffer-substring (max (point-min)
21973 (- b0 org-ds-keyword-length))
21975 timestr (if b3 "" (buffer-substring b0 (point-at-eol)))
21976 deadlinep (string-match org-deadline-regexp tmp)
21977 scheduledp (string-match org-scheduled-regexp tmp)
21978 donep (org-entry-is-done-p))
21979 (if (or scheduledp deadlinep) (throw :skip t))
21980 (if (string-match ">" timestr)
21981 ;; substring should only run to end of time stamp
21982 (setq timestr (substring timestr 0 (match-end 0))))
21983 (save-excursion
21984 (if (re-search-backward "^\\*+ " nil t)
21985 (progn
21986 (goto-char (match-beginning 0))
21987 (setq hdmarker (org-agenda-new-marker)
21988 tags (org-get-tags-at))
21989 (looking-at "\\*+[ \t]+\\([^\r\n]+\\)")
21990 (setq head (match-string 1))
21991 (and org-agenda-skip-timestamp-if-done donep (throw :skip t))
21992 (setq txt (org-format-agenda-item
21993 nil head category tags timestr nil
21994 remove-re)))
21995 (setq txt org-agenda-no-heading-message))
21996 (setq priority (org-get-priority txt))
21997 (org-add-props txt props
21998 'org-marker marker 'org-hd-marker hdmarker)
21999 (org-add-props txt nil 'priority priority
22000 'org-category category 'date date
22001 'type "timestamp")
22002 (push txt ee))
22003 (outline-next-heading)))
22004 (nreverse ee)))
22006 (defun org-agenda-get-sexps ()
22007 "Return the sexp information for agenda display."
22008 (require 'diary-lib)
22009 (let* ((props (list 'face nil
22010 'mouse-face 'highlight
22011 'keymap org-agenda-keymap
22012 'help-echo
22013 (format "mouse-2 or RET jump to org file %s"
22014 (abbreviate-file-name buffer-file-name))))
22015 (regexp "^&?%%(")
22016 marker category ee txt tags entry result beg b sexp sexp-entry)
22017 (goto-char (point-min))
22018 (while (re-search-forward regexp nil t)
22019 (catch :skip
22020 (org-agenda-skip)
22021 (setq beg (match-beginning 0))
22022 (goto-char (1- (match-end 0)))
22023 (setq b (point))
22024 (forward-sexp 1)
22025 (setq sexp (buffer-substring b (point)))
22026 (setq sexp-entry (if (looking-at "[ \t]*\\(\\S-.*\\)")
22027 (org-trim (match-string 1))
22028 ""))
22029 (setq result (org-diary-sexp-entry sexp sexp-entry date))
22030 (when result
22031 (setq marker (org-agenda-new-marker beg)
22032 category (org-get-category beg))
22034 (if (string-match "\\S-" result)
22035 (setq txt result)
22036 (setq txt "SEXP entry returned empty string"))
22038 (setq txt (org-format-agenda-item
22039 "" txt category tags 'time))
22040 (org-add-props txt props 'org-marker marker)
22041 (org-add-props txt nil
22042 'org-category category 'date date
22043 'type "sexp")
22044 (push txt ee))))
22045 (nreverse ee)))
22047 (defun org-agenda-get-closed ()
22048 "Return the logged TODO entries for agenda display."
22049 (let* ((props (list 'mouse-face 'highlight
22050 'org-not-done-regexp org-not-done-regexp
22051 'org-todo-regexp org-todo-regexp
22052 'keymap org-agenda-keymap
22053 'help-echo
22054 (format "mouse-2 or RET jump to org file %s"
22055 (abbreviate-file-name buffer-file-name))))
22056 (regexp (concat
22057 "\\<\\(" org-closed-string "\\|" org-clock-string "\\) *\\["
22058 (regexp-quote
22059 (substring
22060 (format-time-string
22061 (car org-time-stamp-formats)
22062 (apply 'encode-time ; DATE bound by calendar
22063 (list 0 0 0 (nth 1 date) (car date) (nth 2 date))))
22064 1 11))))
22065 marker hdmarker priority category tags closedp
22066 ee txt timestr)
22067 (goto-char (point-min))
22068 (while (re-search-forward regexp nil t)
22069 (catch :skip
22070 (org-agenda-skip)
22071 (setq marker (org-agenda-new-marker (match-beginning 0))
22072 closedp (equal (match-string 1) org-closed-string)
22073 category (org-get-category (match-beginning 0))
22074 timestr (buffer-substring (match-beginning 0) (point-at-eol))
22075 ;; donep (org-entry-is-done-p)
22077 (if (string-match "\\]" timestr)
22078 ;; substring should only run to end of time stamp
22079 (setq timestr (substring timestr 0 (match-end 0))))
22080 (save-excursion
22081 (if (re-search-backward "^\\*+ " nil t)
22082 (progn
22083 (goto-char (match-beginning 0))
22084 (setq hdmarker (org-agenda-new-marker)
22085 tags (org-get-tags-at))
22086 (looking-at "\\*+[ \t]+\\([^\r\n]+\\)")
22087 (setq txt (org-format-agenda-item
22088 (if closedp "Closed: " "Clocked: ")
22089 (match-string 1) category tags timestr)))
22090 (setq txt org-agenda-no-heading-message))
22091 (setq priority 100000)
22092 (org-add-props txt props
22093 'org-marker marker 'org-hd-marker hdmarker 'face 'org-done
22094 'priority priority 'org-category category
22095 'type "closed" 'date date
22096 'undone-face 'org-warning 'done-face 'org-done)
22097 (push txt ee))
22098 (goto-char (point-at-eol))))
22099 (nreverse ee)))
22101 (defun org-agenda-get-deadlines ()
22102 "Return the deadline information for agenda display."
22103 (let* ((props (list 'mouse-face 'highlight
22104 'org-not-done-regexp org-not-done-regexp
22105 'org-todo-regexp org-todo-regexp
22106 'keymap org-agenda-keymap
22107 'help-echo
22108 (format "mouse-2 or RET jump to org file %s"
22109 (abbreviate-file-name buffer-file-name))))
22110 (regexp org-deadline-time-regexp)
22111 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
22112 (d1 (calendar-absolute-from-gregorian date)) ; DATE bound by calendar
22113 d2 diff dfrac wdays pos pos1 category tags
22114 ee txt head face s upcomingp donep timestr)
22115 (goto-char (point-min))
22116 (while (re-search-forward regexp nil t)
22117 (catch :skip
22118 (org-agenda-skip)
22119 (setq s (match-string 1)
22120 pos (1- (match-beginning 1))
22121 d2 (org-time-string-to-absolute (match-string 1) d1 'past)
22122 diff (- d2 d1)
22123 wdays (org-get-wdays s)
22124 dfrac (/ (* 1.0 (- wdays diff)) (max wdays 1))
22125 upcomingp (and todayp (> diff 0)))
22126 ;; When to show a deadline in the calendar:
22127 ;; If the expiration is within wdays warning time.
22128 ;; Past-due deadlines are only shown on the current date
22129 (if (or (and (<= diff wdays)
22130 (and todayp (not org-agenda-only-exact-dates)))
22131 (= diff 0))
22132 (save-excursion
22133 (setq category (org-get-category))
22134 (if (re-search-backward "^\\*+[ \t]+" nil t)
22135 (progn
22136 (goto-char (match-end 0))
22137 (setq pos1 (match-beginning 0))
22138 (setq tags (org-get-tags-at pos1))
22139 (setq head (buffer-substring-no-properties
22140 (point)
22141 (progn (skip-chars-forward "^\r\n")
22142 (point))))
22143 (setq donep (string-match org-looking-at-done-regexp head))
22144 (if (string-match " \\([012]?[0-9]:[0-9][0-9]\\)" s)
22145 (setq timestr
22146 (concat (substring s (match-beginning 1)) " "))
22147 (setq timestr 'time))
22148 (if (and donep
22149 (or org-agenda-skip-deadline-if-done
22150 (not (= diff 0))))
22151 (setq txt nil)
22152 (setq txt (org-format-agenda-item
22153 (if (= diff 0)
22154 (car org-agenda-deadline-leaders)
22155 (format (nth 1 org-agenda-deadline-leaders)
22156 diff))
22157 head category tags timestr))))
22158 (setq txt org-agenda-no-heading-message))
22159 (when txt
22160 (setq face (org-agenda-deadline-face dfrac wdays))
22161 (org-add-props txt props
22162 'org-marker (org-agenda-new-marker pos)
22163 'org-hd-marker (org-agenda-new-marker pos1)
22164 'priority (+ (- diff)
22165 (org-get-priority txt))
22166 'org-category category
22167 'type (if upcomingp "upcoming-deadline" "deadline")
22168 'date (if upcomingp date d2)
22169 'face (if donep 'org-done face)
22170 'undone-face face 'done-face 'org-done)
22171 (push txt ee))))))
22172 (nreverse ee)))
22174 (defun org-agenda-deadline-face (fraction &optional wdays)
22175 "Return the face to displaying a deadline item.
22176 FRACTION is what fraction of the head-warning time has passed."
22177 (if (equal wdays 0) (setq fraction 1.))
22178 (let ((faces org-agenda-deadline-faces) f)
22179 (catch 'exit
22180 (while (setq f (pop faces))
22181 (if (>= fraction (car f)) (throw 'exit (cdr f)))))))
22183 (defun org-agenda-get-scheduled ()
22184 "Return the scheduled information for agenda display."
22185 (let* ((props (list 'org-not-done-regexp org-not-done-regexp
22186 'org-todo-regexp org-todo-regexp
22187 'done-face 'org-done
22188 'mouse-face 'highlight
22189 'keymap org-agenda-keymap
22190 'help-echo
22191 (format "mouse-2 or RET jump to org file %s"
22192 (abbreviate-file-name buffer-file-name))))
22193 (regexp org-scheduled-time-regexp)
22194 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
22195 (d1 (calendar-absolute-from-gregorian date)) ; DATE bound by calendar
22196 d2 diff pos pos1 category tags
22197 ee txt head pastschedp donep face timestr s)
22198 (goto-char (point-min))
22199 (while (re-search-forward regexp nil t)
22200 (catch :skip
22201 (org-agenda-skip)
22202 (setq s (match-string 1)
22203 pos (1- (match-beginning 1))
22204 d2 (org-time-string-to-absolute (match-string 1) d1 'past)
22205 ;;; is this right?
22206 ;;; do we need to do this for deadleine too????
22207 ;;; d2 (org-time-string-to-absolute (match-string 1) (if todayp nil d1))
22208 diff (- d2 d1))
22209 (setq pastschedp (and todayp (< diff 0)))
22210 ;; When to show a scheduled item in the calendar:
22211 ;; If it is on or past the date.
22212 (if (or (and (< diff 0)
22213 (and todayp (not org-agenda-only-exact-dates)))
22214 (= diff 0))
22215 (save-excursion
22216 (setq category (org-get-category))
22217 (if (re-search-backward "^\\*+[ \t]+" nil t)
22218 (progn
22219 (goto-char (match-end 0))
22220 (setq pos1 (match-beginning 0))
22221 (setq tags (org-get-tags-at))
22222 (setq head (buffer-substring-no-properties
22223 (point)
22224 (progn (skip-chars-forward "^\r\n") (point))))
22225 (setq donep (string-match org-looking-at-done-regexp head))
22226 (if (string-match " \\([012]?[0-9]:[0-9][0-9]\\)" s)
22227 (setq timestr
22228 (concat (substring s (match-beginning 1)) " "))
22229 (setq timestr 'time))
22230 (if (and donep
22231 (or org-agenda-skip-scheduled-if-done
22232 (not (= diff 0))))
22233 (setq txt nil)
22234 (setq txt (org-format-agenda-item
22235 (if (= diff 0)
22236 (car org-agenda-scheduled-leaders)
22237 (format (nth 1 org-agenda-scheduled-leaders)
22238 (- 1 diff)))
22239 head category tags timestr))))
22240 (setq txt org-agenda-no-heading-message))
22241 (when txt
22242 (setq face (if pastschedp
22243 'org-scheduled-previously
22244 'org-scheduled-today))
22245 (org-add-props txt props
22246 'undone-face face
22247 'face (if donep 'org-done face)
22248 'org-marker (org-agenda-new-marker pos)
22249 'org-hd-marker (org-agenda-new-marker pos1)
22250 'type (if pastschedp "past-scheduled" "scheduled")
22251 'date (if pastschedp d2 date)
22252 'priority (+ 94 (- 5 diff) (org-get-priority txt))
22253 'org-category category)
22254 (push txt ee))))))
22255 (nreverse ee)))
22257 (defun org-agenda-get-blocks ()
22258 "Return the date-range information for agenda display."
22259 (let* ((props (list 'face nil
22260 'org-not-done-regexp org-not-done-regexp
22261 'org-todo-regexp org-todo-regexp
22262 'mouse-face 'highlight
22263 'keymap org-agenda-keymap
22264 'help-echo
22265 (format "mouse-2 or RET jump to org file %s"
22266 (abbreviate-file-name buffer-file-name))))
22267 (regexp org-tr-regexp)
22268 (d0 (calendar-absolute-from-gregorian date))
22269 marker hdmarker ee txt d1 d2 s1 s2 timestr category tags pos
22270 donep head)
22271 (goto-char (point-min))
22272 (while (re-search-forward regexp nil t)
22273 (catch :skip
22274 (org-agenda-skip)
22275 (setq pos (point))
22276 (setq timestr (match-string 0)
22277 s1 (match-string 1)
22278 s2 (match-string 2)
22279 d1 (time-to-days (org-time-string-to-time s1))
22280 d2 (time-to-days (org-time-string-to-time s2)))
22281 (if (and (> (- d0 d1) -1) (> (- d2 d0) -1))
22282 ;; Only allow days between the limits, because the normal
22283 ;; date stamps will catch the limits.
22284 (save-excursion
22285 (setq marker (org-agenda-new-marker (point)))
22286 (setq category (org-get-category))
22287 (if (re-search-backward "^\\*+ " nil t)
22288 (progn
22289 (goto-char (match-beginning 0))
22290 (setq hdmarker (org-agenda-new-marker (point)))
22291 (setq tags (org-get-tags-at))
22292 (looking-at "\\*+[ \t]+\\([^\r\n]+\\)")
22293 (setq head (match-string 1))
22294 (and org-agenda-skip-timestamp-if-done
22295 (org-entry-is-done-p)
22296 (throw :skip t))
22297 (setq txt (org-format-agenda-item
22298 (format (if (= d1 d2) "" "(%d/%d): ")
22299 (1+ (- d0 d1)) (1+ (- d2 d1)))
22300 head category tags
22301 (if (= d0 d1) timestr))))
22302 (setq txt org-agenda-no-heading-message))
22303 (org-add-props txt props
22304 'org-marker marker 'org-hd-marker hdmarker
22305 'type "block" 'date date
22306 'priority (org-get-priority txt) 'org-category category)
22307 (push txt ee)))
22308 (goto-char pos)))
22309 ;; Sort the entries by expiration date.
22310 (nreverse ee)))
22312 ;;; Agenda presentation and sorting
22314 (defconst org-plain-time-of-day-regexp
22315 (concat
22316 "\\(\\<[012]?[0-9]"
22317 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
22318 "\\(--?"
22319 "\\(\\<[012]?[0-9]"
22320 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
22321 "\\)?")
22322 "Regular expression to match a plain time or time range.
22323 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
22324 groups carry important information:
22325 0 the full match
22326 1 the first time, range or not
22327 8 the second time, if it is a range.")
22329 (defconst org-plain-time-extension-regexp
22330 (concat
22331 "\\(\\<[012]?[0-9]"
22332 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
22333 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
22334 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
22335 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
22336 groups carry important information:
22337 0 the full match
22338 7 hours of duration
22339 9 minutes of duration")
22341 (defconst org-stamp-time-of-day-regexp
22342 (concat
22343 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
22344 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
22345 "\\(--?"
22346 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
22347 "Regular expression to match a timestamp time or time range.
22348 After a match, the following groups carry important information:
22349 0 the full match
22350 1 date plus weekday, for backreferencing to make sure both times on same day
22351 2 the first time, range or not
22352 4 the second time, if it is a range.")
22354 (defvar org-prefix-has-time nil
22355 "A flag, set by `org-compile-prefix-format'.
22356 The flag is set if the currently compiled format contains a `%t'.")
22357 (defvar org-prefix-has-tag nil
22358 "A flag, set by `org-compile-prefix-format'.
22359 The flag is set if the currently compiled format contains a `%T'.")
22361 (defun org-format-agenda-item (extra txt &optional category tags dotime
22362 noprefix remove-re)
22363 "Format TXT to be inserted into the agenda buffer.
22364 In particular, it adds the prefix and corresponding text properties. EXTRA
22365 must be a string and replaces the `%s' specifier in the prefix format.
22366 CATEGORY (string, symbol or nil) may be used to overrule the default
22367 category taken from local variable or file name. It will replace the `%c'
22368 specifier in the format. DOTIME, when non-nil, indicates that a
22369 time-of-day should be extracted from TXT for sorting of this entry, and for
22370 the `%t' specifier in the format. When DOTIME is a string, this string is
22371 searched for a time before TXT is. NOPREFIX is a flag and indicates that
22372 only the correctly processes TXT should be returned - this is used by
22373 `org-agenda-change-all-lines'. TAGS can be the tags of the headline.
22374 Any match of REMOVE-RE will be removed from TXT."
22375 (save-match-data
22376 ;; Diary entries sometimes have extra whitespace at the beginning
22377 (if (string-match "^ +" txt) (setq txt (replace-match "" nil nil txt)))
22378 (let* ((category (or category
22379 org-category
22380 (if buffer-file-name
22381 (file-name-sans-extension
22382 (file-name-nondirectory buffer-file-name))
22383 "")))
22384 (tag (if tags (nth (1- (length tags)) tags) ""))
22385 time ; time and tag are needed for the eval of the prefix format
22386 (ts (if dotime (concat (if (stringp dotime) dotime "") txt)))
22387 (time-of-day (and dotime (org-get-time-of-day ts)))
22388 stamp plain s0 s1 s2 rtn srp)
22389 (when (and dotime time-of-day org-prefix-has-time)
22390 ;; Extract starting and ending time and move them to prefix
22391 (when (or (setq stamp (string-match org-stamp-time-of-day-regexp ts))
22392 (setq plain (string-match org-plain-time-of-day-regexp ts)))
22393 (setq s0 (match-string 0 ts)
22394 srp (and stamp (match-end 3))
22395 s1 (match-string (if plain 1 2) ts)
22396 s2 (match-string (if plain 8 (if srp 4 6)) ts))
22398 ;; If the times are in TXT (not in DOTIMES), and the prefix will list
22399 ;; them, we might want to remove them there to avoid duplication.
22400 ;; The user can turn this off with a variable.
22401 (if (and org-agenda-remove-times-when-in-prefix (or stamp plain)
22402 (string-match (concat (regexp-quote s0) " *") txt)
22403 (not (equal ?\] (string-to-char (substring txt (match-end 0)))))
22404 (if (eq org-agenda-remove-times-when-in-prefix 'beg)
22405 (= (match-beginning 0) 0)
22407 (setq txt (replace-match "" nil nil txt))))
22408 ;; Normalize the time(s) to 24 hour
22409 (if s1 (setq s1 (org-get-time-of-day s1 'string t)))
22410 (if s2 (setq s2 (org-get-time-of-day s2 'string t))))
22412 (when (and s1 (not s2) org-agenda-default-appointment-duration
22413 (string-match "\\([0-9]+\\):\\([0-9]+\\)" s1))
22414 (let ((m (+ (string-to-number (match-string 2 s1))
22415 (* 60 (string-to-number (match-string 1 s1)))
22416 org-agenda-default-appointment-duration))
22418 (setq h (/ m 60) m (- m (* h 60)))
22419 (setq s2 (format "%02d:%02d" h m))))
22421 (when (string-match (org-re "\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$")
22422 txt)
22423 ;; Tags are in the string
22424 (if (or (eq org-agenda-remove-tags t)
22425 (and org-agenda-remove-tags
22426 org-prefix-has-tag))
22427 (setq txt (replace-match "" t t txt))
22428 (setq txt (replace-match
22429 (concat (make-string (max (- 50 (length txt)) 1) ?\ )
22430 (match-string 2 txt))
22431 t t txt))))
22433 (when remove-re
22434 (while (string-match remove-re txt)
22435 (setq txt (replace-match "" t t txt))))
22437 ;; Create the final string
22438 (if noprefix
22439 (setq rtn txt)
22440 ;; Prepare the variables needed in the eval of the compiled format
22441 (setq time (cond (s2 (concat s1 "-" s2))
22442 (s1 (concat s1 "......"))
22443 (t ""))
22444 extra (or extra "")
22445 category (if (symbolp category) (symbol-name category) category))
22446 ;; Evaluate the compiled format
22447 (setq rtn (concat (eval org-prefix-format-compiled) txt)))
22449 ;; And finally add the text properties
22450 (org-add-props rtn nil
22451 'org-category (downcase category) 'tags tags
22452 'org-highest-priority org-highest-priority
22453 'org-lowest-priority org-lowest-priority
22454 'prefix-length (- (length rtn) (length txt))
22455 'time-of-day time-of-day
22456 'txt txt
22457 'time time
22458 'extra extra
22459 'dotime dotime))))
22461 (defvar org-agenda-sorting-strategy) ;; because the def is in a let form
22462 (defvar org-agenda-sorting-strategy-selected nil)
22464 (defun org-agenda-add-time-grid-maybe (list ndays todayp)
22465 (catch 'exit
22466 (cond ((not org-agenda-use-time-grid) (throw 'exit list))
22467 ((and todayp (member 'today (car org-agenda-time-grid))))
22468 ((and (= ndays 1) (member 'daily (car org-agenda-time-grid))))
22469 ((member 'weekly (car org-agenda-time-grid)))
22470 (t (throw 'exit list)))
22471 (let* ((have (delq nil (mapcar
22472 (lambda (x) (get-text-property 1 'time-of-day x))
22473 list)))
22474 (string (nth 1 org-agenda-time-grid))
22475 (gridtimes (nth 2 org-agenda-time-grid))
22476 (req (car org-agenda-time-grid))
22477 (remove (member 'remove-match req))
22478 new time)
22479 (if (and (member 'require-timed req) (not have))
22480 ;; don't show empty grid
22481 (throw 'exit list))
22482 (while (setq time (pop gridtimes))
22483 (unless (and remove (member time have))
22484 (setq time (int-to-string time))
22485 (push (org-format-agenda-item
22486 nil string "" nil
22487 (concat (substring time 0 -2) ":" (substring time -2)))
22488 new)
22489 (put-text-property
22490 1 (length (car new)) 'face 'org-time-grid (car new))))
22491 (if (member 'time-up org-agenda-sorting-strategy-selected)
22492 (append new list)
22493 (append list new)))))
22495 (defun org-compile-prefix-format (key)
22496 "Compile the prefix format into a Lisp form that can be evaluated.
22497 The resulting form is returned and stored in the variable
22498 `org-prefix-format-compiled'."
22499 (setq org-prefix-has-time nil org-prefix-has-tag nil)
22500 (let ((s (cond
22501 ((stringp org-agenda-prefix-format)
22502 org-agenda-prefix-format)
22503 ((assq key org-agenda-prefix-format)
22504 (cdr (assq key org-agenda-prefix-format)))
22505 (t " %-12:c%?-12t% s")))
22506 (start 0)
22507 varform vars var e c f opt)
22508 (while (string-match "%\\(\\?\\)?\\([-+]?[0-9.]*\\)\\([ .;,:!?=|/<>]?\\)\\([cts]\\)"
22509 s start)
22510 (setq var (cdr (assoc (match-string 4 s)
22511 '(("c" . category) ("t" . time) ("s" . extra)
22512 ("T" . tag))))
22513 c (or (match-string 3 s) "")
22514 opt (match-beginning 1)
22515 start (1+ (match-beginning 0)))
22516 (if (equal var 'time) (setq org-prefix-has-time t))
22517 (if (equal var 'tag) (setq org-prefix-has-tag t))
22518 (setq f (concat "%" (match-string 2 s) "s"))
22519 (if opt
22520 (setq varform
22521 `(if (equal "" ,var)
22523 (format ,f (if (equal "" ,var) "" (concat ,var ,c)))))
22524 (setq varform `(format ,f (if (equal ,var "") "" (concat ,var ,c)))))
22525 (setq s (replace-match "%s" t nil s))
22526 (push varform vars))
22527 (setq vars (nreverse vars))
22528 (setq org-prefix-format-compiled `(format ,s ,@vars))))
22530 (defun org-set-sorting-strategy (key)
22531 (if (symbolp (car org-agenda-sorting-strategy))
22532 ;; the old format
22533 (setq org-agenda-sorting-strategy-selected org-agenda-sorting-strategy)
22534 (setq org-agenda-sorting-strategy-selected
22535 (or (cdr (assq key org-agenda-sorting-strategy))
22536 (cdr (assq 'agenda org-agenda-sorting-strategy))
22537 '(time-up category-keep priority-down)))))
22539 (defun org-get-time-of-day (s &optional string mod24)
22540 "Check string S for a time of day.
22541 If found, return it as a military time number between 0 and 2400.
22542 If not found, return nil.
22543 The optional STRING argument forces conversion into a 5 character wide string
22544 HH:MM."
22545 (save-match-data
22546 (when
22547 (or (string-match "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)\\([AaPp][Mm]\\)?\\> *" s)
22548 (string-match "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\([AaPp][Mm]\\)\\> *" s))
22549 (let* ((h (string-to-number (match-string 1 s)))
22550 (m (if (match-end 3) (string-to-number (match-string 3 s)) 0))
22551 (ampm (if (match-end 4) (downcase (match-string 4 s))))
22552 (am-p (equal ampm "am"))
22553 (h1 (cond ((not ampm) h)
22554 ((= h 12) (if am-p 0 12))
22555 (t (+ h (if am-p 0 12)))))
22556 (h2 (if (and string mod24 (not (and (= m 0) (= h1 24))))
22557 (mod h1 24) h1))
22558 (t0 (+ (* 100 h2) m))
22559 (t1 (concat (if (>= h1 24) "+" " ")
22560 (if (< t0 100) "0" "")
22561 (if (< t0 10) "0" "")
22562 (int-to-string t0))))
22563 (if string (concat (substring t1 -4 -2) ":" (substring t1 -2)) t0)))))
22565 (defun org-finalize-agenda-entries (list &optional nosort)
22566 "Sort and concatenate the agenda items."
22567 (setq list (mapcar 'org-agenda-highlight-todo list))
22568 (if nosort
22569 list
22570 (mapconcat 'identity (sort list 'org-entries-lessp) "\n")))
22572 (defun org-agenda-highlight-todo (x)
22573 (let (re pl)
22574 (if (eq x 'line)
22575 (save-excursion
22576 (beginning-of-line 1)
22577 (setq re (get-text-property (point) 'org-todo-regexp))
22578 (goto-char (+ (point) (or (get-text-property (point) 'prefix-length) 0)))
22579 (when (looking-at (concat "[ \t]*\\.*" re " +"))
22580 (add-text-properties (match-beginning 0) (match-end 0)
22581 (list 'face (org-get-todo-face 0)))
22582 (let ((s (buffer-substring (match-beginning 1) (match-end 1))))
22583 (delete-region (match-beginning 1) (1- (match-end 0)))
22584 (goto-char (match-beginning 1))
22585 (insert (format org-agenda-todo-keyword-format s)))))
22586 (setq re (concat (get-text-property 0 'org-todo-regexp x))
22587 pl (get-text-property 0 'prefix-length x))
22588 (when (and re
22589 (equal (string-match (concat "\\(\\.*\\)" re "\\( +\\)")
22590 x (or pl 0)) pl))
22591 (add-text-properties
22592 (or (match-end 1) (match-end 0)) (match-end 0)
22593 (list 'face (org-get-todo-face (match-string 2 x)))
22595 (setq x (concat (substring x 0 (match-end 1))
22596 (format org-agenda-todo-keyword-format
22597 (match-string 2 x))
22599 (substring x (match-end 3)))))
22600 x)))
22602 (defsubst org-cmp-priority (a b)
22603 "Compare the priorities of string A and B."
22604 (let ((pa (or (get-text-property 1 'priority a) 0))
22605 (pb (or (get-text-property 1 'priority b) 0)))
22606 (cond ((> pa pb) +1)
22607 ((< pa pb) -1)
22608 (t nil))))
22610 (defsubst org-cmp-category (a b)
22611 "Compare the string values of categories of strings A and B."
22612 (let ((ca (or (get-text-property 1 'org-category a) ""))
22613 (cb (or (get-text-property 1 'org-category b) "")))
22614 (cond ((string-lessp ca cb) -1)
22615 ((string-lessp cb ca) +1)
22616 (t nil))))
22618 (defsubst org-cmp-tag (a b)
22619 "Compare the string values of categories of strings A and B."
22620 (let ((ta (car (last (get-text-property 1 'tags a))))
22621 (tb (car (last (get-text-property 1 'tags b)))))
22622 (cond ((not ta) +1)
22623 ((not tb) -1)
22624 ((string-lessp ta tb) -1)
22625 ((string-lessp tb ta) +1)
22626 (t nil))))
22628 (defsubst org-cmp-time (a b)
22629 "Compare the time-of-day values of strings A and B."
22630 (let* ((def (if org-sort-agenda-notime-is-late 9901 -1))
22631 (ta (or (get-text-property 1 'time-of-day a) def))
22632 (tb (or (get-text-property 1 'time-of-day b) def)))
22633 (cond ((< ta tb) -1)
22634 ((< tb ta) +1)
22635 (t nil))))
22637 (defun org-entries-lessp (a b)
22638 "Predicate for sorting agenda entries."
22639 ;; The following variables will be used when the form is evaluated.
22640 ;; So even though the compiler complains, keep them.
22641 (let* ((time-up (org-cmp-time a b))
22642 (time-down (if time-up (- time-up) nil))
22643 (priority-up (org-cmp-priority a b))
22644 (priority-down (if priority-up (- priority-up) nil))
22645 (category-up (org-cmp-category a b))
22646 (category-down (if category-up (- category-up) nil))
22647 (category-keep (if category-up +1 nil))
22648 (tag-up (org-cmp-tag a b))
22649 (tag-down (if tag-up (- tag-up) nil)))
22650 (cdr (assoc
22651 (eval (cons 'or org-agenda-sorting-strategy-selected))
22652 '((-1 . t) (1 . nil) (nil . nil))))))
22654 ;;; Agenda restriction lock
22656 (defvar org-agenda-restriction-lock-overlay (org-make-overlay 1 1)
22657 "Overlay to mark the headline to which arenda commands are restricted.")
22658 (org-overlay-put org-agenda-restriction-lock-overlay
22659 'face 'org-agenda-restriction-lock)
22660 (org-overlay-put org-agenda-restriction-lock-overlay
22661 'help-echo "Agendas are currently limited to this subtree.")
22662 (org-detach-overlay org-agenda-restriction-lock-overlay)
22663 (defvar org-speedbar-restriction-lock-overlay (org-make-overlay 1 1)
22664 "Overlay marking the agenda restriction line in speedbar.")
22665 (org-overlay-put org-speedbar-restriction-lock-overlay
22666 'face 'org-agenda-restriction-lock)
22667 (org-overlay-put org-speedbar-restriction-lock-overlay
22668 'help-echo "Agendas are currently limited to this item.")
22669 (org-detach-overlay org-speedbar-restriction-lock-overlay)
22671 (defun org-agenda-set-restriction-lock (&optional type)
22672 "Set restriction lock for agenda, to current subtree or file.
22673 Restriction will be the file if TYPE is `file', or if type is the
22674 universal prefix '(4), or if the cursor is before the first headline
22675 in the file. Otherwise, restriction will be to the current subtree."
22676 (interactive "P")
22677 (and (equal type '(4)) (setq type 'file))
22678 (setq type (cond
22679 (type type)
22680 ((org-at-heading-p) 'subtree)
22681 ((condition-case nil (org-back-to-heading t) (error nil))
22682 'subtree)
22683 (t 'file)))
22684 (if (eq type 'subtree)
22685 (progn
22686 (setq org-agenda-restrict t)
22687 (setq org-agenda-overriding-restriction 'subtree)
22688 (put 'org-agenda-files 'org-restrict
22689 (list (buffer-file-name (buffer-base-buffer))))
22690 (org-back-to-heading t)
22691 (org-move-overlay org-agenda-restriction-lock-overlay (point) (point-at-eol))
22692 (move-marker org-agenda-restrict-begin (point))
22693 (move-marker org-agenda-restrict-end
22694 (save-excursion (org-end-of-subtree t)))
22695 (message "Locking agenda restriction to subtree"))
22696 (put 'org-agenda-files 'org-restrict
22697 (list (buffer-file-name (buffer-base-buffer))))
22698 (setq org-agenda-restrict nil)
22699 (setq org-agenda-overriding-restriction 'file)
22700 (move-marker org-agenda-restrict-begin nil)
22701 (move-marker org-agenda-restrict-end nil)
22702 (message "Locking agenda restriction to file"))
22703 (setq current-prefix-arg nil)
22704 (org-agenda-maybe-redo))
22706 (defun org-agenda-remove-restriction-lock (&optional noupdate)
22707 "Remove the agenda restriction lock."
22708 (interactive "P")
22709 (org-detach-overlay org-agenda-restriction-lock-overlay)
22710 (org-detach-overlay org-speedbar-restriction-lock-overlay)
22711 (setq org-agenda-overriding-restriction nil)
22712 (setq org-agenda-restrict nil)
22713 (put 'org-agenda-files 'org-restrict nil)
22714 (move-marker org-agenda-restrict-begin nil)
22715 (move-marker org-agenda-restrict-end nil)
22716 (setq current-prefix-arg nil)
22717 (message "Agenda restriction lock removed")
22718 (or noupdate (org-agenda-maybe-redo)))
22720 (defun org-agenda-maybe-redo ()
22721 "If there is any window showing the agenda view, update it."
22722 (let ((w (get-buffer-window org-agenda-buffer-name t))
22723 (w0 (selected-window)))
22724 (when w
22725 (select-window w)
22726 (org-agenda-redo)
22727 (select-window w0)
22728 (if org-agenda-overriding-restriction
22729 (message "Agenda view shifted to new %s restriction"
22730 org-agenda-overriding-restriction)
22731 (message "Agenda restriction lock removed")))))
22733 ;;; Agenda commands
22735 (defun org-agenda-check-type (error &rest types)
22736 "Check if agenda buffer is of allowed type.
22737 If ERROR is non-nil, throw an error, otherwise just return nil."
22738 (if (memq org-agenda-type types)
22740 (if error
22741 (error "Not allowed in %s-type agenda buffers" org-agenda-type)
22742 nil)))
22744 (defun org-agenda-quit ()
22745 "Exit agenda by removing the window or the buffer."
22746 (interactive)
22747 (let ((buf (current-buffer)))
22748 (if (not (one-window-p)) (delete-window))
22749 (kill-buffer buf)
22750 (org-agenda-reset-markers)
22751 (org-columns-remove-overlays))
22752 ;; Maybe restore the pre-agenda window configuration.
22753 (and org-agenda-restore-windows-after-quit
22754 (not (eq org-agenda-window-setup 'other-frame))
22755 org-pre-agenda-window-conf
22756 (set-window-configuration org-pre-agenda-window-conf)))
22758 (defun org-agenda-exit ()
22759 "Exit agenda by removing the window or the buffer.
22760 Also kill all Org-mode buffers which have been loaded by `org-agenda'.
22761 Org-mode buffers visited directly by the user will not be touched."
22762 (interactive)
22763 (org-release-buffers org-agenda-new-buffers)
22764 (setq org-agenda-new-buffers nil)
22765 (org-agenda-quit))
22767 (defun org-agenda-execute (arg)
22768 "Execute another agenda command, keeping same window.\\<global-map>
22769 So this is just a shortcut for `\\[org-agenda]', available in the agenda."
22770 (interactive "P")
22771 (let ((org-agenda-window-setup 'current-window))
22772 (org-agenda arg)))
22774 (defun org-save-all-org-buffers ()
22775 "Save all Org-mode buffers without user confirmation."
22776 (interactive)
22777 (message "Saving all Org-mode buffers...")
22778 (save-some-buffers t 'org-mode-p)
22779 (message "Saving all Org-mode buffers... done"))
22781 (defun org-agenda-redo ()
22782 "Rebuild Agenda.
22783 When this is the global TODO list, a prefix argument will be interpreted."
22784 (interactive)
22785 (let* ((org-agenda-keep-modes t)
22786 (line (org-current-line))
22787 (window-line (- line (org-current-line (window-start))))
22788 (lprops (get 'org-agenda-redo-command 'org-lprops)))
22789 (message "Rebuilding agenda buffer...")
22790 (org-let lprops '(eval org-agenda-redo-command))
22791 (setq org-agenda-undo-list nil
22792 org-agenda-pending-undo-list nil)
22793 (message "Rebuilding agenda buffer...done")
22794 (goto-line line)
22795 (recenter window-line)))
22797 (defun org-agenda-manipulate-query-add ()
22798 "Manipulate the query by adding a search term with positive selection.
22799 Positive selection means, the term must be matched for selection of an entry."
22800 (interactive)
22801 (org-agenda-manipulate-query ?\[))
22802 (defun org-agenda-manipulate-query-subtract ()
22803 "Manipulate the query by adding a search term with negative selection.
22804 Negative selection means, term must not be matched for selection of an entry."
22805 (interactive)
22806 (org-agenda-manipulate-query ?\]))
22807 (defun org-agenda-manipulate-query-add-re ()
22808 "Manipulate the query by adding a search regexp with positive selection.
22809 Positive selection means, the regexp must match for selection of an entry."
22810 (interactive)
22811 (org-agenda-manipulate-query ?\{))
22812 (defun org-agenda-manipulate-query-subtract-re ()
22813 "Manipulate the query by adding a search regexp with negative selection.
22814 Negative selection means, regexp must not match for selection of an entry."
22815 (interactive)
22816 (org-agenda-manipulate-query ?\}))
22817 (defun org-agenda-manipulate-query (char)
22818 (cond
22819 ((eq org-agenda-type 'search)
22820 (org-add-to-string
22821 'org-agenda-query-string
22822 (cdr (assoc char '((?\[ . " +") (?\] . " -")
22823 (?\{ . " +{}") (?\} . " -{}")))))
22824 (setq org-agenda-redo-command
22825 (list 'org-search-view
22826 (+ (length org-agenda-query-string)
22827 (if (member char '(?\{ ?\})) 0 1))
22828 org-agenda-query-string))
22829 (set-register org-agenda-query-register org-agenda-query-string)
22830 (org-agenda-redo))
22831 (t (error "Canot manipulate query for %s-type agenda buffers"
22832 org-agenda-type))))
22834 (defun org-add-to-string (var string)
22835 (set var (concat (symbol-value var) string)))
22837 (defun org-agenda-goto-date (date)
22838 "Jump to DATE in agenda."
22839 (interactive (list (org-read-date)))
22840 (org-agenda-list nil date))
22842 (defun org-agenda-goto-today ()
22843 "Go to today."
22844 (interactive)
22845 (org-agenda-check-type t 'timeline 'agenda)
22846 (let ((tdpos (text-property-any (point-min) (point-max) 'org-today t)))
22847 (cond
22848 (tdpos (goto-char tdpos))
22849 ((eq org-agenda-type 'agenda)
22850 (let* ((sd (time-to-days
22851 (time-subtract (current-time)
22852 (list 0 (* 3600 org-extend-today-until) 0))))
22853 (comp (org-agenda-compute-time-span sd org-agenda-span))
22854 (org-agenda-overriding-arguments org-agenda-last-arguments))
22855 (setf (nth 1 org-agenda-overriding-arguments) (car comp))
22856 (setf (nth 2 org-agenda-overriding-arguments) (cdr comp))
22857 (org-agenda-redo)
22858 (org-agenda-find-same-or-today-or-agenda)))
22859 (t (error "Cannot find today")))))
22861 (defun org-agenda-find-same-or-today-or-agenda (&optional cnt)
22862 (goto-char
22863 (or (and cnt (text-property-any (point-min) (point-max) 'org-day-cnt cnt))
22864 (text-property-any (point-min) (point-max) 'org-today t)
22865 (text-property-any (point-min) (point-max) 'org-agenda-type 'agenda)
22866 (point-min))))
22868 (defun org-agenda-later (arg)
22869 "Go forward in time by thee current span.
22870 With prefix ARG, go forward that many times the current span."
22871 (interactive "p")
22872 (org-agenda-check-type t 'agenda)
22873 (let* ((span org-agenda-span)
22874 (sd org-starting-day)
22875 (greg (calendar-gregorian-from-absolute sd))
22876 (cnt (get-text-property (point) 'org-day-cnt))
22877 greg2 nd)
22878 (cond
22879 ((eq span 'day)
22880 (setq sd (+ arg sd) nd 1))
22881 ((eq span 'week)
22882 (setq sd (+ (* 7 arg) sd) nd 7))
22883 ((eq span 'month)
22884 (setq greg2 (list (+ (car greg) arg) (nth 1 greg) (nth 2 greg))
22885 sd (calendar-absolute-from-gregorian greg2))
22886 (setcar greg2 (1+ (car greg2)))
22887 (setq nd (- (calendar-absolute-from-gregorian greg2) sd)))
22888 ((eq span 'year)
22889 (setq greg2 (list (car greg) (nth 1 greg) (+ arg (nth 2 greg)))
22890 sd (calendar-absolute-from-gregorian greg2))
22891 (setcar (nthcdr 2 greg2) (1+ (nth 2 greg2)))
22892 (setq nd (- (calendar-absolute-from-gregorian greg2) sd))))
22893 (let ((org-agenda-overriding-arguments
22894 (list (car org-agenda-last-arguments) sd nd t)))
22895 (org-agenda-redo)
22896 (org-agenda-find-same-or-today-or-agenda cnt))))
22898 (defun org-agenda-earlier (arg)
22899 "Go backward in time by the current span.
22900 With prefix ARG, go backward that many times the current span."
22901 (interactive "p")
22902 (org-agenda-later (- arg)))
22904 (defun org-agenda-day-view ()
22905 "Switch to daily view for agenda."
22906 (interactive)
22907 (setq org-agenda-ndays 1)
22908 (org-agenda-change-time-span 'day))
22909 (defun org-agenda-week-view ()
22910 "Switch to daily view for agenda."
22911 (interactive)
22912 (setq org-agenda-ndays 7)
22913 (org-agenda-change-time-span 'week))
22914 (defun org-agenda-month-view ()
22915 "Switch to daily view for agenda."
22916 (interactive)
22917 (org-agenda-change-time-span 'month))
22918 (defun org-agenda-year-view ()
22919 "Switch to daily view for agenda."
22920 (interactive)
22921 (if (y-or-n-p "Are you sure you want to compute the agenda for an entire year? ")
22922 (org-agenda-change-time-span 'year)
22923 (error "Abort")))
22925 (defun org-agenda-change-time-span (span)
22926 "Change the agenda view to SPAN.
22927 SPAN may be `day', `week', `month', `year'."
22928 (org-agenda-check-type t 'agenda)
22929 (if (equal org-agenda-span span)
22930 (error "Viewing span is already \"%s\"" span))
22931 (let* ((sd (or (get-text-property (point) 'day)
22932 org-starting-day))
22933 (computed (org-agenda-compute-time-span sd span))
22934 (org-agenda-overriding-arguments
22935 (list (car org-agenda-last-arguments)
22936 (car computed) (cdr computed) t)))
22937 (org-agenda-redo)
22938 (org-agenda-find-same-or-today-or-agenda))
22939 (org-agenda-set-mode-name)
22940 (message "Switched to %s view" span))
22942 (defun org-agenda-compute-time-span (sd span)
22943 "Compute starting date and number of days for agenda.
22944 SPAN may be `day', `week', `month', `year'. The return value
22945 is a cons cell with the starting date and the number of days,
22946 so that the date SD will be in that range."
22947 (let* ((greg (calendar-gregorian-from-absolute sd))
22949 (cond
22950 ((eq span 'day)
22951 (setq nd 1))
22952 ((eq span 'week)
22953 (let* ((nt (calendar-day-of-week
22954 (calendar-gregorian-from-absolute sd)))
22955 (d (if org-agenda-start-on-weekday
22956 (- nt org-agenda-start-on-weekday)
22957 0)))
22958 (setq sd (- sd (+ (if (< d 0) 7 0) d)))
22959 (setq nd 7)))
22960 ((eq span 'month)
22961 (setq sd (calendar-absolute-from-gregorian
22962 (list (car greg) 1 (nth 2 greg)))
22963 nd (- (calendar-absolute-from-gregorian
22964 (list (1+ (car greg)) 1 (nth 2 greg)))
22965 sd)))
22966 ((eq span 'year)
22967 (setq sd (calendar-absolute-from-gregorian
22968 (list 1 1 (nth 2 greg)))
22969 nd (- (calendar-absolute-from-gregorian
22970 (list 1 1 (1+ (nth 2 greg))))
22971 sd))))
22972 (cons sd nd)))
22974 ;; FIXME: does not work if user makes date format that starts with a blank
22975 (defun org-agenda-next-date-line (&optional arg)
22976 "Jump to the next line indicating a date in agenda buffer."
22977 (interactive "p")
22978 (org-agenda-check-type t 'agenda 'timeline)
22979 (beginning-of-line 1)
22980 (if (looking-at "^\\S-") (forward-char 1))
22981 (if (not (re-search-forward "^\\S-" nil t arg))
22982 (progn
22983 (backward-char 1)
22984 (error "No next date after this line in this buffer")))
22985 (goto-char (match-beginning 0)))
22987 (defun org-agenda-previous-date-line (&optional arg)
22988 "Jump to the previous line indicating a date in agenda buffer."
22989 (interactive "p")
22990 (org-agenda-check-type t 'agenda 'timeline)
22991 (beginning-of-line 1)
22992 (if (not (re-search-backward "^\\S-" nil t arg))
22993 (error "No previous date before this line in this buffer")))
22995 ;; Initialize the highlight
22996 (defvar org-hl (org-make-overlay 1 1))
22997 (org-overlay-put org-hl 'face 'highlight)
22999 (defun org-highlight (begin end &optional buffer)
23000 "Highlight a region with overlay."
23001 (funcall (if (featurep 'xemacs) 'set-extent-endpoints 'move-overlay)
23002 org-hl begin end (or buffer (current-buffer))))
23004 (defun org-unhighlight ()
23005 "Detach overlay INDEX."
23006 (funcall (if (featurep 'xemacs) 'detach-extent 'delete-overlay) org-hl))
23008 ;; FIXME this is currently not used.
23009 (defun org-highlight-until-next-command (beg end &optional buffer)
23010 (org-highlight beg end buffer)
23011 (add-hook 'pre-command-hook 'org-unhighlight-once))
23012 (defun org-unhighlight-once ()
23013 (remove-hook 'pre-command-hook 'org-unhighlight-once)
23014 (org-unhighlight))
23016 (defun org-agenda-follow-mode ()
23017 "Toggle follow mode in an agenda buffer."
23018 (interactive)
23019 (setq org-agenda-follow-mode (not org-agenda-follow-mode))
23020 (org-agenda-set-mode-name)
23021 (message "Follow mode is %s"
23022 (if org-agenda-follow-mode "on" "off")))
23024 (defun org-agenda-log-mode ()
23025 "Toggle log mode in an agenda buffer."
23026 (interactive)
23027 (org-agenda-check-type t 'agenda 'timeline)
23028 (setq org-agenda-show-log (not org-agenda-show-log))
23029 (org-agenda-set-mode-name)
23030 (org-agenda-redo)
23031 (message "Log mode is %s"
23032 (if org-agenda-show-log "on" "off")))
23034 (defun org-agenda-toggle-diary ()
23035 "Toggle diary inclusion in an agenda buffer."
23036 (interactive)
23037 (org-agenda-check-type t 'agenda)
23038 (setq org-agenda-include-diary (not org-agenda-include-diary))
23039 (org-agenda-redo)
23040 (org-agenda-set-mode-name)
23041 (message "Diary inclusion turned %s"
23042 (if org-agenda-include-diary "on" "off")))
23044 (defun org-agenda-toggle-time-grid ()
23045 "Toggle time grid in an agenda buffer."
23046 (interactive)
23047 (org-agenda-check-type t 'agenda)
23048 (setq org-agenda-use-time-grid (not org-agenda-use-time-grid))
23049 (org-agenda-redo)
23050 (org-agenda-set-mode-name)
23051 (message "Time-grid turned %s"
23052 (if org-agenda-use-time-grid "on" "off")))
23054 (defun org-agenda-set-mode-name ()
23055 "Set the mode name to indicate all the small mode settings."
23056 (setq mode-name
23057 (concat "Org-Agenda"
23058 (if (equal org-agenda-ndays 1) " Day" "")
23059 (if (equal org-agenda-ndays 7) " Week" "")
23060 (if org-agenda-follow-mode " Follow" "")
23061 (if org-agenda-include-diary " Diary" "")
23062 (if org-agenda-use-time-grid " Grid" "")
23063 (if org-agenda-show-log " Log" "")))
23064 (force-mode-line-update))
23066 (defun org-agenda-post-command-hook ()
23067 (and (eolp) (not (bolp)) (backward-char 1))
23068 (setq org-agenda-type (get-text-property (point) 'org-agenda-type))
23069 (if (and org-agenda-follow-mode
23070 (get-text-property (point) 'org-marker))
23071 (org-agenda-show)))
23073 (defun org-agenda-show-priority ()
23074 "Show the priority of the current item.
23075 This priority is composed of the main priority given with the [#A] cookies,
23076 and by additional input from the age of a schedules or deadline entry."
23077 (interactive)
23078 (let* ((pri (get-text-property (point-at-bol) 'priority)))
23079 (message "Priority is %d" (if pri pri -1000))))
23081 (defun org-agenda-show-tags ()
23082 "Show the tags applicable to the current item."
23083 (interactive)
23084 (let* ((tags (get-text-property (point-at-bol) 'tags)))
23085 (if tags
23086 (message "Tags are :%s:"
23087 (org-no-properties (mapconcat 'identity tags ":")))
23088 (message "No tags associated with this line"))))
23090 (defun org-agenda-goto (&optional highlight)
23091 "Go to the Org-mode file which contains the item at point."
23092 (interactive)
23093 (let* ((marker (or (get-text-property (point) 'org-marker)
23094 (org-agenda-error)))
23095 (buffer (marker-buffer marker))
23096 (pos (marker-position marker)))
23097 (switch-to-buffer-other-window buffer)
23098 (widen)
23099 (goto-char pos)
23100 (when (org-mode-p)
23101 (org-show-context 'agenda)
23102 (save-excursion
23103 (and (outline-next-heading)
23104 (org-flag-heading nil)))) ; show the next heading
23105 (recenter (/ (window-height) 2))
23106 (run-hooks 'org-agenda-after-show-hook)
23107 (and highlight (org-highlight (point-at-bol) (point-at-eol)))))
23109 (defvar org-agenda-after-show-hook nil
23110 "Normal hook run after an item has been shown from the agenda.
23111 Point is in the buffer where the item originated.")
23113 (defun org-agenda-kill ()
23114 "Kill the entry or subtree belonging to the current agenda entry."
23115 (interactive)
23116 (or (eq major-mode 'org-agenda-mode) (error "Not in agenda"))
23117 (let* ((marker (or (get-text-property (point) 'org-marker)
23118 (org-agenda-error)))
23119 (buffer (marker-buffer marker))
23120 (pos (marker-position marker))
23121 (type (get-text-property (point) 'type))
23122 dbeg dend (n 0) conf)
23123 (org-with-remote-undo buffer
23124 (with-current-buffer buffer
23125 (save-excursion
23126 (goto-char pos)
23127 (if (and (org-mode-p) (not (member type '("sexp"))))
23128 (setq dbeg (progn (org-back-to-heading t) (point))
23129 dend (org-end-of-subtree t t))
23130 (setq dbeg (point-at-bol)
23131 dend (min (point-max) (1+ (point-at-eol)))))
23132 (goto-char dbeg)
23133 (while (re-search-forward "^[ \t]*\\S-" dend t) (setq n (1+ n)))))
23134 (setq conf (or (eq t org-agenda-confirm-kill)
23135 (and (numberp org-agenda-confirm-kill)
23136 (> n org-agenda-confirm-kill))))
23137 (and conf
23138 (not (y-or-n-p
23139 (format "Delete entry with %d lines in buffer \"%s\"? "
23140 n (buffer-name buffer))))
23141 (error "Abort"))
23142 (org-remove-subtree-entries-from-agenda buffer dbeg dend)
23143 (with-current-buffer buffer (delete-region dbeg dend))
23144 (message "Agenda item and source killed"))))
23146 (defun org-agenda-archive ()
23147 "Kill the entry or subtree belonging to the current agenda entry."
23148 (interactive)
23149 (or (eq major-mode 'org-agenda-mode) (error "Not in agenda"))
23150 (let* ((marker (or (get-text-property (point) 'org-marker)
23151 (org-agenda-error)))
23152 (buffer (marker-buffer marker))
23153 (pos (marker-position marker)))
23154 (org-with-remote-undo buffer
23155 (with-current-buffer buffer
23156 (if (org-mode-p)
23157 (save-excursion
23158 (goto-char pos)
23159 (org-remove-subtree-entries-from-agenda)
23160 (org-back-to-heading t)
23161 (org-archive-subtree))
23162 (error "Archiving works only in Org-mode files"))))))
23164 (defun org-remove-subtree-entries-from-agenda (&optional buf beg end)
23165 "Remove all lines in the agenda that correspond to a given subtree.
23166 The subtree is the one in buffer BUF, starting at BEG and ending at END.
23167 If this information is not given, the function uses the tree at point."
23168 (let ((buf (or buf (current-buffer))) m p)
23169 (save-excursion
23170 (unless (and beg end)
23171 (org-back-to-heading t)
23172 (setq beg (point))
23173 (org-end-of-subtree t)
23174 (setq end (point)))
23175 (set-buffer (get-buffer org-agenda-buffer-name))
23176 (save-excursion
23177 (goto-char (point-max))
23178 (beginning-of-line 1)
23179 (while (not (bobp))
23180 (when (and (setq m (get-text-property (point) 'org-marker))
23181 (equal buf (marker-buffer m))
23182 (setq p (marker-position m))
23183 (>= p beg)
23184 (<= p end))
23185 (let ((inhibit-read-only t))
23186 (delete-region (point-at-bol) (1+ (point-at-eol)))))
23187 (beginning-of-line 0))))))
23189 (defun org-agenda-open-link ()
23190 "Follow the link in the current line, if any."
23191 (interactive)
23192 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local)
23193 (save-excursion
23194 (save-restriction
23195 (narrow-to-region (point-at-bol) (point-at-eol))
23196 (org-open-at-point))))
23198 (defun org-agenda-copy-local-variable (var)
23199 "Get a variable from a referenced buffer and install it here."
23200 (let ((m (get-text-property (point) 'org-marker)))
23201 (when (and m (buffer-live-p (marker-buffer m)))
23202 (org-set-local var (with-current-buffer (marker-buffer m)
23203 (symbol-value var))))))
23205 (defun org-agenda-switch-to (&optional delete-other-windows)
23206 "Go to the Org-mode file which contains the item at point."
23207 (interactive)
23208 (let* ((marker (or (get-text-property (point) 'org-marker)
23209 (org-agenda-error)))
23210 (buffer (marker-buffer marker))
23211 (pos (marker-position marker)))
23212 (switch-to-buffer buffer)
23213 (and delete-other-windows (delete-other-windows))
23214 (widen)
23215 (goto-char pos)
23216 (when (org-mode-p)
23217 (org-show-context 'agenda)
23218 (save-excursion
23219 (and (outline-next-heading)
23220 (org-flag-heading nil)))))) ; show the next heading
23222 (defun org-agenda-goto-mouse (ev)
23223 "Go to the Org-mode file which contains the item at the mouse click."
23224 (interactive "e")
23225 (mouse-set-point ev)
23226 (org-agenda-goto))
23228 (defun org-agenda-show ()
23229 "Display the Org-mode file which contains the item at point."
23230 (interactive)
23231 (let ((win (selected-window)))
23232 (org-agenda-goto t)
23233 (select-window win)))
23235 (defun org-agenda-recenter (arg)
23236 "Display the Org-mode file which contains the item at point and recenter."
23237 (interactive "P")
23238 (let ((win (selected-window)))
23239 (org-agenda-goto t)
23240 (recenter arg)
23241 (select-window win)))
23243 (defun org-agenda-show-mouse (ev)
23244 "Display the Org-mode file which contains the item at the mouse click."
23245 (interactive "e")
23246 (mouse-set-point ev)
23247 (org-agenda-show))
23249 (defun org-agenda-check-no-diary ()
23250 "Check if the entry is a diary link and abort if yes."
23251 (if (get-text-property (point) 'org-agenda-diary-link)
23252 (org-agenda-error)))
23254 (defun org-agenda-error ()
23255 (error "Command not allowed in this line"))
23257 (defun org-agenda-tree-to-indirect-buffer ()
23258 "Show the subtree corresponding to the current entry in an indirect buffer.
23259 This calls the command `org-tree-to-indirect-buffer' from the original
23260 Org-mode buffer.
23261 With numerical prefix arg ARG, go up to this level and then take that tree.
23262 With a C-u prefix, make a separate frame for this tree (i.e. don't use the
23263 dedicated frame)."
23264 (interactive)
23265 (org-agenda-check-no-diary)
23266 (let* ((marker (or (get-text-property (point) 'org-marker)
23267 (org-agenda-error)))
23268 (buffer (marker-buffer marker))
23269 (pos (marker-position marker)))
23270 (with-current-buffer buffer
23271 (save-excursion
23272 (goto-char pos)
23273 (call-interactively 'org-tree-to-indirect-buffer)))))
23275 (defvar org-last-heading-marker (make-marker)
23276 "Marker pointing to the headline that last changed its TODO state
23277 by a remote command from the agenda.")
23279 (defun org-agenda-todo-nextset ()
23280 "Switch TODO entry to next sequence."
23281 (interactive)
23282 (org-agenda-todo 'nextset))
23284 (defun org-agenda-todo-previousset ()
23285 "Switch TODO entry to previous sequence."
23286 (interactive)
23287 (org-agenda-todo 'previousset))
23289 (defun org-agenda-todo (&optional arg)
23290 "Cycle TODO state of line at point, also in Org-mode file.
23291 This changes the line at point, all other lines in the agenda referring to
23292 the same tree node, and the headline of the tree node in the Org-mode file."
23293 (interactive "P")
23294 (org-agenda-check-no-diary)
23295 (let* ((col (current-column))
23296 (marker (or (get-text-property (point) 'org-marker)
23297 (org-agenda-error)))
23298 (buffer (marker-buffer marker))
23299 (pos (marker-position marker))
23300 (hdmarker (get-text-property (point) 'org-hd-marker))
23301 (inhibit-read-only t)
23302 newhead)
23303 (org-with-remote-undo buffer
23304 (with-current-buffer buffer
23305 (widen)
23306 (goto-char pos)
23307 (org-show-context 'agenda)
23308 (save-excursion
23309 (and (outline-next-heading)
23310 (org-flag-heading nil))) ; show the next heading
23311 (org-todo arg)
23312 (and (bolp) (forward-char 1))
23313 (setq newhead (org-get-heading))
23314 (save-excursion
23315 (org-back-to-heading)
23316 (move-marker org-last-heading-marker (point))))
23317 (beginning-of-line 1)
23318 (save-excursion
23319 (org-agenda-change-all-lines newhead hdmarker 'fixface))
23320 (move-to-column col))))
23322 (defun org-agenda-change-all-lines (newhead hdmarker &optional fixface)
23323 "Change all lines in the agenda buffer which match HDMARKER.
23324 The new content of the line will be NEWHEAD (as modified by
23325 `org-format-agenda-item'). HDMARKER is checked with
23326 `equal' against all `org-hd-marker' text properties in the file.
23327 If FIXFACE is non-nil, the face of each item is modified acording to
23328 the new TODO state."
23329 (let* ((inhibit-read-only t)
23330 props m pl undone-face done-face finish new dotime cat tags)
23331 (save-excursion
23332 (goto-char (point-max))
23333 (beginning-of-line 1)
23334 (while (not finish)
23335 (setq finish (bobp))
23336 (when (and (setq m (get-text-property (point) 'org-hd-marker))
23337 (equal m hdmarker))
23338 (setq props (text-properties-at (point))
23339 dotime (get-text-property (point) 'dotime)
23340 cat (get-text-property (point) 'org-category)
23341 tags (get-text-property (point) 'tags)
23342 new (org-format-agenda-item "x" newhead cat tags dotime 'noprefix)
23343 pl (get-text-property (point) 'prefix-length)
23344 undone-face (get-text-property (point) 'undone-face)
23345 done-face (get-text-property (point) 'done-face))
23346 (move-to-column pl)
23347 (cond
23348 ((equal new "")
23349 (beginning-of-line 1)
23350 (and (looking-at ".*\n?") (replace-match "")))
23351 ((looking-at ".*")
23352 (replace-match new t t)
23353 (beginning-of-line 1)
23354 (add-text-properties (point-at-bol) (point-at-eol) props)
23355 (when fixface
23356 (add-text-properties
23357 (point-at-bol) (point-at-eol)
23358 (list 'face
23359 (if org-last-todo-state-is-todo
23360 undone-face done-face))))
23361 (org-agenda-highlight-todo 'line)
23362 (beginning-of-line 1))
23363 (t (error "Line update did not work"))))
23364 (beginning-of-line 0)))
23365 (org-finalize-agenda)))
23367 (defun org-agenda-align-tags (&optional line)
23368 "Align all tags in agenda items to `org-agenda-tags-column'."
23369 (let ((inhibit-read-only t) l c)
23370 (save-excursion
23371 (goto-char (if line (point-at-bol) (point-min)))
23372 (while (re-search-forward (org-re "\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$")
23373 (if line (point-at-eol) nil) t)
23374 (add-text-properties
23375 (match-beginning 2) (match-end 2)
23376 (list 'face (delq nil (list 'org-tag (get-text-property
23377 (match-beginning 2) 'face)))))
23378 (setq l (- (match-end 2) (match-beginning 2))
23379 c (if (< org-agenda-tags-column 0)
23380 (- (abs org-agenda-tags-column) l)
23381 org-agenda-tags-column))
23382 (delete-region (match-beginning 1) (match-end 1))
23383 (goto-char (match-beginning 1))
23384 (insert (org-add-props
23385 (make-string (max 1 (- c (current-column))) ?\ )
23386 (text-properties-at (point))))))))
23388 (defun org-agenda-priority-up ()
23389 "Increase the priority of line at point, also in Org-mode file."
23390 (interactive)
23391 (org-agenda-priority 'up))
23393 (defun org-agenda-priority-down ()
23394 "Decrease the priority of line at point, also in Org-mode file."
23395 (interactive)
23396 (org-agenda-priority 'down))
23398 (defun org-agenda-priority (&optional force-direction)
23399 "Set the priority of line at point, also in Org-mode file.
23400 This changes the line at point, all other lines in the agenda referring to
23401 the same tree node, and the headline of the tree node in the Org-mode file."
23402 (interactive)
23403 (org-agenda-check-no-diary)
23404 (let* ((marker (or (get-text-property (point) 'org-marker)
23405 (org-agenda-error)))
23406 (hdmarker (get-text-property (point) 'org-hd-marker))
23407 (buffer (marker-buffer hdmarker))
23408 (pos (marker-position hdmarker))
23409 (inhibit-read-only t)
23410 newhead)
23411 (org-with-remote-undo buffer
23412 (with-current-buffer buffer
23413 (widen)
23414 (goto-char pos)
23415 (org-show-context 'agenda)
23416 (save-excursion
23417 (and (outline-next-heading)
23418 (org-flag-heading nil))) ; show the next heading
23419 (funcall 'org-priority force-direction)
23420 (end-of-line 1)
23421 (setq newhead (org-get-heading)))
23422 (org-agenda-change-all-lines newhead hdmarker)
23423 (beginning-of-line 1))))
23425 (defun org-get-tags-at (&optional pos)
23426 "Get a list of all headline tags applicable at POS.
23427 POS defaults to point. If tags are inherited, the list contains
23428 the targets in the same sequence as the headlines appear, i.e.
23429 the tags of the current headline come last."
23430 (interactive)
23431 (let (tags lastpos)
23432 (save-excursion
23433 (save-restriction
23434 (widen)
23435 (goto-char (or pos (point)))
23436 (save-match-data
23437 (condition-case nil
23438 (progn
23439 (org-back-to-heading t)
23440 (while (not (equal lastpos (point)))
23441 (setq lastpos (point))
23442 (if (looking-at (org-re "[^\r\n]+?:\\([[:alnum:]_@:]+\\):[ \t]*$"))
23443 (setq tags (append (org-split-string
23444 (org-match-string-no-properties 1) ":")
23445 tags)))
23446 (or org-use-tag-inheritance (error ""))
23447 (org-up-heading-all 1)))
23448 (error nil))))
23449 tags)))
23451 ;; FIXME: should fix the tags property of the agenda line.
23452 (defun org-agenda-set-tags ()
23453 "Set tags for the current headline."
23454 (interactive)
23455 (org-agenda-check-no-diary)
23456 (if (and (org-region-active-p) (interactive-p))
23457 (call-interactively 'org-change-tag-in-region)
23458 (org-agenda-show) ;;; FIXME This is a stupid hack and should not be needed
23459 (let* ((hdmarker (or (get-text-property (point) 'org-hd-marker)
23460 (org-agenda-error)))
23461 (buffer (marker-buffer hdmarker))
23462 (pos (marker-position hdmarker))
23463 (inhibit-read-only t)
23464 newhead)
23465 (org-with-remote-undo buffer
23466 (with-current-buffer buffer
23467 (widen)
23468 (goto-char pos)
23469 (save-excursion
23470 (org-show-context 'agenda))
23471 (save-excursion
23472 (and (outline-next-heading)
23473 (org-flag-heading nil))) ; show the next heading
23474 (goto-char pos)
23475 (call-interactively 'org-set-tags)
23476 (end-of-line 1)
23477 (setq newhead (org-get-heading)))
23478 (org-agenda-change-all-lines newhead hdmarker)
23479 (beginning-of-line 1)))))
23481 (defun org-agenda-toggle-archive-tag ()
23482 "Toggle the archive tag for the current entry."
23483 (interactive)
23484 (org-agenda-check-no-diary)
23485 (org-agenda-show) ;;; FIXME This is a stupid hack and should not be needed
23486 (let* ((hdmarker (or (get-text-property (point) 'org-hd-marker)
23487 (org-agenda-error)))
23488 (buffer (marker-buffer hdmarker))
23489 (pos (marker-position hdmarker))
23490 (inhibit-read-only t)
23491 newhead)
23492 (org-with-remote-undo buffer
23493 (with-current-buffer buffer
23494 (widen)
23495 (goto-char pos)
23496 (org-show-context 'agenda)
23497 (save-excursion
23498 (and (outline-next-heading)
23499 (org-flag-heading nil))) ; show the next heading
23500 (call-interactively 'org-toggle-archive-tag)
23501 (end-of-line 1)
23502 (setq newhead (org-get-heading)))
23503 (org-agenda-change-all-lines newhead hdmarker)
23504 (beginning-of-line 1))))
23506 (defun org-agenda-date-later (arg &optional what)
23507 "Change the date of this item to one day later."
23508 (interactive "p")
23509 (org-agenda-check-type t 'agenda 'timeline)
23510 (org-agenda-check-no-diary)
23511 (let* ((marker (or (get-text-property (point) 'org-marker)
23512 (org-agenda-error)))
23513 (buffer (marker-buffer marker))
23514 (pos (marker-position marker)))
23515 (org-with-remote-undo buffer
23516 (with-current-buffer buffer
23517 (widen)
23518 (goto-char pos)
23519 (if (not (org-at-timestamp-p))
23520 (error "Cannot find time stamp"))
23521 (org-timestamp-change arg (or what 'day)))
23522 (org-agenda-show-new-time marker org-last-changed-timestamp))
23523 (message "Time stamp changed to %s" org-last-changed-timestamp)))
23525 (defun org-agenda-date-earlier (arg &optional what)
23526 "Change the date of this item to one day earlier."
23527 (interactive "p")
23528 (org-agenda-date-later (- arg) what))
23530 (defun org-agenda-show-new-time (marker stamp &optional prefix)
23531 "Show new date stamp via text properties."
23532 ;; We use text properties to make this undoable
23533 (let ((inhibit-read-only t))
23534 (setq stamp (concat " " prefix " => " stamp))
23535 (save-excursion
23536 (goto-char (point-max))
23537 (while (not (bobp))
23538 (when (equal marker (get-text-property (point) 'org-marker))
23539 (move-to-column (- (window-width) (length stamp)) t)
23540 (if (featurep 'xemacs)
23541 ;; Use `duplicable' property to trigger undo recording
23542 (let ((ex (make-extent nil nil))
23543 (gl (make-glyph stamp)))
23544 (set-glyph-face gl 'secondary-selection)
23545 (set-extent-properties
23546 ex (list 'invisible t 'end-glyph gl 'duplicable t))
23547 (insert-extent ex (1- (point)) (point-at-eol)))
23548 (add-text-properties
23549 (1- (point)) (point-at-eol)
23550 (list 'display (org-add-props stamp nil
23551 'face 'secondary-selection))))
23552 (beginning-of-line 1))
23553 (beginning-of-line 0)))))
23555 (defun org-agenda-date-prompt (arg)
23556 "Change the date of this item. Date is prompted for, with default today.
23557 The prefix ARG is passed to the `org-time-stamp' command and can therefore
23558 be used to request time specification in the time stamp."
23559 (interactive "P")
23560 (org-agenda-check-type t 'agenda 'timeline)
23561 (org-agenda-check-no-diary)
23562 (let* ((marker (or (get-text-property (point) 'org-marker)
23563 (org-agenda-error)))
23564 (buffer (marker-buffer marker))
23565 (pos (marker-position marker)))
23566 (org-with-remote-undo buffer
23567 (with-current-buffer buffer
23568 (widen)
23569 (goto-char pos)
23570 (if (not (org-at-timestamp-p))
23571 (error "Cannot find time stamp"))
23572 (org-time-stamp arg)
23573 (message "Time stamp changed to %s" org-last-changed-timestamp)))))
23575 (defun org-agenda-schedule (arg)
23576 "Schedule the item at point."
23577 (interactive "P")
23578 (org-agenda-check-type t 'agenda 'timeline 'todo 'tags)
23579 (org-agenda-check-no-diary)
23580 (let* ((marker (or (get-text-property (point) 'org-marker)
23581 (org-agenda-error)))
23582 (type (marker-insertion-type marker))
23583 (buffer (marker-buffer marker))
23584 (pos (marker-position marker))
23585 (org-insert-labeled-timestamps-at-point nil)
23587 (when type (message "%s" type) (sit-for 3))
23588 (set-marker-insertion-type marker t)
23589 (org-with-remote-undo buffer
23590 (with-current-buffer buffer
23591 (widen)
23592 (goto-char pos)
23593 (setq ts (org-schedule arg)))
23594 (org-agenda-show-new-time marker ts "S"))
23595 (message "Item scheduled for %s" ts)))
23597 (defun org-agenda-deadline (arg)
23598 "Schedule the item at point."
23599 (interactive "P")
23600 (org-agenda-check-type t 'agenda 'timeline 'todo 'tags)
23601 (org-agenda-check-no-diary)
23602 (let* ((marker (or (get-text-property (point) 'org-marker)
23603 (org-agenda-error)))
23604 (buffer (marker-buffer marker))
23605 (pos (marker-position marker))
23606 (org-insert-labeled-timestamps-at-point nil)
23608 (org-with-remote-undo buffer
23609 (with-current-buffer buffer
23610 (widen)
23611 (goto-char pos)
23612 (setq ts (org-deadline arg)))
23613 (org-agenda-show-new-time marker ts "S"))
23614 (message "Deadline for this item set to %s" ts)))
23616 (defun org-get-heading (&optional no-tags)
23617 "Return the heading of the current entry, without the stars."
23618 (save-excursion
23619 (org-back-to-heading t)
23620 (if (looking-at
23621 (if no-tags
23622 (org-re "\\*+[ \t]+\\([^\n\r]*?\\)\\([ \t]+:[[:alnum:]:_@]+:[ \t]*\\)?$")
23623 "\\*+[ \t]+\\([^\r\n]*\\)"))
23624 (match-string 1) "")))
23626 (defun org-agenda-clock-in (&optional arg)
23627 "Start the clock on the currently selected item."
23628 (interactive "P")
23629 (org-agenda-check-no-diary)
23630 (let* ((marker (or (get-text-property (point) 'org-marker)
23631 (org-agenda-error)))
23632 (pos (marker-position marker)))
23633 (org-with-remote-undo (marker-buffer marker)
23634 (with-current-buffer (marker-buffer marker)
23635 (widen)
23636 (goto-char pos)
23637 (org-clock-in)))))
23639 (defun org-agenda-clock-out (&optional arg)
23640 "Stop the currently running clock."
23641 (interactive "P")
23642 (unless (marker-buffer org-clock-marker)
23643 (error "No running clock"))
23644 (org-with-remote-undo (marker-buffer org-clock-marker)
23645 (org-clock-out)))
23647 (defun org-agenda-clock-cancel (&optional arg)
23648 "Cancel the currently running clock."
23649 (interactive "P")
23650 (unless (marker-buffer org-clock-marker)
23651 (error "No running clock"))
23652 (org-with-remote-undo (marker-buffer org-clock-marker)
23653 (org-clock-cancel)))
23655 (defun org-agenda-diary-entry ()
23656 "Make a diary entry, like the `i' command from the calendar.
23657 All the standard commands work: block, weekly etc."
23658 (interactive)
23659 (org-agenda-check-type t 'agenda 'timeline)
23660 (require 'diary-lib)
23661 (let* ((char (progn
23662 (message "Diary entry: [d]ay [w]eekly [m]onthly [y]early [a]nniversary [b]lock [c]yclic")
23663 (read-char-exclusive)))
23664 (cmd (cdr (assoc char
23665 '((?d . insert-diary-entry)
23666 (?w . insert-weekly-diary-entry)
23667 (?m . insert-monthly-diary-entry)
23668 (?y . insert-yearly-diary-entry)
23669 (?a . insert-anniversary-diary-entry)
23670 (?b . insert-block-diary-entry)
23671 (?c . insert-cyclic-diary-entry)))))
23672 (oldf (symbol-function 'calendar-cursor-to-date))
23673 ; (buf (get-file-buffer (substitute-in-file-name diary-file)))
23674 (point (point))
23675 (mark (or (mark t) (point))))
23676 (unless cmd
23677 (error "No command associated with <%c>" char))
23678 (unless (and (get-text-property point 'day)
23679 (or (not (equal ?b char))
23680 (get-text-property mark 'day)))
23681 (error "Don't know which date to use for diary entry"))
23682 ;; We implement this by hacking the `calendar-cursor-to-date' function
23683 ;; and the `calendar-mark-ring' variable. Saves a lot of code.
23684 (let ((calendar-mark-ring
23685 (list (calendar-gregorian-from-absolute
23686 (or (get-text-property mark 'day)
23687 (get-text-property point 'day))))))
23688 (unwind-protect
23689 (progn
23690 (fset 'calendar-cursor-to-date
23691 (lambda (&optional error)
23692 (calendar-gregorian-from-absolute
23693 (get-text-property point 'day))))
23694 (call-interactively cmd))
23695 (fset 'calendar-cursor-to-date oldf)))))
23698 (defun org-agenda-execute-calendar-command (cmd)
23699 "Execute a calendar command from the agenda, with the date associated to
23700 the cursor position."
23701 (org-agenda-check-type t 'agenda 'timeline)
23702 (require 'diary-lib)
23703 (unless (get-text-property (point) 'day)
23704 (error "Don't know which date to use for calendar command"))
23705 (let* ((oldf (symbol-function 'calendar-cursor-to-date))
23706 (point (point))
23707 (date (calendar-gregorian-from-absolute
23708 (get-text-property point 'day)))
23709 ;; the following 3 vars are needed in the calendar
23710 (displayed-day (extract-calendar-day date))
23711 (displayed-month (extract-calendar-month date))
23712 (displayed-year (extract-calendar-year date)))
23713 (unwind-protect
23714 (progn
23715 (fset 'calendar-cursor-to-date
23716 (lambda (&optional error)
23717 (calendar-gregorian-from-absolute
23718 (get-text-property point 'day))))
23719 (call-interactively cmd))
23720 (fset 'calendar-cursor-to-date oldf))))
23722 (defun org-agenda-phases-of-moon ()
23723 "Display the phases of the moon for the 3 months around the cursor date."
23724 (interactive)
23725 (org-agenda-execute-calendar-command 'calendar-phases-of-moon))
23727 (defun org-agenda-holidays ()
23728 "Display the holidays for the 3 months around the cursor date."
23729 (interactive)
23730 (org-agenda-execute-calendar-command 'list-calendar-holidays))
23732 (defvar calendar-longitude)
23733 (defvar calendar-latitude)
23734 (defvar calendar-location-name)
23736 (defun org-agenda-sunrise-sunset (arg)
23737 "Display sunrise and sunset for the cursor date.
23738 Latitude and longitude can be specified with the variables
23739 `calendar-latitude' and `calendar-longitude'. When called with prefix
23740 argument, latitude and longitude will be prompted for."
23741 (interactive "P")
23742 (require 'solar)
23743 (let ((calendar-longitude (if arg nil calendar-longitude))
23744 (calendar-latitude (if arg nil calendar-latitude))
23745 (calendar-location-name
23746 (if arg "the given coordinates" calendar-location-name)))
23747 (org-agenda-execute-calendar-command 'calendar-sunrise-sunset)))
23749 (defun org-agenda-goto-calendar ()
23750 "Open the Emacs calendar with the date at the cursor."
23751 (interactive)
23752 (org-agenda-check-type t 'agenda 'timeline)
23753 (let* ((day (or (get-text-property (point) 'day)
23754 (error "Don't know which date to open in calendar")))
23755 (date (calendar-gregorian-from-absolute day))
23756 (calendar-move-hook nil)
23757 (view-calendar-holidays-initially nil)
23758 (view-diary-entries-initially nil))
23759 (calendar)
23760 (calendar-goto-date date)))
23762 (defun org-calendar-goto-agenda ()
23763 "Compute the Org-mode agenda for the calendar date displayed at the cursor.
23764 This is a command that has to be installed in `calendar-mode-map'."
23765 (interactive)
23766 (org-agenda-list nil (calendar-absolute-from-gregorian
23767 (calendar-cursor-to-date))
23768 nil))
23770 (defun org-agenda-convert-date ()
23771 (interactive)
23772 (org-agenda-check-type t 'agenda 'timeline)
23773 (let ((day (get-text-property (point) 'day))
23774 date s)
23775 (unless day
23776 (error "Don't know which date to convert"))
23777 (setq date (calendar-gregorian-from-absolute day))
23778 (setq s (concat
23779 "Gregorian: " (calendar-date-string date) "\n"
23780 "ISO: " (calendar-iso-date-string date) "\n"
23781 "Day of Yr: " (calendar-day-of-year-string date) "\n"
23782 "Julian: " (calendar-julian-date-string date) "\n"
23783 "Astron. JD: " (calendar-astro-date-string date)
23784 " (Julian date number at noon UTC)\n"
23785 "Hebrew: " (calendar-hebrew-date-string date) " (until sunset)\n"
23786 "Islamic: " (calendar-islamic-date-string date) " (until sunset)\n"
23787 "French: " (calendar-french-date-string date) "\n"
23788 "Baha'i: " (calendar-bahai-date-string date) " (until sunset)\n"
23789 "Mayan: " (calendar-mayan-date-string date) "\n"
23790 "Coptic: " (calendar-coptic-date-string date) "\n"
23791 "Ethiopic: " (calendar-ethiopic-date-string date) "\n"
23792 "Persian: " (calendar-persian-date-string date) "\n"
23793 "Chinese: " (calendar-chinese-date-string date) "\n"))
23794 (with-output-to-temp-buffer "*Dates*"
23795 (princ s))
23796 (if (fboundp 'fit-window-to-buffer)
23797 (fit-window-to-buffer (get-buffer-window "*Dates*")))))
23800 ;;;; Embedded LaTeX
23802 (defvar org-cdlatex-mode-map (make-sparse-keymap)
23803 "Keymap for the minor `org-cdlatex-mode'.")
23805 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
23806 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
23807 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
23808 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
23809 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
23811 (defvar org-cdlatex-texmathp-advice-is-done nil
23812 "Flag remembering if we have applied the advice to texmathp already.")
23814 (define-minor-mode org-cdlatex-mode
23815 "Toggle the minor `org-cdlatex-mode'.
23816 This mode supports entering LaTeX environment and math in LaTeX fragments
23817 in Org-mode.
23818 \\{org-cdlatex-mode-map}"
23819 nil " OCDL" nil
23820 (when org-cdlatex-mode (require 'cdlatex))
23821 (unless org-cdlatex-texmathp-advice-is-done
23822 (setq org-cdlatex-texmathp-advice-is-done t)
23823 (defadvice texmathp (around org-math-always-on activate)
23824 "Always return t in org-mode buffers.
23825 This is because we want to insert math symbols without dollars even outside
23826 the LaTeX math segments. If Orgmode thinks that point is actually inside
23827 en embedded LaTeX fragement, let texmathp do its job.
23828 \\[org-cdlatex-mode-map]"
23829 (interactive)
23830 (let (p)
23831 (cond
23832 ((not (org-mode-p)) ad-do-it)
23833 ((eq this-command 'cdlatex-math-symbol)
23834 (setq ad-return-value t
23835 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
23837 (let ((p (org-inside-LaTeX-fragment-p)))
23838 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
23839 (setq ad-return-value t
23840 texmathp-why '("Org-mode embedded math" . 0))
23841 (if p ad-do-it)))))))))
23843 (defun turn-on-org-cdlatex ()
23844 "Unconditionally turn on `org-cdlatex-mode'."
23845 (org-cdlatex-mode 1))
23847 (defun org-inside-LaTeX-fragment-p ()
23848 "Test if point is inside a LaTeX fragment.
23849 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
23850 sequence appearing also before point.
23851 Even though the matchers for math are configurable, this function assumes
23852 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
23853 delimiters are skipped when they have been removed by customization.
23854 The return value is nil, or a cons cell with the delimiter and
23855 and the position of this delimiter.
23857 This function does a reasonably good job, but can locally be fooled by
23858 for example currency specifications. For example it will assume being in
23859 inline math after \"$22.34\". The LaTeX fragment formatter will only format
23860 fragments that are properly closed, but during editing, we have to live
23861 with the uncertainty caused by missing closing delimiters. This function
23862 looks only before point, not after."
23863 (catch 'exit
23864 (let ((pos (point))
23865 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
23866 (lim (progn
23867 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
23868 (point)))
23869 dd-on str (start 0) m re)
23870 (goto-char pos)
23871 (when dodollar
23872 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
23873 re (nth 1 (assoc "$" org-latex-regexps)))
23874 (while (string-match re str start)
23875 (cond
23876 ((= (match-end 0) (length str))
23877 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
23878 ((= (match-end 0) (- (length str) 5))
23879 (throw 'exit nil))
23880 (t (setq start (match-end 0))))))
23881 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
23882 (goto-char pos)
23883 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
23884 (and (match-beginning 2) (throw 'exit nil))
23885 ;; count $$
23886 (while (re-search-backward "\\$\\$" lim t)
23887 (setq dd-on (not dd-on)))
23888 (goto-char pos)
23889 (if dd-on (cons "$$" m))))))
23892 (defun org-try-cdlatex-tab ()
23893 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
23894 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
23895 - inside a LaTeX fragment, or
23896 - after the first word in a line, where an abbreviation expansion could
23897 insert a LaTeX environment."
23898 (when org-cdlatex-mode
23899 (cond
23900 ((save-excursion
23901 (skip-chars-backward "a-zA-Z0-9*")
23902 (skip-chars-backward " \t")
23903 (bolp))
23904 (cdlatex-tab) t)
23905 ((org-inside-LaTeX-fragment-p)
23906 (cdlatex-tab) t)
23907 (t nil))))
23909 (defun org-cdlatex-underscore-caret (&optional arg)
23910 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
23911 Revert to the normal definition outside of these fragments."
23912 (interactive "P")
23913 (if (org-inside-LaTeX-fragment-p)
23914 (call-interactively 'cdlatex-sub-superscript)
23915 (let (org-cdlatex-mode)
23916 (call-interactively (key-binding (vector last-input-event))))))
23918 (defun org-cdlatex-math-modify (&optional arg)
23919 "Execute `cdlatex-math-modify' in LaTeX fragments.
23920 Revert to the normal definition outside of these fragments."
23921 (interactive "P")
23922 (if (org-inside-LaTeX-fragment-p)
23923 (call-interactively 'cdlatex-math-modify)
23924 (let (org-cdlatex-mode)
23925 (call-interactively (key-binding (vector last-input-event))))))
23927 (defvar org-latex-fragment-image-overlays nil
23928 "List of overlays carrying the images of latex fragments.")
23929 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
23931 (defun org-remove-latex-fragment-image-overlays ()
23932 "Remove all overlays with LaTeX fragment images in current buffer."
23933 (mapc 'org-delete-overlay org-latex-fragment-image-overlays)
23934 (setq org-latex-fragment-image-overlays nil))
23936 (defun org-preview-latex-fragment (&optional subtree)
23937 "Preview the LaTeX fragment at point, or all locally or globally.
23938 If the cursor is in a LaTeX fragment, create the image and overlay
23939 it over the source code. If there is no fragment at point, display
23940 all fragments in the current text, from one headline to the next. With
23941 prefix SUBTREE, display all fragments in the current subtree. With a
23942 double prefix `C-u C-u', or when the cursor is before the first headline,
23943 display all fragments in the buffer.
23944 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
23945 (interactive "P")
23946 (org-remove-latex-fragment-image-overlays)
23947 (save-excursion
23948 (save-restriction
23949 (let (beg end at msg)
23950 (cond
23951 ((or (equal subtree '(16))
23952 (not (save-excursion
23953 (re-search-backward (concat "^" outline-regexp) nil t))))
23954 (setq beg (point-min) end (point-max)
23955 msg "Creating images for buffer...%s"))
23956 ((equal subtree '(4))
23957 (org-back-to-heading)
23958 (setq beg (point) end (org-end-of-subtree t)
23959 msg "Creating images for subtree...%s"))
23961 (if (setq at (org-inside-LaTeX-fragment-p))
23962 (goto-char (max (point-min) (- (cdr at) 2)))
23963 (org-back-to-heading))
23964 (setq beg (point) end (progn (outline-next-heading) (point))
23965 msg (if at "Creating image...%s"
23966 "Creating images for entry...%s"))))
23967 (message msg "")
23968 (narrow-to-region beg end)
23969 (goto-char beg)
23970 (org-format-latex
23971 (concat "ltxpng/" (file-name-sans-extension
23972 (file-name-nondirectory
23973 buffer-file-name)))
23974 default-directory 'overlays msg at 'forbuffer)
23975 (message msg "done. Use `C-c C-c' to remove images.")))))
23977 (defvar org-latex-regexps
23978 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
23979 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
23980 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
23981 ("$" "\\([^$]\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([ .,?;:'\")\000]\\|$\\)" 2 nil)
23982 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
23983 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 t)
23984 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 t))
23985 "Regular expressions for matching embedded LaTeX.")
23987 (defun org-format-latex (prefix &optional dir overlays msg at forbuffer)
23988 "Replace LaTeX fragments with links to an image, and produce images."
23989 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
23990 (let* ((prefixnodir (file-name-nondirectory prefix))
23991 (absprefix (expand-file-name prefix dir))
23992 (todir (file-name-directory absprefix))
23993 (opt org-format-latex-options)
23994 (matchers (plist-get opt :matchers))
23995 (re-list org-latex-regexps)
23996 (cnt 0) txt link beg end re e checkdir
23997 m n block linkfile movefile ov)
23998 ;; Check if there are old images files with this prefix, and remove them
23999 (when (file-directory-p todir)
24000 (mapc 'delete-file
24001 (directory-files
24002 todir 'full
24003 (concat (regexp-quote prefixnodir) "_[0-9]+\\.png$"))))
24004 ;; Check the different regular expressions
24005 (while (setq e (pop re-list))
24006 (setq m (car e) re (nth 1 e) n (nth 2 e)
24007 block (if (nth 3 e) "\n\n" ""))
24008 (when (member m matchers)
24009 (goto-char (point-min))
24010 (while (re-search-forward re nil t)
24011 (when (or (not at) (equal (cdr at) (match-beginning n)))
24012 (setq txt (match-string n)
24013 beg (match-beginning n) end (match-end n)
24014 cnt (1+ cnt)
24015 linkfile (format "%s_%04d.png" prefix cnt)
24016 movefile (format "%s_%04d.png" absprefix cnt)
24017 link (concat block "[[file:" linkfile "]]" block))
24018 (if msg (message msg cnt))
24019 (goto-char beg)
24020 (unless checkdir ; make sure the directory exists
24021 (setq checkdir t)
24022 (or (file-directory-p todir) (make-directory todir)))
24023 (org-create-formula-image
24024 txt movefile opt forbuffer)
24025 (if overlays
24026 (progn
24027 (setq ov (org-make-overlay beg end))
24028 (if (featurep 'xemacs)
24029 (progn
24030 (org-overlay-put ov 'invisible t)
24031 (org-overlay-put
24032 ov 'end-glyph
24033 (make-glyph (vector 'png :file movefile))))
24034 (org-overlay-put
24035 ov 'display
24036 (list 'image :type 'png :file movefile :ascent 'center)))
24037 (push ov org-latex-fragment-image-overlays)
24038 (goto-char end))
24039 (delete-region beg end)
24040 (insert link))))))))
24042 ;; This function borrows from Ganesh Swami's latex2png.el
24043 (defun org-create-formula-image (string tofile options buffer)
24044 (let* ((tmpdir (if (featurep 'xemacs)
24045 (temp-directory)
24046 temporary-file-directory))
24047 (texfilebase (make-temp-name
24048 (expand-file-name "orgtex" tmpdir)))
24049 (texfile (concat texfilebase ".tex"))
24050 (dvifile (concat texfilebase ".dvi"))
24051 (pngfile (concat texfilebase ".png"))
24052 (fnh (face-attribute 'default :height nil))
24053 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
24054 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
24055 (fg (or (plist-get options (if buffer :foreground :html-foreground))
24056 "Black"))
24057 (bg (or (plist-get options (if buffer :background :html-background))
24058 "Transparent")))
24059 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
24060 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
24061 (with-temp-file texfile
24062 (insert org-format-latex-header
24063 "\n\\begin{document}\n" string "\n\\end{document}\n"))
24064 (let ((dir default-directory))
24065 (condition-case nil
24066 (progn
24067 (cd tmpdir)
24068 (call-process "latex" nil nil nil texfile))
24069 (error nil))
24070 (cd dir))
24071 (if (not (file-exists-p dvifile))
24072 (progn (message "Failed to create dvi file from %s" texfile) nil)
24073 (call-process "dvipng" nil nil nil
24074 "-E" "-fg" fg "-bg" bg
24075 "-D" dpi
24076 ;;"-x" scale "-y" scale
24077 "-T" "tight"
24078 "-o" pngfile
24079 dvifile)
24080 (if (not (file-exists-p pngfile))
24081 (progn (message "Failed to create png file from %s" texfile) nil)
24082 ;; Use the requested file name and clean up
24083 (copy-file pngfile tofile 'replace)
24084 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
24085 (delete-file (concat texfilebase e)))
24086 pngfile))))
24088 (defun org-dvipng-color (attr)
24089 "Return an rgb color specification for dvipng."
24090 (apply 'format "rgb %s %s %s"
24091 (mapcar 'org-normalize-color
24092 (color-values (face-attribute 'default attr nil)))))
24094 (defun org-normalize-color (value)
24095 "Return string to be used as color value for an RGB component."
24096 (format "%g" (/ value 65535.0)))
24098 ;;;; Exporting
24100 ;;; Variables, constants, and parameter plists
24102 (defconst org-level-max 20)
24104 (defvar org-export-html-preamble nil
24105 "Preamble, to be inserted just after <body>. Set by publishing functions.")
24106 (defvar org-export-html-postamble nil
24107 "Preamble, to be inserted just before </body>. Set by publishing functions.")
24108 (defvar org-export-html-auto-preamble t
24109 "Should default preamble be inserted? Set by publishing functions.")
24110 (defvar org-export-html-auto-postamble t
24111 "Should default postamble be inserted? Set by publishing functions.")
24112 (defvar org-current-export-file nil) ; dynamically scoped parameter
24113 (defvar org-current-export-dir nil) ; dynamically scoped parameter
24116 (defconst org-export-plist-vars
24117 '((:language . org-export-default-language)
24118 (:customtime . org-display-custom-times)
24119 (:headline-levels . org-export-headline-levels)
24120 (:section-numbers . org-export-with-section-numbers)
24121 (:table-of-contents . org-export-with-toc)
24122 (:preserve-breaks . org-export-preserve-breaks)
24123 (:archived-trees . org-export-with-archived-trees)
24124 (:emphasize . org-export-with-emphasize)
24125 (:sub-superscript . org-export-with-sub-superscripts)
24126 (:special-strings . org-export-with-special-strings)
24127 (:footnotes . org-export-with-footnotes)
24128 (:drawers . org-export-with-drawers)
24129 (:tags . org-export-with-tags)
24130 (:TeX-macros . org-export-with-TeX-macros)
24131 (:LaTeX-fragments . org-export-with-LaTeX-fragments)
24132 (:skip-before-1st-heading . org-export-skip-text-before-1st-heading)
24133 (:fixed-width . org-export-with-fixed-width)
24134 (:timestamps . org-export-with-timestamps)
24135 (:author-info . org-export-author-info)
24136 (:time-stamp-file . org-export-time-stamp-file)
24137 (:tables . org-export-with-tables)
24138 (:table-auto-headline . org-export-highlight-first-table-line)
24139 (:style . org-export-html-style)
24140 (:agenda-style . org-agenda-export-html-style)
24141 (:convert-org-links . org-export-html-link-org-files-as-html)
24142 (:inline-images . org-export-html-inline-images)
24143 (:html-extension . org-export-html-extension)
24144 (:html-table-tag . org-export-html-table-tag)
24145 (:expand-quoted-html . org-export-html-expand)
24146 (:timestamp . org-export-html-with-timestamp)
24147 (:publishing-directory . org-export-publishing-directory)
24148 (:preamble . org-export-html-preamble)
24149 (:postamble . org-export-html-postamble)
24150 (:auto-preamble . org-export-html-auto-preamble)
24151 (:auto-postamble . org-export-html-auto-postamble)
24152 (:author . user-full-name)
24153 (:email . user-mail-address)))
24155 (defun org-default-export-plist ()
24156 "Return the property list with default settings for the export variables."
24157 (let ((l org-export-plist-vars) rtn e)
24158 (while (setq e (pop l))
24159 (setq rtn (cons (car e) (cons (symbol-value (cdr e)) rtn))))
24160 rtn))
24162 (defun org-infile-export-plist ()
24163 "Return the property list with file-local settings for export."
24164 (save-excursion
24165 (save-restriction
24166 (widen)
24167 (goto-char 0)
24168 (let ((re (org-make-options-regexp
24169 '("TITLE" "AUTHOR" "DATE" "EMAIL" "TEXT" "OPTIONS" "LANGUAGE")))
24170 p key val text options)
24171 (while (re-search-forward re nil t)
24172 (setq key (org-match-string-no-properties 1)
24173 val (org-match-string-no-properties 2))
24174 (cond
24175 ((string-equal key "TITLE") (setq p (plist-put p :title val)))
24176 ((string-equal key "AUTHOR")(setq p (plist-put p :author val)))
24177 ((string-equal key "EMAIL") (setq p (plist-put p :email val)))
24178 ((string-equal key "DATE") (setq p (plist-put p :date val)))
24179 ((string-equal key "LANGUAGE") (setq p (plist-put p :language val)))
24180 ((string-equal key "TEXT")
24181 (setq text (if text (concat text "\n" val) val)))
24182 ((string-equal key "OPTIONS") (setq options val))))
24183 (setq p (plist-put p :text text))
24184 (when options
24185 (let ((op '(("H" . :headline-levels)
24186 ("num" . :section-numbers)
24187 ("toc" . :table-of-contents)
24188 ("\\n" . :preserve-breaks)
24189 ("@" . :expand-quoted-html)
24190 (":" . :fixed-width)
24191 ("|" . :tables)
24192 ("^" . :sub-superscript)
24193 ("-" . :special-strings)
24194 ("f" . :footnotes)
24195 ("d" . :drawers)
24196 ("tags" . :tags)
24197 ("*" . :emphasize)
24198 ("TeX" . :TeX-macros)
24199 ("LaTeX" . :LaTeX-fragments)
24200 ("skip" . :skip-before-1st-heading)
24201 ("author" . :author-info)
24202 ("timestamp" . :time-stamp-file)))
24204 (while (setq o (pop op))
24205 (if (string-match (concat (regexp-quote (car o))
24206 ":\\([^ \t\n\r;,.]*\\)")
24207 options)
24208 (setq p (plist-put p (cdr o)
24209 (car (read-from-string
24210 (match-string 1 options)))))))))
24211 p))))
24213 (defun org-export-directory (type plist)
24214 (let* ((val (plist-get plist :publishing-directory))
24215 (dir (if (listp val)
24216 (or (cdr (assoc type val)) ".")
24217 val)))
24218 dir))
24220 (defun org-skip-comments (lines)
24221 "Skip lines starting with \"#\" and subtrees starting with COMMENT."
24222 (let ((re1 (concat "^\\(\\*+\\)[ \t]+" org-comment-string))
24223 (re2 "^\\(\\*+\\)[ \t\n\r]")
24224 (case-fold-search nil)
24225 rtn line level)
24226 (while (setq line (pop lines))
24227 (cond
24228 ((and (string-match re1 line)
24229 (setq level (- (match-end 1) (match-beginning 1))))
24230 ;; Beginning of a COMMENT subtree. Skip it.
24231 (while (and (setq line (pop lines))
24232 (or (not (string-match re2 line))
24233 (> (- (match-end 1) (match-beginning 1)) level))))
24234 (setq lines (cons line lines)))
24235 ((string-match "^#" line)
24236 ;; an ordinary comment line
24238 ((and org-export-table-remove-special-lines
24239 (string-match "^[ \t]*|" line)
24240 (or (string-match "^[ \t]*| *[!_^] *|" line)
24241 (and (string-match "| *<[0-9]+> *|" line)
24242 (not (string-match "| *[^ <|]" line)))))
24243 ;; a special table line that should be removed
24245 (t (setq rtn (cons line rtn)))))
24246 (nreverse rtn)))
24248 (defun org-export (&optional arg)
24249 (interactive)
24250 (let ((help "[t] insert the export option template
24251 \[v] limit export to visible part of outline tree
24253 \[a] export as ASCII
24255 \[h] export as HTML
24256 \[H] export as HTML to temporary buffer
24257 \[R] export region as HTML
24258 \[b] export as HTML and browse immediately
24259 \[x] export as XOXO
24261 \[l] export as LaTeX
24262 \[L] export as LaTeX to temporary buffer
24264 \[i] export current file as iCalendar file
24265 \[I] export all agenda files as iCalendar files
24266 \[c] export agenda files into combined iCalendar file
24268 \[F] publish current file
24269 \[P] publish current project
24270 \[X] publish... (project will be prompted for)
24271 \[A] publish all projects")
24272 (cmds
24273 '((?t . org-insert-export-options-template)
24274 (?v . org-export-visible)
24275 (?a . org-export-as-ascii)
24276 (?h . org-export-as-html)
24277 (?b . org-export-as-html-and-open)
24278 (?H . org-export-as-html-to-buffer)
24279 (?R . org-export-region-as-html)
24280 (?x . org-export-as-xoxo)
24281 (?l . org-export-as-latex)
24282 (?L . org-export-as-latex-to-buffer)
24283 (?i . org-export-icalendar-this-file)
24284 (?I . org-export-icalendar-all-agenda-files)
24285 (?c . org-export-icalendar-combine-agenda-files)
24286 (?F . org-publish-current-file)
24287 (?P . org-publish-current-project)
24288 (?X . org-publish)
24289 (?A . org-publish-all)))
24290 r1 r2 ass)
24291 (save-window-excursion
24292 (delete-other-windows)
24293 (with-output-to-temp-buffer "*Org Export/Publishing Help*"
24294 (princ help))
24295 (message "Select command: ")
24296 (setq r1 (read-char-exclusive)))
24297 (setq r2 (if (< r1 27) (+ r1 96) r1))
24298 (if (setq ass (assq r2 cmds))
24299 (call-interactively (cdr ass))
24300 (error "No command associated with key %c" r1))))
24302 (defconst org-html-entities
24303 '(("nbsp")
24304 ("iexcl")
24305 ("cent")
24306 ("pound")
24307 ("curren")
24308 ("yen")
24309 ("brvbar")
24310 ("vert" . "&#124;")
24311 ("sect")
24312 ("uml")
24313 ("copy")
24314 ("ordf")
24315 ("laquo")
24316 ("not")
24317 ("shy")
24318 ("reg")
24319 ("macr")
24320 ("deg")
24321 ("plusmn")
24322 ("sup2")
24323 ("sup3")
24324 ("acute")
24325 ("micro")
24326 ("para")
24327 ("middot")
24328 ("odot"."o")
24329 ("star"."*")
24330 ("cedil")
24331 ("sup1")
24332 ("ordm")
24333 ("raquo")
24334 ("frac14")
24335 ("frac12")
24336 ("frac34")
24337 ("iquest")
24338 ("Agrave")
24339 ("Aacute")
24340 ("Acirc")
24341 ("Atilde")
24342 ("Auml")
24343 ("Aring") ("AA"."&Aring;")
24344 ("AElig")
24345 ("Ccedil")
24346 ("Egrave")
24347 ("Eacute")
24348 ("Ecirc")
24349 ("Euml")
24350 ("Igrave")
24351 ("Iacute")
24352 ("Icirc")
24353 ("Iuml")
24354 ("ETH")
24355 ("Ntilde")
24356 ("Ograve")
24357 ("Oacute")
24358 ("Ocirc")
24359 ("Otilde")
24360 ("Ouml")
24361 ("times")
24362 ("Oslash")
24363 ("Ugrave")
24364 ("Uacute")
24365 ("Ucirc")
24366 ("Uuml")
24367 ("Yacute")
24368 ("THORN")
24369 ("szlig")
24370 ("agrave")
24371 ("aacute")
24372 ("acirc")
24373 ("atilde")
24374 ("auml")
24375 ("aring")
24376 ("aelig")
24377 ("ccedil")
24378 ("egrave")
24379 ("eacute")
24380 ("ecirc")
24381 ("euml")
24382 ("igrave")
24383 ("iacute")
24384 ("icirc")
24385 ("iuml")
24386 ("eth")
24387 ("ntilde")
24388 ("ograve")
24389 ("oacute")
24390 ("ocirc")
24391 ("otilde")
24392 ("ouml")
24393 ("divide")
24394 ("oslash")
24395 ("ugrave")
24396 ("uacute")
24397 ("ucirc")
24398 ("uuml")
24399 ("yacute")
24400 ("thorn")
24401 ("yuml")
24402 ("fnof")
24403 ("Alpha")
24404 ("Beta")
24405 ("Gamma")
24406 ("Delta")
24407 ("Epsilon")
24408 ("Zeta")
24409 ("Eta")
24410 ("Theta")
24411 ("Iota")
24412 ("Kappa")
24413 ("Lambda")
24414 ("Mu")
24415 ("Nu")
24416 ("Xi")
24417 ("Omicron")
24418 ("Pi")
24419 ("Rho")
24420 ("Sigma")
24421 ("Tau")
24422 ("Upsilon")
24423 ("Phi")
24424 ("Chi")
24425 ("Psi")
24426 ("Omega")
24427 ("alpha")
24428 ("beta")
24429 ("gamma")
24430 ("delta")
24431 ("epsilon")
24432 ("varepsilon"."&epsilon;")
24433 ("zeta")
24434 ("eta")
24435 ("theta")
24436 ("iota")
24437 ("kappa")
24438 ("lambda")
24439 ("mu")
24440 ("nu")
24441 ("xi")
24442 ("omicron")
24443 ("pi")
24444 ("rho")
24445 ("sigmaf") ("varsigma"."&sigmaf;")
24446 ("sigma")
24447 ("tau")
24448 ("upsilon")
24449 ("phi")
24450 ("chi")
24451 ("psi")
24452 ("omega")
24453 ("thetasym") ("vartheta"."&thetasym;")
24454 ("upsih")
24455 ("piv")
24456 ("bull") ("bullet"."&bull;")
24457 ("hellip") ("dots"."&hellip;")
24458 ("prime")
24459 ("Prime")
24460 ("oline")
24461 ("frasl")
24462 ("weierp")
24463 ("image")
24464 ("real")
24465 ("trade")
24466 ("alefsym")
24467 ("larr") ("leftarrow"."&larr;") ("gets"."&larr;")
24468 ("uarr") ("uparrow"."&uarr;")
24469 ("rarr") ("to"."&rarr;") ("rightarrow"."&rarr;")
24470 ("darr")("downarrow"."&darr;")
24471 ("harr") ("leftrightarrow"."&harr;")
24472 ("crarr") ("hookleftarrow"."&crarr;") ; has round hook, not quite CR
24473 ("lArr") ("Leftarrow"."&lArr;")
24474 ("uArr") ("Uparrow"."&uArr;")
24475 ("rArr") ("Rightarrow"."&rArr;")
24476 ("dArr") ("Downarrow"."&dArr;")
24477 ("hArr") ("Leftrightarrow"."&hArr;")
24478 ("forall")
24479 ("part") ("partial"."&part;")
24480 ("exist") ("exists"."&exist;")
24481 ("empty") ("emptyset"."&empty;")
24482 ("nabla")
24483 ("isin") ("in"."&isin;")
24484 ("notin")
24485 ("ni")
24486 ("prod")
24487 ("sum")
24488 ("minus")
24489 ("lowast") ("ast"."&lowast;")
24490 ("radic")
24491 ("prop") ("proptp"."&prop;")
24492 ("infin") ("infty"."&infin;")
24493 ("ang") ("angle"."&ang;")
24494 ("and") ("wedge"."&and;")
24495 ("or") ("vee"."&or;")
24496 ("cap")
24497 ("cup")
24498 ("int")
24499 ("there4")
24500 ("sim")
24501 ("cong") ("simeq"."&cong;")
24502 ("asymp")("approx"."&asymp;")
24503 ("ne") ("neq"."&ne;")
24504 ("equiv")
24505 ("le")
24506 ("ge")
24507 ("sub") ("subset"."&sub;")
24508 ("sup") ("supset"."&sup;")
24509 ("nsub")
24510 ("sube")
24511 ("supe")
24512 ("oplus")
24513 ("otimes")
24514 ("perp")
24515 ("sdot") ("cdot"."&sdot;")
24516 ("lceil")
24517 ("rceil")
24518 ("lfloor")
24519 ("rfloor")
24520 ("lang")
24521 ("rang")
24522 ("loz") ("Diamond"."&loz;")
24523 ("spades") ("spadesuit"."&spades;")
24524 ("clubs") ("clubsuit"."&clubs;")
24525 ("hearts") ("diamondsuit"."&hearts;")
24526 ("diams") ("diamondsuit"."&diams;")
24527 ("smile"."&#9786;") ("blacksmile"."&#9787;") ("sad"."&#9785;")
24528 ("quot")
24529 ("amp")
24530 ("lt")
24531 ("gt")
24532 ("OElig")
24533 ("oelig")
24534 ("Scaron")
24535 ("scaron")
24536 ("Yuml")
24537 ("circ")
24538 ("tilde")
24539 ("ensp")
24540 ("emsp")
24541 ("thinsp")
24542 ("zwnj")
24543 ("zwj")
24544 ("lrm")
24545 ("rlm")
24546 ("ndash")
24547 ("mdash")
24548 ("lsquo")
24549 ("rsquo")
24550 ("sbquo")
24551 ("ldquo")
24552 ("rdquo")
24553 ("bdquo")
24554 ("dagger")
24555 ("Dagger")
24556 ("permil")
24557 ("lsaquo")
24558 ("rsaquo")
24559 ("euro")
24561 ("arccos"."arccos")
24562 ("arcsin"."arcsin")
24563 ("arctan"."arctan")
24564 ("arg"."arg")
24565 ("cos"."cos")
24566 ("cosh"."cosh")
24567 ("cot"."cot")
24568 ("coth"."coth")
24569 ("csc"."csc")
24570 ("deg"."deg")
24571 ("det"."det")
24572 ("dim"."dim")
24573 ("exp"."exp")
24574 ("gcd"."gcd")
24575 ("hom"."hom")
24576 ("inf"."inf")
24577 ("ker"."ker")
24578 ("lg"."lg")
24579 ("lim"."lim")
24580 ("liminf"."liminf")
24581 ("limsup"."limsup")
24582 ("ln"."ln")
24583 ("log"."log")
24584 ("max"."max")
24585 ("min"."min")
24586 ("Pr"."Pr")
24587 ("sec"."sec")
24588 ("sin"."sin")
24589 ("sinh"."sinh")
24590 ("sup"."sup")
24591 ("tan"."tan")
24592 ("tanh"."tanh")
24594 "Entities for TeX->HTML translation.
24595 Entries can be like (\"ent\"), in which case \"\\ent\" will be translated to
24596 \"&ent;\". An entry can also be a dotted pair like (\"ent\".\"&other;\").
24597 In that case, \"\\ent\" will be translated to \"&other;\".
24598 The list contains HTML entities for Latin-1, Greek and other symbols.
24599 It is supplemented by a number of commonly used TeX macros with appropriate
24600 translations. There is currently no way for users to extend this.")
24602 ;;; General functions for all backends
24604 (defun org-cleaned-string-for-export (string &rest parameters)
24605 "Cleanup a buffer STRING so that links can be created safely."
24606 (interactive)
24607 (let* ((re-radio (and org-target-link-regexp
24608 (concat "\\([^<]\\)\\(" org-target-link-regexp "\\)")))
24609 (re-plain-link (concat "\\([^[<]\\)" org-plain-link-re))
24610 (re-angle-link (concat "\\([^[]\\)" org-angle-link-re))
24611 (re-archive (concat ":" org-archive-tag ":"))
24612 (re-quote (concat "^\\*+[ \t]+" org-quote-string "\\>"))
24613 (re-commented (concat "^\\*+[ \t]+" org-comment-string "\\>"))
24614 (htmlp (plist-get parameters :for-html))
24615 (asciip (plist-get parameters :for-ascii))
24616 (latexp (plist-get parameters :for-LaTeX))
24617 (commentsp (plist-get parameters :comments))
24618 (archived-trees (plist-get parameters :archived-trees))
24619 (inhibit-read-only t)
24620 (drawers org-drawers)
24621 (exp-drawers (plist-get parameters :drawers))
24622 (outline-regexp "\\*+ ")
24623 a b xx
24624 rtn p)
24625 (with-current-buffer (get-buffer-create " org-mode-tmp")
24626 (erase-buffer)
24627 (insert string)
24628 ;; Remove license-to-kill stuff
24629 (while (setq p (text-property-any (point-min) (point-max)
24630 :org-license-to-kill t))
24631 (delete-region p (next-single-property-change p :org-license-to-kill)))
24633 (let ((org-inhibit-startup t)) (org-mode))
24634 (untabify (point-min) (point-max))
24636 ;; Get rid of drawers
24637 (unless (eq t exp-drawers)
24638 (goto-char (point-min))
24639 (let ((re (concat "^[ \t]*:\\("
24640 (mapconcat
24641 'identity
24642 (org-delete-all exp-drawers
24643 (copy-sequence drawers))
24644 "\\|")
24645 "\\):[ \t]*\n\\([^@]*?\n\\)?[ \t]*:END:[ \t]*\n")))
24646 (while (re-search-forward re nil t)
24647 (replace-match ""))))
24649 ;; Get the correct stuff before the first headline
24650 (when (plist-get parameters :skip-before-1st-heading)
24651 (goto-char (point-min))
24652 (when (re-search-forward "^\\*+[ \t]" nil t)
24653 (delete-region (point-min) (match-beginning 0))
24654 (goto-char (point-min))
24655 (insert "\n")))
24656 (when (plist-get parameters :add-text)
24657 (goto-char (point-min))
24658 (insert (plist-get parameters :add-text) "\n"))
24660 ;; Get rid of archived trees
24661 (when (not (eq archived-trees t))
24662 (goto-char (point-min))
24663 (while (re-search-forward re-archive nil t)
24664 (if (not (org-on-heading-p t))
24665 (org-end-of-subtree t)
24666 (beginning-of-line 1)
24667 (setq a (if archived-trees
24668 (1+ (point-at-eol)) (point))
24669 b (org-end-of-subtree t))
24670 (if (> b a) (delete-region a b)))))
24672 ;; Find targets in comments and move them out of comments,
24673 ;; but mark them as targets that should be invisible
24674 (goto-char (point-min))
24675 (while (re-search-forward "^#.*?\\(<<<?[^>\r\n]+>>>?\\).*" nil t)
24676 (replace-match "\\1(INVISIBLE)"))
24678 ;; Protect backend specific stuff, throw away the others.
24679 (let ((formatters
24680 `((,htmlp "HTML" "BEGIN_HTML" "END_HTML")
24681 (,asciip "ASCII" "BEGIN_ASCII" "END_ASCII")
24682 (,latexp "LaTeX" "BEGIN_LaTeX" "END_LaTeX")))
24683 fmt)
24684 (goto-char (point-min))
24685 (while (re-search-forward "^#\\+BEGIN_EXAMPLE[ \t]*\n" nil t)
24686 (goto-char (match-end 0))
24687 (while (not (looking-at "#\\+END_EXAMPLE"))
24688 (insert ": ")
24689 (beginning-of-line 2)))
24690 (goto-char (point-min))
24691 (while (re-search-forward "^[ \t]*:.*\\(\n[ \t]*:.*\\)*" nil t)
24692 (add-text-properties (match-beginning 0) (match-end 0)
24693 '(org-protected t)))
24694 (while formatters
24695 (setq fmt (pop formatters))
24696 (when (car fmt)
24697 (goto-char (point-min))
24698 (while (re-search-forward (concat "^#\\+" (cadr fmt)
24699 ":[ \t]*\\(.*\\)") nil t)
24700 (replace-match "\\1" t)
24701 (add-text-properties
24702 (point-at-bol) (min (1+ (point-at-eol)) (point-max))
24703 '(org-protected t))))
24704 (goto-char (point-min))
24705 (while (re-search-forward
24706 (concat "^#\\+"
24707 (caddr fmt) "\\>.*\\(\\(\n.*\\)*?\n\\)#\\+"
24708 (cadddr fmt) "\\>.*\n?") nil t)
24709 (if (car fmt)
24710 (add-text-properties (match-beginning 1) (1+ (match-end 1))
24711 '(org-protected t))
24712 (delete-region (match-beginning 0) (match-end 0))))))
24714 ;; Protect quoted subtrees
24715 (goto-char (point-min))
24716 (while (re-search-forward re-quote nil t)
24717 (goto-char (match-beginning 0))
24718 (end-of-line 1)
24719 (add-text-properties (point) (org-end-of-subtree t)
24720 '(org-protected t)))
24722 ;; Protect verbatim elements
24723 (goto-char (point-min))
24724 (while (re-search-forward org-verbatim-re nil t)
24725 (add-text-properties (match-beginning 4) (match-end 4)
24726 '(org-protected t))
24727 (goto-char (1+ (match-end 4))))
24729 ;; Remove subtrees that are commented
24730 (goto-char (point-min))
24731 (while (re-search-forward re-commented nil t)
24732 (goto-char (match-beginning 0))
24733 (delete-region (point) (org-end-of-subtree t)))
24735 ;; Remove special table lines
24736 (when org-export-table-remove-special-lines
24737 (goto-char (point-min))
24738 (while (re-search-forward "^[ \t]*|" nil t)
24739 (beginning-of-line 1)
24740 (if (or (looking-at "[ \t]*| *[!_^] *|")
24741 (and (looking-at ".*?| *<[0-9]+> *|")
24742 (not (looking-at ".*?| *[^ <|]"))))
24743 (delete-region (max (point-min) (1- (point-at-bol)))
24744 (point-at-eol))
24745 (end-of-line 1))))
24747 ;; Specific LaTeX stuff
24748 (when latexp
24749 (require 'org-export-latex nil)
24750 (org-export-latex-cleaned-string))
24752 (when asciip
24753 (org-export-ascii-clean-string))
24755 ;; Specific HTML stuff
24756 (when htmlp
24757 ;; Convert LaTeX fragments to images
24758 (when (plist-get parameters :LaTeX-fragments)
24759 (org-format-latex
24760 (concat "ltxpng/" (file-name-sans-extension
24761 (file-name-nondirectory
24762 org-current-export-file)))
24763 org-current-export-dir nil "Creating LaTeX image %s"))
24764 (message "Exporting..."))
24766 ;; Remove or replace comments
24767 (goto-char (point-min))
24768 (while (re-search-forward "^#\\(.*\n?\\)" nil t)
24769 (if commentsp
24770 (progn (add-text-properties
24771 (match-beginning 0) (match-end 0) '(org-protected t))
24772 (replace-match (format commentsp (match-string 1)) t t))
24773 (replace-match "")))
24775 ;; Find matches for radio targets and turn them into internal links
24776 (goto-char (point-min))
24777 (when re-radio
24778 (while (re-search-forward re-radio nil t)
24779 (org-if-unprotected
24780 (replace-match "\\1[[\\2]]"))))
24782 ;; Find all links that contain a newline and put them into a single line
24783 (goto-char (point-min))
24784 (while (re-search-forward "\\(\\(\\[\\|\\]\\)\\[[^]]*?\\)[ \t]*\n[ \t]*\\([^]]*\\]\\(\\[\\|\\]\\)\\)" nil t)
24785 (org-if-unprotected
24786 (replace-match "\\1 \\3")
24787 (goto-char (match-beginning 0))))
24790 ;; Normalize links: Convert angle and plain links into bracket links
24791 ;; Expand link abbreviations
24792 (goto-char (point-min))
24793 (while (re-search-forward re-plain-link nil t)
24794 (goto-char (1- (match-end 0)))
24795 (org-if-unprotected
24796 (let* ((s (concat (match-string 1) "[[" (match-string 2)
24797 ":" (match-string 3) "]]")))
24798 ;; added 'org-link face to links
24799 (put-text-property 0 (length s) 'face 'org-link s)
24800 (replace-match s t t))))
24801 (goto-char (point-min))
24802 (while (re-search-forward re-angle-link nil t)
24803 (goto-char (1- (match-end 0)))
24804 (org-if-unprotected
24805 (let* ((s (concat (match-string 1) "[[" (match-string 2)
24806 ":" (match-string 3) "]]")))
24807 (put-text-property 0 (length s) 'face 'org-link s)
24808 (replace-match s t t))))
24809 (goto-char (point-min))
24810 (while (re-search-forward org-bracket-link-regexp nil t)
24811 (org-if-unprotected
24812 (let* ((s (concat "[[" (setq xx (save-match-data
24813 (org-link-expand-abbrev (match-string 1))))
24815 (if (match-end 3)
24816 (match-string 2)
24817 (concat "[" xx "]"))
24818 "]")))
24819 (put-text-property 0 (length s) 'face 'org-link s)
24820 (replace-match s t t))))
24822 ;; Find multiline emphasis and put them into single line
24823 (when (plist-get parameters :emph-multiline)
24824 (goto-char (point-min))
24825 (while (re-search-forward org-emph-re nil t)
24826 (if (not (= (char-after (match-beginning 3))
24827 (char-after (match-beginning 4))))
24828 (org-if-unprotected
24829 (subst-char-in-region (match-beginning 0) (match-end 0)
24830 ?\n ?\ t)
24831 (goto-char (1- (match-end 0))))
24832 (goto-char (1+ (match-beginning 0))))))
24834 (setq rtn (buffer-string)))
24835 (kill-buffer " org-mode-tmp")
24836 rtn))
24838 (defun org-export-grab-title-from-buffer ()
24839 "Get a title for the current document, from looking at the buffer."
24840 (let ((inhibit-read-only t))
24841 (save-excursion
24842 (goto-char (point-min))
24843 (let ((end (save-excursion (outline-next-heading) (point))))
24844 (when (re-search-forward "^[ \t]*[^|# \t\r\n].*\n" end t)
24845 ;; Mark the line so that it will not be exported as normal text.
24846 (org-unmodified
24847 (add-text-properties (match-beginning 0) (match-end 0)
24848 (list :org-license-to-kill t)))
24849 ;; Return the title string
24850 (org-trim (match-string 0)))))))
24852 (defun org-export-get-title-from-subtree ()
24853 "Return subtree title and exclude it from export."
24854 (let (title (m (mark)))
24855 (save-excursion
24856 (goto-char (region-beginning))
24857 (when (and (org-at-heading-p)
24858 (>= (org-end-of-subtree t t) (region-end)))
24859 ;; This is a subtree, we take the title from the first heading
24860 (goto-char (region-beginning))
24861 (looking-at org-todo-line-regexp)
24862 (setq title (match-string 3))
24863 (org-unmodified
24864 (add-text-properties (point) (1+ (point-at-eol))
24865 (list :org-license-to-kill t)))))
24866 title))
24868 (defun org-solidify-link-text (s &optional alist)
24869 "Take link text and make a safe target out of it."
24870 (save-match-data
24871 (let* ((rtn
24872 (mapconcat
24873 'identity
24874 (org-split-string s "[ \t\r\n]+") "--"))
24875 (a (assoc rtn alist)))
24876 (or (cdr a) rtn))))
24878 (defun org-get-min-level (lines)
24879 "Get the minimum level in LINES."
24880 (let ((re "^\\(\\*+\\) ") l min)
24881 (catch 'exit
24882 (while (setq l (pop lines))
24883 (if (string-match re l)
24884 (throw 'exit (org-tr-level (length (match-string 1 l))))))
24885 1)))
24887 ;; Variable holding the vector with section numbers
24888 (defvar org-section-numbers (make-vector org-level-max 0))
24890 (defun org-init-section-numbers ()
24891 "Initialize the vector for the section numbers."
24892 (let* ((level -1)
24893 (numbers (nreverse (org-split-string "" "\\.")))
24894 (depth (1- (length org-section-numbers)))
24895 (i depth) number-string)
24896 (while (>= i 0)
24897 (if (> i level)
24898 (aset org-section-numbers i 0)
24899 (setq number-string (or (car numbers) "0"))
24900 (if (string-match "\\`[A-Z]\\'" number-string)
24901 (aset org-section-numbers i
24902 (- (string-to-char number-string) ?A -1))
24903 (aset org-section-numbers i (string-to-number number-string)))
24904 (pop numbers))
24905 (setq i (1- i)))))
24907 (defun org-section-number (&optional level)
24908 "Return a string with the current section number.
24909 When LEVEL is non-nil, increase section numbers on that level."
24910 (let* ((depth (1- (length org-section-numbers))) idx n (string ""))
24911 (when level
24912 (when (> level -1)
24913 (aset org-section-numbers
24914 level (1+ (aref org-section-numbers level))))
24915 (setq idx (1+ level))
24916 (while (<= idx depth)
24917 (if (not (= idx 1))
24918 (aset org-section-numbers idx 0))
24919 (setq idx (1+ idx))))
24920 (setq idx 0)
24921 (while (<= idx depth)
24922 (setq n (aref org-section-numbers idx))
24923 (setq string (concat string (if (not (string= string "")) "." "")
24924 (int-to-string n)))
24925 (setq idx (1+ idx)))
24926 (save-match-data
24927 (if (string-match "\\`\\([@0]\\.\\)+" string)
24928 (setq string (replace-match "" t nil string)))
24929 (if (string-match "\\(\\.0\\)+\\'" string)
24930 (setq string (replace-match "" t nil string))))
24931 string))
24933 ;;; ASCII export
24935 (defvar org-last-level nil) ; dynamically scoped variable
24936 (defvar org-min-level nil) ; dynamically scoped variable
24937 (defvar org-levels-open nil) ; dynamically scoped parameter
24938 (defvar org-ascii-current-indentation nil) ; For communication
24940 (defun org-export-as-ascii (arg)
24941 "Export the outline as a pretty ASCII file.
24942 If there is an active region, export only the region.
24943 The prefix ARG specifies how many levels of the outline should become
24944 underlined headlines. The default is 3."
24945 (interactive "P")
24946 (setq-default org-todo-line-regexp org-todo-line-regexp)
24947 (let* ((opt-plist (org-combine-plists (org-default-export-plist)
24948 (org-infile-export-plist)))
24949 (region-p (org-region-active-p))
24950 (subtree-p
24951 (when region-p
24952 (save-excursion
24953 (goto-char (region-beginning))
24954 (and (org-at-heading-p)
24955 (>= (org-end-of-subtree t t) (region-end))))))
24956 (custom-times org-display-custom-times)
24957 (org-ascii-current-indentation '(0 . 0))
24958 (level 0) line txt
24959 (umax nil)
24960 (umax-toc nil)
24961 (case-fold-search nil)
24962 (filename (concat (file-name-as-directory
24963 (org-export-directory :ascii opt-plist))
24964 (file-name-sans-extension
24965 (or (and subtree-p
24966 (org-entry-get (region-beginning)
24967 "EXPORT_FILE_NAME" t))
24968 (file-name-nondirectory buffer-file-name)))
24969 ".txt"))
24970 (filename (if (equal (file-truename filename)
24971 (file-truename buffer-file-name))
24972 (concat filename ".txt")
24973 filename))
24974 (buffer (find-file-noselect filename))
24975 (org-levels-open (make-vector org-level-max nil))
24976 (odd org-odd-levels-only)
24977 (date (plist-get opt-plist :date))
24978 (author (plist-get opt-plist :author))
24979 (title (or (and subtree-p (org-export-get-title-from-subtree))
24980 (plist-get opt-plist :title)
24981 (and (not
24982 (plist-get opt-plist :skip-before-1st-heading))
24983 (org-export-grab-title-from-buffer))
24984 (file-name-sans-extension
24985 (file-name-nondirectory buffer-file-name))))
24986 (email (plist-get opt-plist :email))
24987 (language (plist-get opt-plist :language))
24988 (quote-re0 (concat "^[ \t]*" org-quote-string "\\>"))
24989 ; (quote-re (concat "^\\(\\*+\\)\\([ \t]*" org-quote-string "\\>\\)"))
24990 (todo nil)
24991 (lang-words nil)
24992 (region
24993 (buffer-substring
24994 (if (org-region-active-p) (region-beginning) (point-min))
24995 (if (org-region-active-p) (region-end) (point-max))))
24996 (lines (org-split-string
24997 (org-cleaned-string-for-export
24998 region
24999 :for-ascii t
25000 :skip-before-1st-heading
25001 (plist-get opt-plist :skip-before-1st-heading)
25002 :drawers (plist-get opt-plist :drawers)
25003 :verbatim-multiline t
25004 :archived-trees
25005 (plist-get opt-plist :archived-trees)
25006 :add-text (plist-get opt-plist :text))
25007 "\n"))
25008 thetoc have-headings first-heading-pos
25009 table-open table-buffer)
25011 (let ((inhibit-read-only t))
25012 (org-unmodified
25013 (remove-text-properties (point-min) (point-max)
25014 '(:org-license-to-kill t))))
25016 (setq org-min-level (org-get-min-level lines))
25017 (setq org-last-level org-min-level)
25018 (org-init-section-numbers)
25020 (find-file-noselect filename)
25022 (setq lang-words (or (assoc language org-export-language-setup)
25023 (assoc "en" org-export-language-setup)))
25024 (switch-to-buffer-other-window buffer)
25025 (erase-buffer)
25026 (fundamental-mode)
25027 ;; create local variables for all options, to make sure all called
25028 ;; functions get the correct information
25029 (mapc (lambda (x)
25030 (set (make-local-variable (cdr x))
25031 (plist-get opt-plist (car x))))
25032 org-export-plist-vars)
25033 (org-set-local 'org-odd-levels-only odd)
25034 (setq umax (if arg (prefix-numeric-value arg)
25035 org-export-headline-levels))
25036 (setq umax-toc (if (integerp org-export-with-toc)
25037 (min org-export-with-toc umax)
25038 umax))
25040 ;; File header
25041 (if title (org-insert-centered title ?=))
25042 (insert "\n")
25043 (if (and (or author email)
25044 org-export-author-info)
25045 (insert (concat (nth 1 lang-words) ": " (or author "")
25046 (if email (concat " <" email ">") "")
25047 "\n")))
25049 (cond
25050 ((and date (string-match "%" date))
25051 (setq date (format-time-string date (current-time))))
25052 (date)
25053 (t (setq date (format-time-string "%Y/%m/%d %X" (current-time)))))
25055 (if (and date org-export-time-stamp-file)
25056 (insert (concat (nth 2 lang-words) ": " date"\n")))
25058 (insert "\n\n")
25060 (if org-export-with-toc
25061 (progn
25062 (push (concat (nth 3 lang-words) "\n") thetoc)
25063 (push (concat (make-string (length (nth 3 lang-words)) ?=) "\n") thetoc)
25064 (mapc '(lambda (line)
25065 (if (string-match org-todo-line-regexp
25066 line)
25067 ;; This is a headline
25068 (progn
25069 (setq have-headings t)
25070 (setq level (- (match-end 1) (match-beginning 1))
25071 level (org-tr-level level)
25072 txt (match-string 3 line)
25073 todo
25074 (or (and org-export-mark-todo-in-toc
25075 (match-beginning 2)
25076 (not (member (match-string 2 line)
25077 org-done-keywords)))
25078 ; TODO, not DONE
25079 (and org-export-mark-todo-in-toc
25080 (= level umax-toc)
25081 (org-search-todo-below
25082 line lines level))))
25083 (setq txt (org-html-expand-for-ascii txt))
25085 (while (string-match org-bracket-link-regexp txt)
25086 (setq txt
25087 (replace-match
25088 (match-string (if (match-end 2) 3 1) txt)
25089 t t txt)))
25091 (if (and (memq org-export-with-tags '(not-in-toc nil))
25092 (string-match
25093 (org-re "[ \t]+:[[:alnum:]_@:]+:[ \t]*$")
25094 txt))
25095 (setq txt (replace-match "" t t txt)))
25096 (if (string-match quote-re0 txt)
25097 (setq txt (replace-match "" t t txt)))
25099 (if org-export-with-section-numbers
25100 (setq txt (concat (org-section-number level)
25101 " " txt)))
25102 (if (<= level umax-toc)
25103 (progn
25104 (push
25105 (concat
25106 (make-string
25107 (* (max 0 (- level org-min-level)) 4) ?\ )
25108 (format (if todo "%s (*)\n" "%s\n") txt))
25109 thetoc)
25110 (setq org-last-level level))
25111 ))))
25112 lines)
25113 (setq thetoc (if have-headings (nreverse thetoc) nil))))
25115 (org-init-section-numbers)
25116 (while (setq line (pop lines))
25117 ;; Remove the quoted HTML tags.
25118 (setq line (org-html-expand-for-ascii line))
25119 ;; Remove targets
25120 (while (string-match "<<<?[^<>]*>>>?[ \t]*\n?" line)
25121 (setq line (replace-match "" t t line)))
25122 ;; Replace internal links
25123 (while (string-match org-bracket-link-regexp line)
25124 (setq line (replace-match
25125 (if (match-end 3) "[\\3]" "[\\1]")
25126 t nil line)))
25127 (when custom-times
25128 (setq line (org-translate-time line)))
25129 (cond
25130 ((string-match "^\\(\\*+\\)[ \t]+\\(.*\\)" line)
25131 ;; a Headline
25132 (setq first-heading-pos (or first-heading-pos (point)))
25133 (setq level (org-tr-level (- (match-end 1) (match-beginning 1)))
25134 txt (match-string 2 line))
25135 (org-ascii-level-start level txt umax lines))
25137 ((and org-export-with-tables
25138 (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)" line))
25139 (if (not table-open)
25140 ;; New table starts
25141 (setq table-open t table-buffer nil))
25142 ;; Accumulate lines
25143 (setq table-buffer (cons line table-buffer))
25144 (when (or (not lines)
25145 (not (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)"
25146 (car lines))))
25147 (setq table-open nil
25148 table-buffer (nreverse table-buffer))
25149 (insert (mapconcat
25150 (lambda (x)
25151 (org-fix-indentation x org-ascii-current-indentation))
25152 (org-format-table-ascii table-buffer)
25153 "\n") "\n")))
25155 (setq line (org-fix-indentation line org-ascii-current-indentation))
25156 (if (and org-export-with-fixed-width
25157 (string-match "^\\([ \t]*\\)\\(:\\)" line))
25158 (setq line (replace-match "\\1" nil nil line)))
25159 (insert line "\n"))))
25161 (normal-mode)
25163 ;; insert the table of contents
25164 (when thetoc
25165 (goto-char (point-min))
25166 (if (re-search-forward "^[ \t]*\\[TABLE-OF-CONTENTS\\][ \t]*$" nil t)
25167 (progn
25168 (goto-char (match-beginning 0))
25169 (replace-match ""))
25170 (goto-char first-heading-pos))
25171 (mapc 'insert thetoc)
25172 (or (looking-at "[ \t]*\n[ \t]*\n")
25173 (insert "\n\n")))
25175 ;; Convert whitespace place holders
25176 (goto-char (point-min))
25177 (let (beg end)
25178 (while (setq beg (next-single-property-change (point) 'org-whitespace))
25179 (setq end (next-single-property-change beg 'org-whitespace))
25180 (goto-char beg)
25181 (delete-region beg end)
25182 (insert (make-string (- end beg) ?\ ))))
25184 (save-buffer)
25185 ;; remove display and invisible chars
25186 (let (beg end)
25187 (goto-char (point-min))
25188 (while (setq beg (next-single-property-change (point) 'display))
25189 (setq end (next-single-property-change beg 'display))
25190 (delete-region beg end)
25191 (goto-char beg)
25192 (insert "=>"))
25193 (goto-char (point-min))
25194 (while (setq beg (next-single-property-change (point) 'org-cwidth))
25195 (setq end (next-single-property-change beg 'org-cwidth))
25196 (delete-region beg end)
25197 (goto-char beg)))
25198 (goto-char (point-min))))
25200 (defun org-export-ascii-clean-string ()
25201 "Do extra work for ASCII export"
25202 (goto-char (point-min))
25203 (while (re-search-forward org-verbatim-re nil t)
25204 (goto-char (match-end 2))
25205 (backward-delete-char 1) (insert "'")
25206 (goto-char (match-beginning 2))
25207 (delete-char 1) (insert "`")
25208 (goto-char (match-end 2))))
25210 (defun org-search-todo-below (line lines level)
25211 "Search the subtree below LINE for any TODO entries."
25212 (let ((rest (cdr (memq line lines)))
25213 (re org-todo-line-regexp)
25214 line lv todo)
25215 (catch 'exit
25216 (while (setq line (pop rest))
25217 (if (string-match re line)
25218 (progn
25219 (setq lv (- (match-end 1) (match-beginning 1))
25220 todo (and (match-beginning 2)
25221 (not (member (match-string 2 line)
25222 org-done-keywords))))
25223 ; TODO, not DONE
25224 (if (<= lv level) (throw 'exit nil))
25225 (if todo (throw 'exit t))))))))
25227 (defun org-html-expand-for-ascii (line)
25228 "Handle quoted HTML for ASCII export."
25229 (if org-export-html-expand
25230 (while (string-match "@<[^<>\n]*>" line)
25231 ;; We just remove the tags for now.
25232 (setq line (replace-match "" nil nil line))))
25233 line)
25235 (defun org-insert-centered (s &optional underline)
25236 "Insert the string S centered and underline it with character UNDERLINE."
25237 (let ((ind (max (/ (- 80 (string-width s)) 2) 0)))
25238 (insert (make-string ind ?\ ) s "\n")
25239 (if underline
25240 (insert (make-string ind ?\ )
25241 (make-string (string-width s) underline)
25242 "\n"))))
25244 (defun org-ascii-level-start (level title umax &optional lines)
25245 "Insert a new level in ASCII export."
25246 (let (char (n (- level umax 1)) (ind 0))
25247 (if (> level umax)
25248 (progn
25249 (insert (make-string (* 2 n) ?\ )
25250 (char-to-string (nth (% n (length org-export-ascii-bullets))
25251 org-export-ascii-bullets))
25252 " " title "\n")
25253 ;; find the indentation of the next non-empty line
25254 (catch 'stop
25255 (while lines
25256 (if (string-match "^\\* " (car lines)) (throw 'stop nil))
25257 (if (string-match "^\\([ \t]*\\)\\S-" (car lines))
25258 (throw 'stop (setq ind (org-get-indentation (car lines)))))
25259 (pop lines)))
25260 (setq org-ascii-current-indentation (cons (* 2 (1+ n)) ind)))
25261 (if (or (not (equal (char-before) ?\n))
25262 (not (equal (char-before (1- (point))) ?\n)))
25263 (insert "\n"))
25264 (setq char (nth (- umax level) (reverse org-export-ascii-underline)))
25265 (unless org-export-with-tags
25266 (if (string-match (org-re "[ \t]+\\(:[[:alnum:]_@:]+:\\)[ \t]*$") title)
25267 (setq title (replace-match "" t t title))))
25268 (if org-export-with-section-numbers
25269 (setq title (concat (org-section-number level) " " title)))
25270 (insert title "\n" (make-string (string-width title) char) "\n")
25271 (setq org-ascii-current-indentation '(0 . 0)))))
25273 (defun org-export-visible (type arg)
25274 "Create a copy of the visible part of the current buffer, and export it.
25275 The copy is created in a temporary buffer and removed after use.
25276 TYPE is the final key (as a string) that also select the export command in
25277 the `C-c C-e' export dispatcher.
25278 As a special case, if the you type SPC at the prompt, the temporary
25279 org-mode file will not be removed but presented to you so that you can
25280 continue to use it. The prefix arg ARG is passed through to the exporting
25281 command."
25282 (interactive
25283 (list (progn
25284 (message "Export visible: [a]SCII [h]tml [b]rowse HTML [H/R]uffer with HTML [x]OXO [ ]keep buffer")
25285 (read-char-exclusive))
25286 current-prefix-arg))
25287 (if (not (member type '(?a ?\C-a ?b ?\C-b ?h ?x ?\ )))
25288 (error "Invalid export key"))
25289 (let* ((binding (cdr (assoc type
25290 '((?a . org-export-as-ascii)
25291 (?\C-a . org-export-as-ascii)
25292 (?b . org-export-as-html-and-open)
25293 (?\C-b . org-export-as-html-and-open)
25294 (?h . org-export-as-html)
25295 (?H . org-export-as-html-to-buffer)
25296 (?R . org-export-region-as-html)
25297 (?x . org-export-as-xoxo)))))
25298 (keepp (equal type ?\ ))
25299 (file buffer-file-name)
25300 (buffer (get-buffer-create "*Org Export Visible*"))
25301 s e)
25302 ;; Need to hack the drawers here.
25303 (save-excursion
25304 (goto-char (point-min))
25305 (while (re-search-forward org-drawer-regexp nil t)
25306 (goto-char (match-beginning 1))
25307 (or (org-invisible-p) (org-flag-drawer nil))))
25308 (with-current-buffer buffer (erase-buffer))
25309 (save-excursion
25310 (setq s (goto-char (point-min)))
25311 (while (not (= (point) (point-max)))
25312 (goto-char (org-find-invisible))
25313 (append-to-buffer buffer s (point))
25314 (setq s (goto-char (org-find-visible))))
25315 (org-cycle-hide-drawers 'all)
25316 (goto-char (point-min))
25317 (unless keepp
25318 ;; Copy all comment lines to the end, to make sure #+ settings are
25319 ;; still available for the second export step. Kind of a hack, but
25320 ;; does do the trick.
25321 (if (looking-at "#[^\r\n]*")
25322 (append-to-buffer buffer (match-beginning 0) (1+ (match-end 0))))
25323 (while (re-search-forward "[\n\r]#[^\n\r]*" nil t)
25324 (append-to-buffer buffer (1+ (match-beginning 0))
25325 (min (point-max) (1+ (match-end 0))))))
25326 (set-buffer buffer)
25327 (let ((buffer-file-name file)
25328 (org-inhibit-startup t))
25329 (org-mode)
25330 (show-all)
25331 (unless keepp (funcall binding arg))))
25332 (if (not keepp)
25333 (kill-buffer buffer)
25334 (switch-to-buffer-other-window buffer)
25335 (goto-char (point-min)))))
25337 (defun org-find-visible ()
25338 (let ((s (point)))
25339 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
25340 (get-char-property s 'invisible)))
25342 (defun org-find-invisible ()
25343 (let ((s (point)))
25344 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
25345 (not (get-char-property s 'invisible))))
25348 ;;; HTML export
25350 (defun org-get-current-options ()
25351 "Return a string with current options as keyword options.
25352 Does include HTML export options as well as TODO and CATEGORY stuff."
25353 (format
25354 "#+TITLE: %s
25355 #+AUTHOR: %s
25356 #+EMAIL: %s
25357 #+LANGUAGE: %s
25358 #+TEXT: Some descriptive text to be emitted. Several lines OK.
25359 #+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
25360 #+CATEGORY: %s
25361 #+SEQ_TODO: %s
25362 #+TYP_TODO: %s
25363 #+PRIORITIES: %c %c %c
25364 #+DRAWERS: %s
25365 #+STARTUP: %s %s %s %s %s
25366 #+TAGS: %s
25367 #+ARCHIVE: %s
25368 #+LINK: %s
25370 (buffer-name) (user-full-name) user-mail-address org-export-default-language
25371 org-export-headline-levels
25372 org-export-with-section-numbers
25373 org-export-with-toc
25374 org-export-preserve-breaks
25375 org-export-html-expand
25376 org-export-with-fixed-width
25377 org-export-with-tables
25378 org-export-with-sub-superscripts
25379 org-export-with-special-strings
25380 org-export-with-footnotes
25381 org-export-with-emphasize
25382 org-export-with-TeX-macros
25383 org-export-with-LaTeX-fragments
25384 org-export-skip-text-before-1st-heading
25385 org-export-with-drawers
25386 org-export-with-tags
25387 (file-name-nondirectory buffer-file-name)
25388 "TODO FEEDBACK VERIFY DONE"
25389 "Me Jason Marie DONE"
25390 org-highest-priority org-lowest-priority org-default-priority
25391 (mapconcat 'identity org-drawers " ")
25392 (cdr (assoc org-startup-folded
25393 '((nil . "showall") (t . "overview") (content . "content"))))
25394 (if org-odd-levels-only "odd" "oddeven")
25395 (if org-hide-leading-stars "hidestars" "showstars")
25396 (if org-startup-align-all-tables "align" "noalign")
25397 (cond ((eq org-log-done t) "logdone")
25398 ((equal org-log-done 'note) "lognotedone")
25399 ((not org-log-done) "nologdone"))
25400 (or (mapconcat (lambda (x)
25401 (cond
25402 ((equal '(:startgroup) x) "{")
25403 ((equal '(:endgroup) x) "}")
25404 ((cdr x) (format "%s(%c)" (car x) (cdr x)))
25405 (t (car x))))
25406 (or org-tag-alist (org-get-buffer-tags)) " ") "")
25407 org-archive-location
25408 "org file:~/org/%s.org"
25411 (defun org-insert-export-options-template ()
25412 "Insert into the buffer a template with information for exporting."
25413 (interactive)
25414 (if (not (bolp)) (newline))
25415 (let ((s (org-get-current-options)))
25416 (and (string-match "#\\+CATEGORY" s)
25417 (setq s (substring s 0 (match-beginning 0))))
25418 (insert s)))
25420 (defun org-toggle-fixed-width-section (arg)
25421 "Toggle the fixed-width export.
25422 If there is no active region, the QUOTE keyword at the current headline is
25423 inserted or removed. When present, it causes the text between this headline
25424 and the next to be exported as fixed-width text, and unmodified.
25425 If there is an active region, this command adds or removes a colon as the
25426 first character of this line. If the first character of a line is a colon,
25427 this line is also exported in fixed-width font."
25428 (interactive "P")
25429 (let* ((cc 0)
25430 (regionp (org-region-active-p))
25431 (beg (if regionp (region-beginning) (point)))
25432 (end (if regionp (region-end)))
25433 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
25434 (case-fold-search nil)
25435 (re "[ \t]*\\(:\\)")
25436 off)
25437 (if regionp
25438 (save-excursion
25439 (goto-char beg)
25440 (setq cc (current-column))
25441 (beginning-of-line 1)
25442 (setq off (looking-at re))
25443 (while (> nlines 0)
25444 (setq nlines (1- nlines))
25445 (beginning-of-line 1)
25446 (cond
25447 (arg
25448 (move-to-column cc t)
25449 (insert ":\n")
25450 (forward-line -1))
25451 ((and off (looking-at re))
25452 (replace-match "" t t nil 1))
25453 ((not off) (move-to-column cc t) (insert ":")))
25454 (forward-line 1)))
25455 (save-excursion
25456 (org-back-to-heading)
25457 (if (looking-at (concat outline-regexp
25458 "\\( *\\<" org-quote-string "\\>[ \t]*\\)"))
25459 (replace-match "" t t nil 1)
25460 (if (looking-at outline-regexp)
25461 (progn
25462 (goto-char (match-end 0))
25463 (insert org-quote-string " "))))))))
25465 (defun org-export-as-html-and-open (arg)
25466 "Export the outline as HTML and immediately open it with a browser.
25467 If there is an active region, export only the region.
25468 The prefix ARG specifies how many levels of the outline should become
25469 headlines. The default is 3. Lower levels will become bulleted lists."
25470 (interactive "P")
25471 (org-export-as-html arg 'hidden)
25472 (org-open-file buffer-file-name))
25474 (defun org-export-as-html-batch ()
25475 "Call `org-export-as-html', may be used in batch processing as
25476 emacs --batch
25477 --load=$HOME/lib/emacs/org.el
25478 --eval \"(setq org-export-headline-levels 2)\"
25479 --visit=MyFile --funcall org-export-as-html-batch"
25480 (org-export-as-html org-export-headline-levels 'hidden))
25482 (defun org-export-as-html-to-buffer (arg)
25483 "Call `org-exort-as-html` with output to a temporary buffer.
25484 No file is created. The prefix ARG is passed through to `org-export-as-html'."
25485 (interactive "P")
25486 (org-export-as-html arg nil nil "*Org HTML Export*")
25487 (switch-to-buffer-other-window "*Org HTML Export*"))
25489 (defun org-replace-region-by-html (beg end)
25490 "Assume the current region has org-mode syntax, and convert it to HTML.
25491 This can be used in any buffer. For example, you could write an
25492 itemized list in org-mode syntax in an HTML buffer and then use this
25493 command to convert it."
25494 (interactive "r")
25495 (let (reg html buf pop-up-frames)
25496 (save-window-excursion
25497 (if (org-mode-p)
25498 (setq html (org-export-region-as-html
25499 beg end t 'string))
25500 (setq reg (buffer-substring beg end)
25501 buf (get-buffer-create "*Org tmp*"))
25502 (with-current-buffer buf
25503 (erase-buffer)
25504 (insert reg)
25505 (org-mode)
25506 (setq html (org-export-region-as-html
25507 (point-min) (point-max) t 'string)))
25508 (kill-buffer buf)))
25509 (delete-region beg end)
25510 (insert html)))
25512 (defun org-export-region-as-html (beg end &optional body-only buffer)
25513 "Convert region from BEG to END in org-mode buffer to HTML.
25514 If prefix arg BODY-ONLY is set, omit file header, footer, and table of
25515 contents, and only produce the region of converted text, useful for
25516 cut-and-paste operations.
25517 If BUFFER is a buffer or a string, use/create that buffer as a target
25518 of the converted HTML. If BUFFER is the symbol `string', return the
25519 produced HTML as a string and leave not buffer behind. For example,
25520 a Lisp program could call this function in the following way:
25522 (setq html (org-export-region-as-html beg end t 'string))
25524 When called interactively, the output buffer is selected, and shown
25525 in a window. A non-interactive call will only retunr the buffer."
25526 (interactive "r\nP")
25527 (when (interactive-p)
25528 (setq buffer "*Org HTML Export*"))
25529 (let ((transient-mark-mode t) (zmacs-regions t)
25530 rtn)
25531 (goto-char end)
25532 (set-mark (point)) ;; to activate the region
25533 (goto-char beg)
25534 (setq rtn (org-export-as-html
25535 nil nil nil
25536 buffer body-only))
25537 (if (fboundp 'deactivate-mark) (deactivate-mark))
25538 (if (and (interactive-p) (bufferp rtn))
25539 (switch-to-buffer-other-window rtn)
25540 rtn)))
25542 (defvar html-table-tag nil) ; dynamically scoped into this.
25543 (defun org-export-as-html (arg &optional hidden ext-plist
25544 to-buffer body-only pub-dir)
25545 "Export the outline as a pretty HTML file.
25546 If there is an active region, export only the region. The prefix
25547 ARG specifies how many levels of the outline should become
25548 headlines. The default is 3. Lower levels will become bulleted
25549 lists. When HIDDEN is non-nil, don't display the HTML buffer.
25550 EXT-PLIST is a property list with external parameters overriding
25551 org-mode's default settings, but still inferior to file-local
25552 settings. When TO-BUFFER is non-nil, create a buffer with that
25553 name and export to that buffer. If TO-BUFFER is the symbol
25554 `string', don't leave any buffer behind but just return the
25555 resulting HTML as a string. When BODY-ONLY is set, don't produce
25556 the file header and footer, simply return the content of
25557 <body>...</body>, without even the body tags themselves. When
25558 PUB-DIR is set, use this as the publishing directory."
25559 (interactive "P")
25561 ;; Make sure we have a file name when we need it.
25562 (when (and (not (or to-buffer body-only))
25563 (not buffer-file-name))
25564 (if (buffer-base-buffer)
25565 (org-set-local 'buffer-file-name
25566 (with-current-buffer (buffer-base-buffer)
25567 buffer-file-name))
25568 (error "Need a file name to be able to export.")))
25570 (message "Exporting...")
25571 (setq-default org-todo-line-regexp org-todo-line-regexp)
25572 (setq-default org-deadline-line-regexp org-deadline-line-regexp)
25573 (setq-default org-done-keywords org-done-keywords)
25574 (setq-default org-maybe-keyword-time-regexp org-maybe-keyword-time-regexp)
25575 (let* ((opt-plist (org-combine-plists (org-default-export-plist)
25576 ext-plist
25577 (org-infile-export-plist)))
25579 (style (plist-get opt-plist :style))
25580 (html-extension (plist-get opt-plist :html-extension))
25581 (link-validate (plist-get opt-plist :link-validation-function))
25582 valid thetoc have-headings first-heading-pos
25583 (odd org-odd-levels-only)
25584 (region-p (org-region-active-p))
25585 (subtree-p
25586 (when region-p
25587 (save-excursion
25588 (goto-char (region-beginning))
25589 (and (org-at-heading-p)
25590 (>= (org-end-of-subtree t t) (region-end))))))
25591 ;; The following two are dynamically scoped into other
25592 ;; routines below.
25593 (org-current-export-dir
25594 (or pub-dir (org-export-directory :html opt-plist)))
25595 (org-current-export-file buffer-file-name)
25596 (level 0) (line "") (origline "") txt todo
25597 (umax nil)
25598 (umax-toc nil)
25599 (filename (if to-buffer nil
25600 (expand-file-name
25601 (concat
25602 (file-name-sans-extension
25603 (or (and subtree-p
25604 (org-entry-get (region-beginning)
25605 "EXPORT_FILE_NAME" t))
25606 (file-name-nondirectory buffer-file-name)))
25607 "." html-extension)
25608 (file-name-as-directory
25609 (or pub-dir (org-export-directory :html opt-plist))))))
25610 (current-dir (if buffer-file-name
25611 (file-name-directory buffer-file-name)
25612 default-directory))
25613 (buffer (if to-buffer
25614 (cond
25615 ((eq to-buffer 'string) (get-buffer-create "*Org HTML Export*"))
25616 (t (get-buffer-create to-buffer)))
25617 (find-file-noselect filename)))
25618 (org-levels-open (make-vector org-level-max nil))
25619 (date (plist-get opt-plist :date))
25620 (author (plist-get opt-plist :author))
25621 (title (or (and subtree-p (org-export-get-title-from-subtree))
25622 (plist-get opt-plist :title)
25623 (and (not
25624 (plist-get opt-plist :skip-before-1st-heading))
25625 (org-export-grab-title-from-buffer))
25626 (and buffer-file-name
25627 (file-name-sans-extension
25628 (file-name-nondirectory buffer-file-name)))
25629 "UNTITLED"))
25630 (html-table-tag (plist-get opt-plist :html-table-tag))
25631 (quote-re0 (concat "^[ \t]*" org-quote-string "\\>"))
25632 (quote-re (concat "^\\(\\*+\\)\\([ \t]+" org-quote-string "\\>\\)"))
25633 (inquote nil)
25634 (infixed nil)
25635 (in-local-list nil)
25636 (local-list-num nil)
25637 (local-list-indent nil)
25638 (llt org-plain-list-ordered-item-terminator)
25639 (email (plist-get opt-plist :email))
25640 (language (plist-get opt-plist :language))
25641 (lang-words nil)
25642 (target-alist nil) tg
25643 (head-count 0) cnt
25644 (start 0)
25645 (coding-system (and (boundp 'buffer-file-coding-system)
25646 buffer-file-coding-system))
25647 (coding-system-for-write (or org-export-html-coding-system
25648 coding-system))
25649 (save-buffer-coding-system (or org-export-html-coding-system
25650 coding-system))
25651 (charset (and coding-system-for-write
25652 (fboundp 'coding-system-get)
25653 (coding-system-get coding-system-for-write
25654 'mime-charset)))
25655 (region
25656 (buffer-substring
25657 (if region-p (region-beginning) (point-min))
25658 (if region-p (region-end) (point-max))))
25659 (lines
25660 (org-split-string
25661 (org-cleaned-string-for-export
25662 region
25663 :emph-multiline t
25664 :for-html t
25665 :skip-before-1st-heading
25666 (plist-get opt-plist :skip-before-1st-heading)
25667 :drawers (plist-get opt-plist :drawers)
25668 :archived-trees
25669 (plist-get opt-plist :archived-trees)
25670 :add-text
25671 (plist-get opt-plist :text)
25672 :LaTeX-fragments
25673 (plist-get opt-plist :LaTeX-fragments))
25674 "[\r\n]"))
25675 table-open type
25676 table-buffer table-orig-buffer
25677 ind start-is-num starter didclose
25678 rpl path desc descp desc1 desc2 link
25679 snumber
25682 (let ((inhibit-read-only t))
25683 (org-unmodified
25684 (remove-text-properties (point-min) (point-max)
25685 '(:org-license-to-kill t))))
25687 (message "Exporting...")
25689 (setq org-min-level (org-get-min-level lines))
25690 (setq org-last-level org-min-level)
25691 (org-init-section-numbers)
25693 (cond
25694 ((and date (string-match "%" date))
25695 (setq date (format-time-string date (current-time))))
25696 (date)
25697 (t (setq date (format-time-string "%Y/%m/%d %X" (current-time)))))
25699 ;; Get the language-dependent settings
25700 (setq lang-words (or (assoc language org-export-language-setup)
25701 (assoc "en" org-export-language-setup)))
25703 ;; Switch to the output buffer
25704 (set-buffer buffer)
25705 (let ((inhibit-read-only t)) (erase-buffer))
25706 (fundamental-mode)
25708 (and (fboundp 'set-buffer-file-coding-system)
25709 (set-buffer-file-coding-system coding-system-for-write))
25711 (let ((case-fold-search nil)
25712 (org-odd-levels-only odd))
25713 ;; create local variables for all options, to make sure all called
25714 ;; functions get the correct information
25715 (mapc (lambda (x)
25716 (set (make-local-variable (cdr x))
25717 (plist-get opt-plist (car x))))
25718 org-export-plist-vars)
25719 (setq umax (if arg (prefix-numeric-value arg)
25720 org-export-headline-levels))
25721 (setq umax-toc (if (integerp org-export-with-toc)
25722 (min org-export-with-toc umax)
25723 umax))
25724 (unless body-only
25725 ;; File header
25726 (insert (format
25727 "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"
25728 \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">
25729 <html xmlns=\"http://www.w3.org/1999/xhtml\"
25730 lang=\"%s\" xml:lang=\"%s\">
25731 <head>
25732 <title>%s</title>
25733 <meta http-equiv=\"Content-Type\" content=\"text/html;charset=%s\"/>
25734 <meta name=\"generator\" content=\"Org-mode\"/>
25735 <meta name=\"generated\" content=\"%s\"/>
25736 <meta name=\"author\" content=\"%s\"/>
25738 </head><body>
25740 language language (org-html-expand title)
25741 (or charset "iso-8859-1") date author style))
25743 (insert (or (plist-get opt-plist :preamble) ""))
25745 (when (plist-get opt-plist :auto-preamble)
25746 (if title (insert (format org-export-html-title-format
25747 (org-html-expand title))))))
25749 (if (and org-export-with-toc (not body-only))
25750 (progn
25751 (push (format "<h%d>%s</h%d>\n"
25752 org-export-html-toplevel-hlevel
25753 (nth 3 lang-words)
25754 org-export-html-toplevel-hlevel)
25755 thetoc)
25756 (push "<div id=\"text-table-of-contents\">\n" thetoc)
25757 (push "<ul>\n<li>" thetoc)
25758 (setq lines
25759 (mapcar '(lambda (line)
25760 (if (string-match org-todo-line-regexp line)
25761 ;; This is a headline
25762 (progn
25763 (setq have-headings t)
25764 (setq level (- (match-end 1) (match-beginning 1))
25765 level (org-tr-level level)
25766 txt (save-match-data
25767 (org-html-expand
25768 (org-export-cleanup-toc-line
25769 (match-string 3 line))))
25770 todo
25771 (or (and org-export-mark-todo-in-toc
25772 (match-beginning 2)
25773 (not (member (match-string 2 line)
25774 org-done-keywords)))
25775 ; TODO, not DONE
25776 (and org-export-mark-todo-in-toc
25777 (= level umax-toc)
25778 (org-search-todo-below
25779 line lines level))))
25780 (if (string-match
25781 (org-re "[ \t]+:\\([[:alnum:]_@:]+\\):[ \t]*$") txt)
25782 (setq txt (replace-match "&nbsp;&nbsp;&nbsp;<span class=\"tag\"> \\1</span>" t nil txt)))
25783 (if (string-match quote-re0 txt)
25784 (setq txt (replace-match "" t t txt)))
25785 (setq snumber (org-section-number level))
25786 (if org-export-with-section-numbers
25787 (setq txt (concat snumber " " txt)))
25788 (if (<= level (max umax umax-toc))
25789 (setq head-count (+ head-count 1)))
25790 (if (<= level umax-toc)
25791 (progn
25792 (if (> level org-last-level)
25793 (progn
25794 (setq cnt (- level org-last-level))
25795 (while (>= (setq cnt (1- cnt)) 0)
25796 (push "\n<ul>\n<li>" thetoc))
25797 (push "\n" thetoc)))
25798 (if (< level org-last-level)
25799 (progn
25800 (setq cnt (- org-last-level level))
25801 (while (>= (setq cnt (1- cnt)) 0)
25802 (push "</li>\n</ul>" thetoc))
25803 (push "\n" thetoc)))
25804 ;; Check for targets
25805 (while (string-match org-target-regexp line)
25806 (setq tg (match-string 1 line)
25807 line (replace-match
25808 (concat "@<span class=\"target\">" tg "@</span> ")
25809 t t line))
25810 (push (cons (org-solidify-link-text tg)
25811 (format "sec-%s" snumber))
25812 target-alist))
25813 (while (string-match "&lt;\\(&lt;\\)+\\|&gt;\\(&gt;\\)+" txt)
25814 (setq txt (replace-match "" t t txt)))
25815 (push
25816 (format
25817 (if todo
25818 "</li>\n<li><a href=\"#sec-%s\"><span class=\"todo\">%s</span></a>"
25819 "</li>\n<li><a href=\"#sec-%s\">%s</a>")
25820 snumber txt) thetoc)
25822 (setq org-last-level level))
25824 line)
25825 lines))
25826 (while (> org-last-level (1- org-min-level))
25827 (setq org-last-level (1- org-last-level))
25828 (push "</li>\n</ul>\n" thetoc))
25829 (push "</div>\n" thetoc)
25830 (setq thetoc (if have-headings (nreverse thetoc) nil))))
25832 (setq head-count 0)
25833 (org-init-section-numbers)
25835 (while (setq line (pop lines) origline line)
25836 (catch 'nextline
25838 ;; end of quote section?
25839 (when (and inquote (string-match "^\\*+ " line))
25840 (insert "</pre>\n")
25841 (setq inquote nil))
25842 ;; inside a quote section?
25843 (when inquote
25844 (insert (org-html-protect line) "\n")
25845 (throw 'nextline nil))
25847 ;; verbatim lines
25848 (when (and org-export-with-fixed-width
25849 (string-match "^[ \t]*:\\(.*\\)" line))
25850 (when (not infixed)
25851 (setq infixed t)
25852 (insert "<pre>\n"))
25853 (insert (org-html-protect (match-string 1 line)) "\n")
25854 (when (and lines
25855 (not (string-match "^[ \t]*\\(:.*\\)"
25856 (car lines))))
25857 (setq infixed nil)
25858 (insert "</pre>\n"))
25859 (throw 'nextline nil))
25861 ;; Protected HTML
25862 (when (get-text-property 0 'org-protected line)
25863 (let (par)
25864 (when (re-search-backward
25865 "\\(<p>\\)\\([ \t\r\n]*\\)\\=" (- (point) 100) t)
25866 (setq par (match-string 1))
25867 (replace-match "\\2\n"))
25868 (insert line "\n")
25869 (while (and lines
25870 (or (= (length (car lines)) 0)
25871 (get-text-property 0 'org-protected (car lines))))
25872 (insert (pop lines) "\n"))
25873 (and par (insert "<p>\n")))
25874 (throw 'nextline nil))
25876 ;; Horizontal line
25877 (when (string-match "^[ \t]*-\\{5,\\}[ \t]*$" line)
25878 (insert "\n<hr/>\n")
25879 (throw 'nextline nil))
25881 ;; make targets to anchors
25882 (while (string-match "<<<?\\([^<>]*\\)>>>?\\((INVISIBLE)\\)?[ \t]*\n?" line)
25883 (cond
25884 ((match-end 2)
25885 (setq line (replace-match
25886 (concat "@<a name=\""
25887 (org-solidify-link-text (match-string 1 line))
25888 "\">\\nbsp@</a>")
25889 t t line)))
25890 ((and org-export-with-toc (equal (string-to-char line) ?*))
25891 (setq line (replace-match
25892 (concat "@<span class=\"target\">" (match-string 1 line) "@</span> ")
25893 ; (concat "@<i>" (match-string 1 line) "@</i> ")
25894 t t line)))
25896 (setq line (replace-match
25897 (concat "@<a name=\""
25898 (org-solidify-link-text (match-string 1 line))
25899 "\" class=\"target\">" (match-string 1 line) "@</a> ")
25900 t t line)))))
25902 (setq line (org-html-handle-time-stamps line))
25904 ;; replace "&" by "&amp;", "<" and ">" by "&lt;" and "&gt;"
25905 ;; handle @<..> HTML tags (replace "@&gt;..&lt;" by "<..>")
25906 ;; Also handle sub_superscripts and checkboxes
25907 (or (string-match org-table-hline-regexp line)
25908 (setq line (org-html-expand line)))
25910 ;; Format the links
25911 (setq start 0)
25912 (while (string-match org-bracket-link-analytic-regexp line start)
25913 (setq start (match-beginning 0))
25914 (setq type (if (match-end 2) (match-string 2 line) "internal"))
25915 (setq path (match-string 3 line))
25916 (setq desc1 (if (match-end 5) (match-string 5 line))
25917 desc2 (if (match-end 2) (concat type ":" path) path)
25918 descp (and desc1 (not (equal desc1 desc2)))
25919 desc (or desc1 desc2))
25920 ;; Make an image out of the description if that is so wanted
25921 (when (and descp (org-file-image-p desc))
25922 (save-match-data
25923 (if (string-match "^file:" desc)
25924 (setq desc (substring desc (match-end 0)))))
25925 (setq desc (concat "<img src=\"" desc "\"/>")))
25926 ;; FIXME: do we need to unescape here somewhere?
25927 (cond
25928 ((equal type "internal")
25929 (setq rpl
25930 (concat
25931 "<a href=\"#"
25932 (org-solidify-link-text
25933 (save-match-data (org-link-unescape path)) target-alist)
25934 "\">" desc "</a>")))
25935 ((member type '("http" "https"))
25936 ;; standard URL, just check if we need to inline an image
25937 (if (and (or (eq t org-export-html-inline-images)
25938 (and org-export-html-inline-images (not descp)))
25939 (org-file-image-p path))
25940 (setq rpl (concat "<img src=\"" type ":" path "\"/>"))
25941 (setq link (concat type ":" path))
25942 (setq rpl (concat "<a href=\"" link "\">" desc "</a>"))))
25943 ((member type '("ftp" "mailto" "news"))
25944 ;; standard URL
25945 (setq link (concat type ":" path))
25946 (setq rpl (concat "<a href=\"" link "\">" desc "</a>")))
25947 ((string= type "file")
25948 ;; FILE link
25949 (let* ((filename path)
25950 (abs-p (file-name-absolute-p filename))
25951 thefile file-is-image-p search)
25952 (save-match-data
25953 (if (string-match "::\\(.*\\)" filename)
25954 (setq search (match-string 1 filename)
25955 filename (replace-match "" t nil filename)))
25956 (setq valid
25957 (if (functionp link-validate)
25958 (funcall link-validate filename current-dir)
25960 (setq file-is-image-p (org-file-image-p filename))
25961 (setq thefile (if abs-p (expand-file-name filename) filename))
25962 (when (and org-export-html-link-org-files-as-html
25963 (string-match "\\.org$" thefile))
25964 (setq thefile (concat (substring thefile 0
25965 (match-beginning 0))
25966 "." html-extension))
25967 (if (and search
25968 ;; make sure this is can be used as target search
25969 (not (string-match "^[0-9]*$" search))
25970 (not (string-match "^\\*" search))
25971 (not (string-match "^/.*/$" search)))
25972 (setq thefile (concat thefile "#"
25973 (org-solidify-link-text
25974 (org-link-unescape search)))))
25975 (when (string-match "^file:" desc)
25976 (setq desc (replace-match "" t t desc))
25977 (if (string-match "\\.org$" desc)
25978 (setq desc (replace-match "" t t desc))))))
25979 (setq rpl (if (and file-is-image-p
25980 (or (eq t org-export-html-inline-images)
25981 (and org-export-html-inline-images
25982 (not descp))))
25983 (concat "<img src=\"" thefile "\"/>")
25984 (concat "<a href=\"" thefile "\">" desc "</a>")))
25985 (if (not valid) (setq rpl desc))))
25986 ((member type '("bbdb" "vm" "wl" "mhe" "rmail" "gnus" "shell" "info" "elisp"))
25987 (setq rpl (concat "<i>&lt;" type ":"
25988 (save-match-data (org-link-unescape path))
25989 "&gt;</i>"))))
25990 (setq line (replace-match rpl t t line)
25991 start (+ start (length rpl))))
25993 ;; TODO items
25994 (if (and (string-match org-todo-line-regexp line)
25995 (match-beginning 2))
25997 (setq line
25998 (concat (substring line 0 (match-beginning 2))
25999 "<span class=\""
26000 (if (member (match-string 2 line)
26001 org-done-keywords)
26002 "done" "todo")
26003 "\">" (match-string 2 line)
26004 "</span>" (substring line (match-end 2)))))
26006 ;; Does this contain a reference to a footnote?
26007 (when org-export-with-footnotes
26008 (setq start 0)
26009 (while (string-match "\\([^* \t].*?\\)\\[\\([0-9]+\\)\\]" line start)
26010 (if (get-text-property (match-beginning 2) 'org-protected line)
26011 (setq start (match-end 2))
26012 (let ((n (match-string 2 line)))
26013 (setq line
26014 (replace-match
26015 (format
26016 "%s<sup><a class=\"footref\" name=\"fnr.%s\" href=\"#fn.%s\">%s</a></sup>"
26017 (match-string 1 line) n n n)
26018 t t line))))))
26020 (cond
26021 ((string-match "^\\(\\*+\\)[ \t]+\\(.*\\)" line)
26022 ;; This is a headline
26023 (setq level (org-tr-level (- (match-end 1) (match-beginning 1)))
26024 txt (match-string 2 line))
26025 (if (string-match quote-re0 txt)
26026 (setq txt (replace-match "" t t txt)))
26027 (if (<= level (max umax umax-toc))
26028 (setq head-count (+ head-count 1)))
26029 (when in-local-list
26030 ;; Close any local lists before inserting a new header line
26031 (while local-list-num
26032 (org-close-li)
26033 (insert (if (car local-list-num) "</ol>\n" "</ul>"))
26034 (pop local-list-num))
26035 (setq local-list-indent nil
26036 in-local-list nil))
26037 (setq first-heading-pos (or first-heading-pos (point)))
26038 (org-html-level-start level txt umax
26039 (and org-export-with-toc (<= level umax))
26040 head-count)
26041 ;; QUOTES
26042 (when (string-match quote-re line)
26043 (insert "<pre>")
26044 (setq inquote t)))
26046 ((and org-export-with-tables
26047 (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)" line))
26048 (if (not table-open)
26049 ;; New table starts
26050 (setq table-open t table-buffer nil table-orig-buffer nil))
26051 ;; Accumulate lines
26052 (setq table-buffer (cons line table-buffer)
26053 table-orig-buffer (cons origline table-orig-buffer))
26054 (when (or (not lines)
26055 (not (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)"
26056 (car lines))))
26057 (setq table-open nil
26058 table-buffer (nreverse table-buffer)
26059 table-orig-buffer (nreverse table-orig-buffer))
26060 (org-close-par-maybe)
26061 (insert (org-format-table-html table-buffer table-orig-buffer))))
26063 ;; Normal lines
26064 (when (string-match
26065 (cond
26066 ((eq llt t) "^\\([ \t]*\\)\\(\\([-+*] \\)\\|\\([0-9]+[.)]\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
26067 ((= llt ?.) "^\\([ \t]*\\)\\(\\([-+*] \\)\\|\\([0-9]+\\.\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
26068 ((= llt ?\)) "^\\([ \t]*\\)\\(\\([-+*] \\)\\|\\([0-9]+)\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
26069 (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))
26070 line)
26071 (setq ind (org-get-string-indentation line)
26072 start-is-num (match-beginning 4)
26073 starter (if (match-beginning 2)
26074 (substring (match-string 2 line) 0 -1))
26075 line (substring line (match-beginning 5)))
26076 (unless (string-match "[^ \t]" line)
26077 ;; empty line. Pretend indentation is large.
26078 (setq ind (if org-empty-line-terminates-plain-lists
26080 (1+ (or (car local-list-indent) 1)))))
26081 (setq didclose nil)
26082 (while (and in-local-list
26083 (or (and (= ind (car local-list-indent))
26084 (not starter))
26085 (< ind (car local-list-indent))))
26086 (setq didclose t)
26087 (org-close-li)
26088 (insert (if (car local-list-num) "</ol>\n" "</ul>"))
26089 (pop local-list-num) (pop local-list-indent)
26090 (setq in-local-list local-list-indent))
26091 (cond
26092 ((and starter
26093 (or (not in-local-list)
26094 (> ind (car local-list-indent))))
26095 ;; Start new (level of) list
26096 (org-close-par-maybe)
26097 (insert (if start-is-num "<ol>\n<li>\n" "<ul>\n<li>\n"))
26098 (push start-is-num local-list-num)
26099 (push ind local-list-indent)
26100 (setq in-local-list t))
26101 (starter
26102 ;; continue current list
26103 (org-close-li)
26104 (insert "<li>\n"))
26105 (didclose
26106 ;; we did close a list, normal text follows: need <p>
26107 (org-open-par)))
26108 (if (string-match "^[ \t]*\\[\\([X ]\\)\\]" line)
26109 (setq line
26110 (replace-match
26111 (if (equal (match-string 1 line) "X")
26112 "<b>[X]</b>"
26113 "<b>[<span style=\"visibility:hidden;\">X</span>]</b>")
26114 t t line))))
26116 ;; Empty lines start a new paragraph. If hand-formatted lists
26117 ;; are not fully interpreted, lines starting with "-", "+", "*"
26118 ;; also start a new paragraph.
26119 (if (string-match "^ [-+*]-\\|^[ \t]*$" line) (org-open-par))
26121 ;; Is this the start of a footnote?
26122 (when org-export-with-footnotes
26123 (when (string-match "^[ \t]*\\[\\([0-9]+\\)\\]" line)
26124 (org-close-par-maybe)
26125 (let ((n (match-string 1 line)))
26126 (setq line (replace-match
26127 (format "<p class=\"footnote\"><sup><a class=\"footnum\" name=\"fn.%s\" href=\"#fnr.%s\">%s</a></sup>" n n n) t t line)))))
26129 ;; Check if the line break needs to be conserved
26130 (cond
26131 ((string-match "\\\\\\\\[ \t]*$" line)
26132 (setq line (replace-match "<br/>" t t line)))
26133 (org-export-preserve-breaks
26134 (setq line (concat line "<br/>"))))
26136 (insert line "\n")))))
26138 ;; Properly close all local lists and other lists
26139 (when inquote (insert "</pre>\n"))
26140 (when in-local-list
26141 ;; Close any local lists before inserting a new header line
26142 (while local-list-num
26143 (org-close-li)
26144 (insert (if (car local-list-num) "</ol>\n" "</ul>\n"))
26145 (pop local-list-num))
26146 (setq local-list-indent nil
26147 in-local-list nil))
26148 (org-html-level-start 1 nil umax
26149 (and org-export-with-toc (<= level umax))
26150 head-count)
26151 ;; the </div> to lose the last text-... div.
26152 (insert "</div>\n")
26154 (unless body-only
26155 (when (plist-get opt-plist :auto-postamble)
26156 (insert "<div id=\"postamble\">")
26157 (when (and org-export-author-info author)
26158 (insert "<p class=\"author\"> "
26159 (nth 1 lang-words) ": " author "\n")
26160 (when email
26161 (if (listp (split-string email ",+ *"))
26162 (mapc (lambda(e)
26163 (insert "<a href=\"mailto:" e "\">&lt;"
26164 e "&gt;</a>\n"))
26165 (split-string email ",+ *"))
26166 (insert "<a href=\"mailto:" email "\">&lt;"
26167 email "&gt;</a>\n")))
26168 (insert "</p>\n"))
26169 (when (and date org-export-time-stamp-file)
26170 (insert "<p class=\"date\"> "
26171 (nth 2 lang-words) ": "
26172 date "</p>\n"))
26173 (insert "</div>"))
26175 (if org-export-html-with-timestamp
26176 (insert org-export-html-html-helper-timestamp))
26177 (insert (or (plist-get opt-plist :postamble) ""))
26178 (insert "</body>\n</html>\n"))
26180 (normal-mode)
26181 (if (eq major-mode default-major-mode) (html-mode))
26183 ;; insert the table of contents
26184 (goto-char (point-min))
26185 (when thetoc
26186 (if (or (re-search-forward
26187 "<p>\\s-*\\[TABLE-OF-CONTENTS\\]\\s-*</p>" nil t)
26188 (re-search-forward
26189 "\\[TABLE-OF-CONTENTS\\]" nil t))
26190 (progn
26191 (goto-char (match-beginning 0))
26192 (replace-match ""))
26193 (goto-char first-heading-pos)
26194 (when (looking-at "\\s-*</p>")
26195 (goto-char (match-end 0))
26196 (insert "\n")))
26197 (insert "<div id=\"table-of-contents\">\n")
26198 (mapc 'insert thetoc)
26199 (insert "</div>\n"))
26200 ;; remove empty paragraphs and lists
26201 (goto-char (point-min))
26202 (while (re-search-forward "<p>[ \r\n\t]*</p>" nil t)
26203 (replace-match ""))
26204 (goto-char (point-min))
26205 (while (re-search-forward "<li>[ \r\n\t]*</li>\n?" nil t)
26206 (replace-match ""))
26207 (goto-char (point-min))
26208 (while (re-search-forward "</ul>\\s-*<ul>\n?" nil t)
26209 (replace-match ""))
26210 ;; Convert whitespace place holders
26211 (goto-char (point-min))
26212 (let (beg end n)
26213 (while (setq beg (next-single-property-change (point) 'org-whitespace))
26214 (setq n (get-text-property beg 'org-whitespace)
26215 end (next-single-property-change beg 'org-whitespace))
26216 (goto-char beg)
26217 (delete-region beg end)
26218 (insert (format "<span style=\"visibility:hidden;\">%s</span>"
26219 (make-string n ?x)))))
26220 (or to-buffer (save-buffer))
26221 (goto-char (point-min))
26222 (message "Exporting... done")
26223 (if (eq to-buffer 'string)
26224 (prog1 (buffer-substring (point-min) (point-max))
26225 (kill-buffer (current-buffer)))
26226 (current-buffer)))))
26228 (defvar org-table-colgroup-info nil)
26229 (defun org-format-table-ascii (lines)
26230 "Format a table for ascii export."
26231 (if (stringp lines)
26232 (setq lines (org-split-string lines "\n")))
26233 (if (not (string-match "^[ \t]*|" (car lines)))
26234 ;; Table made by table.el - test for spanning
26235 lines
26237 ;; A normal org table
26238 ;; Get rid of hlines at beginning and end
26239 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
26240 (setq lines (nreverse lines))
26241 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
26242 (setq lines (nreverse lines))
26243 (when org-export-table-remove-special-lines
26244 ;; Check if the table has a marking column. If yes remove the
26245 ;; column and the special lines
26246 (setq lines (org-table-clean-before-export lines)))
26247 ;; Get rid of the vertical lines except for grouping
26248 (let ((vl (org-colgroup-info-to-vline-list org-table-colgroup-info))
26249 rtn line vl1 start)
26250 (while (setq line (pop lines))
26251 (if (string-match org-table-hline-regexp line)
26252 (and (string-match "|\\(.*\\)|" line)
26253 (setq line (replace-match " \\1" t nil line)))
26254 (setq start 0 vl1 vl)
26255 (while (string-match "|" line start)
26256 (setq start (match-end 0))
26257 (or (pop vl1) (setq line (replace-match " " t t line)))))
26258 (push line rtn))
26259 (nreverse rtn))))
26261 (defun org-colgroup-info-to-vline-list (info)
26262 (let (vl new last)
26263 (while info
26264 (setq last new new (pop info))
26265 (if (or (memq last '(:end :startend))
26266 (memq new '(:start :startend)))
26267 (push t vl)
26268 (push nil vl)))
26269 (setq vl (nreverse vl))
26270 (and vl (setcar vl nil))
26271 vl))
26273 (defun org-format-table-html (lines olines)
26274 "Find out which HTML converter to use and return the HTML code."
26275 (if (stringp lines)
26276 (setq lines (org-split-string lines "\n")))
26277 (if (string-match "^[ \t]*|" (car lines))
26278 ;; A normal org table
26279 (org-format-org-table-html lines)
26280 ;; Table made by table.el - test for spanning
26281 (let* ((hlines (delq nil (mapcar
26282 (lambda (x)
26283 (if (string-match "^[ \t]*\\+-" x) x
26284 nil))
26285 lines)))
26286 (first (car hlines))
26287 (ll (and (string-match "\\S-+" first)
26288 (match-string 0 first)))
26289 (re (concat "^[ \t]*" (regexp-quote ll)))
26290 (spanning (delq nil (mapcar (lambda (x) (not (string-match re x)))
26291 hlines))))
26292 (if (and (not spanning)
26293 (not org-export-prefer-native-exporter-for-tables))
26294 ;; We can use my own converter with HTML conversions
26295 (org-format-table-table-html lines)
26296 ;; Need to use the code generator in table.el, with the original text.
26297 (org-format-table-table-html-using-table-generate-source olines)))))
26299 (defun org-format-org-table-html (lines &optional splice)
26300 "Format a table into HTML."
26301 ;; Get rid of hlines at beginning and end
26302 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
26303 (setq lines (nreverse lines))
26304 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
26305 (setq lines (nreverse lines))
26306 (when org-export-table-remove-special-lines
26307 ;; Check if the table has a marking column. If yes remove the
26308 ;; column and the special lines
26309 (setq lines (org-table-clean-before-export lines)))
26311 (let ((head (and org-export-highlight-first-table-line
26312 (delq nil (mapcar
26313 (lambda (x) (string-match "^[ \t]*|-" x))
26314 (cdr lines)))))
26315 (nlines 0) fnum i
26316 tbopen line fields html gr colgropen)
26317 (if splice (setq head nil))
26318 (unless splice (push (if head "<thead>" "<tbody>") html))
26319 (setq tbopen t)
26320 (while (setq line (pop lines))
26321 (catch 'next-line
26322 (if (string-match "^[ \t]*|-" line)
26323 (progn
26324 (unless splice
26325 (push (if head "</thead>" "</tbody>") html)
26326 (if lines (push "<tbody>" html) (setq tbopen nil)))
26327 (setq head nil) ;; head ends here, first time around
26328 ;; ignore this line
26329 (throw 'next-line t)))
26330 ;; Break the line into fields
26331 (setq fields (org-split-string line "[ \t]*|[ \t]*"))
26332 (unless fnum (setq fnum (make-vector (length fields) 0)))
26333 (setq nlines (1+ nlines) i -1)
26334 (push (concat "<tr>"
26335 (mapconcat
26336 (lambda (x)
26337 (setq i (1+ i))
26338 (if (and (< i nlines)
26339 (string-match org-table-number-regexp x))
26340 (incf (aref fnum i)))
26341 (if head
26342 (concat (car org-export-table-header-tags) x
26343 (cdr org-export-table-header-tags))
26344 (concat (car org-export-table-data-tags) x
26345 (cdr org-export-table-data-tags))))
26346 fields "")
26347 "</tr>")
26348 html)))
26349 (unless splice (if tbopen (push "</tbody>" html)))
26350 (unless splice (push "</table>\n" html))
26351 (setq html (nreverse html))
26352 (unless splice
26353 ;; Put in col tags with the alignment (unfortuntely often ignored...)
26354 (push (mapconcat
26355 (lambda (x)
26356 (setq gr (pop org-table-colgroup-info))
26357 (format "%s<col align=\"%s\"></col>%s"
26358 (if (memq gr '(:start :startend))
26359 (prog1
26360 (if colgropen "</colgroup>\n<colgroup>" "<colgroup>")
26361 (setq colgropen t))
26363 (if (> (/ (float x) nlines) org-table-number-fraction)
26364 "right" "left")
26365 (if (memq gr '(:end :startend))
26366 (progn (setq colgropen nil) "</colgroup>")
26367 "")))
26368 fnum "")
26369 html)
26370 (if colgropen (setq html (cons (car html) (cons "</colgroup>" (cdr html)))))
26371 (push html-table-tag html))
26372 (concat (mapconcat 'identity html "\n") "\n")))
26374 (defun org-table-clean-before-export (lines)
26375 "Check if the table has a marking column.
26376 If yes remove the column and the special lines."
26377 (setq org-table-colgroup-info nil)
26378 (if (memq nil
26379 (mapcar
26380 (lambda (x) (or (string-match "^[ \t]*|-" x)
26381 (string-match "^[ \t]*| *\\([#!$*_^ /]\\) *|" x)))
26382 lines))
26383 (progn
26384 (setq org-table-clean-did-remove-column nil)
26385 (delq nil
26386 (mapcar
26387 (lambda (x)
26388 (cond
26389 ((string-match "^[ \t]*| */ *|" x)
26390 (setq org-table-colgroup-info
26391 (mapcar (lambda (x)
26392 (cond ((member x '("<" "&lt;")) :start)
26393 ((member x '(">" "&gt;")) :end)
26394 ((member x '("<>" "&lt;&gt;")) :startend)
26395 (t nil)))
26396 (org-split-string x "[ \t]*|[ \t]*")))
26397 nil)
26398 (t x)))
26399 lines)))
26400 (setq org-table-clean-did-remove-column t)
26401 (delq nil
26402 (mapcar
26403 (lambda (x)
26404 (cond
26405 ((string-match "^[ \t]*| */ *|" x)
26406 (setq org-table-colgroup-info
26407 (mapcar (lambda (x)
26408 (cond ((member x '("<" "&lt;")) :start)
26409 ((member x '(">" "&gt;")) :end)
26410 ((member x '("<>" "&lt;&gt;")) :startend)
26411 (t nil)))
26412 (cdr (org-split-string x "[ \t]*|[ \t]*"))))
26413 nil)
26414 ((string-match "^[ \t]*| *[!_^/] *|" x)
26415 nil) ; ignore this line
26416 ((or (string-match "^\\([ \t]*\\)|-+\\+" x)
26417 (string-match "^\\([ \t]*\\)|[^|]*|" x))
26418 ;; remove the first column
26419 (replace-match "\\1|" t nil x))))
26420 lines))))
26422 (defun org-format-table-table-html (lines)
26423 "Format a table generated by table.el into HTML.
26424 This conversion does *not* use `table-generate-source' from table.el.
26425 This has the advantage that Org-mode's HTML conversions can be used.
26426 But it has the disadvantage, that no cell- or row-spanning is allowed."
26427 (let (line field-buffer
26428 (head org-export-highlight-first-table-line)
26429 fields html empty)
26430 (setq html (concat html-table-tag "\n"))
26431 (while (setq line (pop lines))
26432 (setq empty "&nbsp;")
26433 (catch 'next-line
26434 (if (string-match "^[ \t]*\\+-" line)
26435 (progn
26436 (if field-buffer
26437 (progn
26438 (setq
26439 html
26440 (concat
26441 html
26442 "<tr>"
26443 (mapconcat
26444 (lambda (x)
26445 (if (equal x "") (setq x empty))
26446 (if head
26447 (concat (car org-export-table-header-tags) x
26448 (cdr org-export-table-header-tags))
26449 (concat (car org-export-table-data-tags) x
26450 (cdr org-export-table-data-tags))))
26451 field-buffer "\n")
26452 "</tr>\n"))
26453 (setq head nil)
26454 (setq field-buffer nil)))
26455 ;; Ignore this line
26456 (throw 'next-line t)))
26457 ;; Break the line into fields and store the fields
26458 (setq fields (org-split-string line "[ \t]*|[ \t]*"))
26459 (if field-buffer
26460 (setq field-buffer (mapcar
26461 (lambda (x)
26462 (concat x "<br/>" (pop fields)))
26463 field-buffer))
26464 (setq field-buffer fields))))
26465 (setq html (concat html "</table>\n"))
26466 html))
26468 (defun org-format-table-table-html-using-table-generate-source (lines)
26469 "Format a table into html, using `table-generate-source' from table.el.
26470 This has the advantage that cell- or row-spanning is allowed.
26471 But it has the disadvantage, that Org-mode's HTML conversions cannot be used."
26472 (require 'table)
26473 (with-current-buffer (get-buffer-create " org-tmp1 ")
26474 (erase-buffer)
26475 (insert (mapconcat 'identity lines "\n"))
26476 (goto-char (point-min))
26477 (if (not (re-search-forward "|[^+]" nil t))
26478 (error "Error processing table"))
26479 (table-recognize-table)
26480 (with-current-buffer (get-buffer-create " org-tmp2 ") (erase-buffer))
26481 (table-generate-source 'html " org-tmp2 ")
26482 (set-buffer " org-tmp2 ")
26483 (buffer-substring (point-min) (point-max))))
26485 (defun org-html-handle-time-stamps (s)
26486 "Format time stamps in string S, or remove them."
26487 (catch 'exit
26488 (let (r b)
26489 (while (string-match org-maybe-keyword-time-regexp s)
26490 (if (and (match-end 1) (equal (match-string 1 s) org-clock-string))
26491 ;; never export CLOCK
26492 (throw 'exit ""))
26493 (or b (setq b (substring s 0 (match-beginning 0))))
26494 (if (not org-export-with-timestamps)
26495 (setq r (concat r (substring s 0 (match-beginning 0)))
26496 s (substring s (match-end 0)))
26497 (setq r (concat
26498 r (substring s 0 (match-beginning 0))
26499 (if (match-end 1)
26500 (format "@<span class=\"timestamp-kwd\">%s @</span>"
26501 (match-string 1 s)))
26502 (format " @<span class=\"timestamp\">%s@</span>"
26503 (substring
26504 (org-translate-time (match-string 3 s)) 1 -1)))
26505 s (substring s (match-end 0)))))
26506 ;; Line break if line started and ended with time stamp stuff
26507 (if (not r)
26509 (setq r (concat r s))
26510 (unless (string-match "\\S-" (concat b s))
26511 (setq r (concat r "@<br/>")))
26512 r))))
26514 (defun org-html-protect (s)
26515 ;; convert & to &amp;, < to &lt; and > to &gt;
26516 (let ((start 0))
26517 (while (string-match "&" s start)
26518 (setq s (replace-match "&amp;" t t s)
26519 start (1+ (match-beginning 0))))
26520 (while (string-match "<" s)
26521 (setq s (replace-match "&lt;" t t s)))
26522 (while (string-match ">" s)
26523 (setq s (replace-match "&gt;" t t s))))
26526 (defun org-export-cleanup-toc-line (s)
26527 "Remove tags and time staps from lines going into the toc."
26528 (when (memq org-export-with-tags '(not-in-toc nil))
26529 (if (string-match (org-re " +:[[:alnum:]_@:]+: *$") s)
26530 (setq s (replace-match "" t t s))))
26531 (when org-export-remove-timestamps-from-toc
26532 (while (string-match org-maybe-keyword-time-regexp s)
26533 (setq s (replace-match "" t t s))))
26534 (while (string-match org-bracket-link-regexp s)
26535 (setq s (replace-match (match-string (if (match-end 3) 3 1) s)
26536 t t s)))
26539 (defun org-html-expand (string)
26540 "Prepare STRING for HTML export. Applies all active conversions.
26541 If there are links in the string, don't modify these."
26542 (let* ((re (concat org-bracket-link-regexp "\\|"
26543 (org-re "[ \t]+\\(:[[:alnum:]_@:]+:\\)[ \t]*$")))
26544 m s l res)
26545 (while (setq m (string-match re string))
26546 (setq s (substring string 0 m)
26547 l (match-string 0 string)
26548 string (substring string (match-end 0)))
26549 (push (org-html-do-expand s) res)
26550 (push l res))
26551 (push (org-html-do-expand string) res)
26552 (apply 'concat (nreverse res))))
26554 (defun org-html-do-expand (s)
26555 "Apply all active conversions to translate special ASCII to HTML."
26556 (setq s (org-html-protect s))
26557 (if org-export-html-expand
26558 (let ((start 0))
26559 (while (string-match "@&lt;\\([^&]*\\)&gt;" s)
26560 (setq s (replace-match "<\\1>" t nil s)))))
26561 (if org-export-with-emphasize
26562 (setq s (org-export-html-convert-emphasize s)))
26563 (if org-export-with-special-strings
26564 (setq s (org-export-html-convert-special-strings s)))
26565 (if org-export-with-sub-superscripts
26566 (setq s (org-export-html-convert-sub-super s)))
26567 (if org-export-with-TeX-macros
26568 (let ((start 0) wd ass)
26569 (while (setq start (string-match "\\\\\\([a-zA-Z]+\\)" s start))
26570 (if (get-text-property (match-beginning 0) 'org-protected s)
26571 (setq start (match-end 0))
26572 (setq wd (match-string 1 s))
26573 (if (setq ass (assoc wd org-html-entities))
26574 (setq s (replace-match (or (cdr ass)
26575 (concat "&" (car ass) ";"))
26576 t t s))
26577 (setq start (+ start (length wd))))))))
26580 (defun org-create-multibrace-regexp (left right n)
26581 "Create a regular expression which will match a balanced sexp.
26582 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
26583 as single character strings.
26584 The regexp returned will match the entire expression including the
26585 delimiters. It will also define a single group which contains the
26586 match except for the outermost delimiters. The maximum depth of
26587 stacked delimiters is N. Escaping delimiters is not possible."
26588 (let* ((nothing (concat "[^" "\\" left "\\" right "]*?"))
26589 (or "\\|")
26590 (re nothing)
26591 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
26592 (while (> n 1)
26593 (setq n (1- n)
26594 re (concat re or next)
26595 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
26596 (concat left "\\(" re "\\)" right)))
26598 (defvar org-match-substring-regexp
26599 (concat
26600 "\\([^\\]\\)\\([_^]\\)\\("
26601 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
26602 "\\|"
26603 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
26604 "\\|"
26605 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
26606 "The regular expression matching a sub- or superscript.")
26608 (defvar org-match-substring-with-braces-regexp
26609 (concat
26610 "\\([^\\]\\)\\([_^]\\)\\("
26611 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
26612 "\\)")
26613 "The regular expression matching a sub- or superscript, forcing braces.")
26615 (defconst org-export-html-special-string-regexps
26616 '(("\\\\-" . "&shy;")
26617 ("---\\([^-]\\)" . "&mdash;\\1")
26618 ("--\\([^-]\\)" . "&ndash;\\1")
26619 ("\\.\\.\\." . "&hellip;"))
26620 "Regular expressions for special string conversion.")
26622 (defun org-export-html-convert-special-strings (string)
26623 "Convert special characters in STRING to HTML."
26624 (let ((all org-export-html-special-string-regexps)
26625 e a re rpl start)
26626 (while (setq a (pop all))
26627 (setq re (car a) rpl (cdr a) start 0)
26628 (while (string-match re string start)
26629 (if (get-text-property (match-beginning 0) 'org-protected string)
26630 (setq start (match-end 0))
26631 (setq string (replace-match rpl t nil string)))))
26632 string))
26634 (defun org-export-html-convert-sub-super (string)
26635 "Convert sub- and superscripts in STRING to HTML."
26636 (let (key c (s 0) (requireb (eq org-export-with-sub-superscripts '{})))
26637 (while (string-match org-match-substring-regexp string s)
26638 (cond
26639 ((and requireb (match-end 8)) (setq s (match-end 2)))
26640 ((get-text-property (match-beginning 2) 'org-protected string)
26641 (setq s (match-end 2)))
26643 (setq s (match-end 1)
26644 key (if (string= (match-string 2 string) "_") "sub" "sup")
26645 c (or (match-string 8 string)
26646 (match-string 6 string)
26647 (match-string 5 string))
26648 string (replace-match
26649 (concat (match-string 1 string)
26650 "<" key ">" c "</" key ">")
26651 t t string)))))
26652 (while (string-match "\\\\\\([_^]\\)" string)
26653 (setq string (replace-match (match-string 1 string) t t string)))
26654 string))
26656 (defun org-export-html-convert-emphasize (string)
26657 "Apply emphasis."
26658 (let ((s 0) rpl)
26659 (while (string-match org-emph-re string s)
26660 (if (not (equal
26661 (substring string (match-beginning 3) (1+ (match-beginning 3)))
26662 (substring string (match-beginning 4) (1+ (match-beginning 4)))))
26663 (setq s (match-beginning 0)
26665 (concat
26666 (match-string 1 string)
26667 (nth 2 (assoc (match-string 3 string) org-emphasis-alist))
26668 (match-string 4 string)
26669 (nth 3 (assoc (match-string 3 string)
26670 org-emphasis-alist))
26671 (match-string 5 string))
26672 string (replace-match rpl t t string)
26673 s (+ s (- (length rpl) 2)))
26674 (setq s (1+ s))))
26675 string))
26677 (defvar org-par-open nil)
26678 (defun org-open-par ()
26679 "Insert <p>, but first close previous paragraph if any."
26680 (org-close-par-maybe)
26681 (insert "\n<p>")
26682 (setq org-par-open t))
26683 (defun org-close-par-maybe ()
26684 "Close paragraph if there is one open."
26685 (when org-par-open
26686 (insert "</p>")
26687 (setq org-par-open nil)))
26688 (defun org-close-li ()
26689 "Close <li> if necessary."
26690 (org-close-par-maybe)
26691 (insert "</li>\n"))
26693 (defvar body-only) ; dynamically scoped into this.
26694 (defun org-html-level-start (level title umax with-toc head-count)
26695 "Insert a new level in HTML export.
26696 When TITLE is nil, just close all open levels."
26697 (org-close-par-maybe)
26698 (let ((l org-level-max) snumber)
26699 (while (>= l level)
26700 (if (aref org-levels-open (1- l))
26701 (progn
26702 (org-html-level-close l umax)
26703 (aset org-levels-open (1- l) nil)))
26704 (setq l (1- l)))
26705 (when title
26706 ;; If title is nil, this means this function is called to close
26707 ;; all levels, so the rest is done only if title is given
26708 (when (string-match (org-re "\\(:[[:alnum:]_@:]+:\\)[ \t]*$") title)
26709 (setq title (replace-match
26710 (if org-export-with-tags
26711 (save-match-data
26712 (concat
26713 "&nbsp;&nbsp;&nbsp;<span class=\"tag\">"
26714 (mapconcat 'identity (org-split-string
26715 (match-string 1 title) ":")
26716 "&nbsp;")
26717 "</span>"))
26719 t t title)))
26720 (if (> level umax)
26721 (progn
26722 (if (aref org-levels-open (1- level))
26723 (progn
26724 (org-close-li)
26725 (insert "<li>" title "<br/>\n"))
26726 (aset org-levels-open (1- level) t)
26727 (org-close-par-maybe)
26728 (insert "<ul>\n<li>" title "<br/>\n")))
26729 (aset org-levels-open (1- level) t)
26730 (setq snumber (org-section-number level))
26731 (if (and org-export-with-section-numbers (not body-only))
26732 (setq title (concat snumber " " title)))
26733 (setq level (+ level org-export-html-toplevel-hlevel -1))
26734 (unless (= head-count 1) (insert "\n</div>\n"))
26735 (insert (format "\n<div id=\"outline-container-%s\" class=\"outline-%d\">\n<h%d id=\"sec-%s\">%s</h%d>\n<div id=\"text-%s\">\n"
26736 snumber level level snumber title level snumber))
26737 (org-open-par)))))
26739 (defun org-html-level-close (level max-outline-level)
26740 "Terminate one level in HTML export."
26741 (if (<= level max-outline-level)
26742 (insert "</div>\n")
26743 (org-close-li)
26744 (insert "</ul>\n")))
26746 ;;; iCalendar export
26748 ;;;###autoload
26749 (defun org-export-icalendar-this-file ()
26750 "Export current file as an iCalendar file.
26751 The iCalendar file will be located in the same directory as the Org-mode
26752 file, but with extension `.ics'."
26753 (interactive)
26754 (org-export-icalendar nil buffer-file-name))
26756 ;;;###autoload
26757 (defun org-export-icalendar-all-agenda-files ()
26758 "Export all files in `org-agenda-files' to iCalendar .ics files.
26759 Each iCalendar file will be located in the same directory as the Org-mode
26760 file, but with extension `.ics'."
26761 (interactive)
26762 (apply 'org-export-icalendar nil (org-agenda-files t)))
26764 ;;;###autoload
26765 (defun org-export-icalendar-combine-agenda-files ()
26766 "Export all files in `org-agenda-files' to a single combined iCalendar file.
26767 The file is stored under the name `org-combined-agenda-icalendar-file'."
26768 (interactive)
26769 (apply 'org-export-icalendar t (org-agenda-files t)))
26771 (defun org-export-icalendar (combine &rest files)
26772 "Create iCalendar files for all elements of FILES.
26773 If COMBINE is non-nil, combine all calendar entries into a single large
26774 file and store it under the name `org-combined-agenda-icalendar-file'."
26775 (save-excursion
26776 (org-prepare-agenda-buffers files)
26777 (let* ((dir (org-export-directory
26778 :ical (list :publishing-directory
26779 org-export-publishing-directory)))
26780 file ical-file ical-buffer category started org-agenda-new-buffers)
26781 (and (get-buffer "*ical-tmp*") (kill-buffer "*ical-tmp*"))
26782 (when combine
26783 (setq ical-file
26784 (if (file-name-absolute-p org-combined-agenda-icalendar-file)
26785 org-combined-agenda-icalendar-file
26786 (expand-file-name org-combined-agenda-icalendar-file dir))
26787 ical-buffer (org-get-agenda-file-buffer ical-file))
26788 (set-buffer ical-buffer) (erase-buffer))
26789 (while (setq file (pop files))
26790 (catch 'nextfile
26791 (org-check-agenda-file file)
26792 (set-buffer (org-get-agenda-file-buffer file))
26793 (unless combine
26794 (setq ical-file (concat (file-name-as-directory dir)
26795 (file-name-sans-extension
26796 (file-name-nondirectory buffer-file-name))
26797 ".ics"))
26798 (setq ical-buffer (org-get-agenda-file-buffer ical-file))
26799 (with-current-buffer ical-buffer (erase-buffer)))
26800 (setq category (or org-category
26801 (file-name-sans-extension
26802 (file-name-nondirectory buffer-file-name))))
26803 (if (symbolp category) (setq category (symbol-name category)))
26804 (let ((standard-output ical-buffer))
26805 (if combine
26806 (and (not started) (setq started t)
26807 (org-start-icalendar-file org-icalendar-combined-name))
26808 (org-start-icalendar-file category))
26809 (org-print-icalendar-entries combine)
26810 (when (or (and combine (not files)) (not combine))
26811 (org-finish-icalendar-file)
26812 (set-buffer ical-buffer)
26813 (save-buffer)
26814 (run-hooks 'org-after-save-iCalendar-file-hook)))))
26815 (org-release-buffers org-agenda-new-buffers))))
26817 (defvar org-after-save-iCalendar-file-hook nil
26818 "Hook run after an iCalendar file has been saved.
26819 The iCalendar buffer is still current when this hook is run.
26820 A good way to use this is to tell a desktop calenndar application to re-read
26821 the iCalendar file.")
26823 (defun org-print-icalendar-entries (&optional combine)
26824 "Print iCalendar entries for the current Org-mode file to `standard-output'.
26825 When COMBINE is non nil, add the category to each line."
26826 (let ((re1 (concat org-ts-regexp "\\|<%%([^>\n]+>"))
26827 (re2 (concat "--?-?\\(" org-ts-regexp "\\)"))
26828 (dts (org-ical-ts-to-string
26829 (format-time-string (cdr org-time-stamp-formats) (current-time))
26830 "DTSTART"))
26831 hd ts ts2 state status (inc t) pos b sexp rrule
26832 scheduledp deadlinep tmp pri category entry location summary desc
26833 (sexp-buffer (get-buffer-create "*ical-tmp*")))
26834 (org-refresh-category-properties)
26835 (save-excursion
26836 (goto-char (point-min))
26837 (while (re-search-forward re1 nil t)
26838 (catch :skip
26839 (org-agenda-skip)
26840 (when (boundp 'org-icalendar-verify-function)
26841 (unless (funcall org-icalendar-verify-function)
26842 (outline-next-heading)
26843 (backward-char 1)
26844 (throw :skip nil)))
26845 (setq pos (match-beginning 0)
26846 ts (match-string 0)
26847 inc t
26848 hd (org-get-heading)
26849 summary (org-icalendar-cleanup-string
26850 (org-entry-get nil "SUMMARY"))
26851 desc (org-icalendar-cleanup-string
26852 (or (org-entry-get nil "DESCRIPTION")
26853 (and org-icalendar-include-body (org-get-entry)))
26854 t org-icalendar-include-body)
26855 location (org-icalendar-cleanup-string
26856 (org-entry-get nil "LOCATION"))
26857 category (org-get-category))
26858 (if (looking-at re2)
26859 (progn
26860 (goto-char (match-end 0))
26861 (setq ts2 (match-string 1) inc nil))
26862 (setq tmp (buffer-substring (max (point-min)
26863 (- pos org-ds-keyword-length))
26864 pos)
26865 ts2 (if (string-match "[0-9]\\{1,2\\}:[0-9][0-9]-\\([0-9]\\{1,2\\}:[0-9][0-9]\\)" ts)
26866 (progn
26867 (setq inc nil)
26868 (replace-match "\\1" t nil ts))
26870 deadlinep (string-match org-deadline-regexp tmp)
26871 scheduledp (string-match org-scheduled-regexp tmp)
26872 ;; donep (org-entry-is-done-p)
26874 (if (or (string-match org-tr-regexp hd)
26875 (string-match org-ts-regexp hd))
26876 (setq hd (replace-match "" t t hd)))
26877 (if (string-match "\\+\\([0-9]+\\)\\([dwmy]\\)>" ts)
26878 (setq rrule
26879 (concat "\nRRULE:FREQ="
26880 (cdr (assoc
26881 (match-string 2 ts)
26882 '(("d" . "DAILY")("w" . "WEEKLY")
26883 ("m" . "MONTHLY")("y" . "YEARLY"))))
26884 ";INTERVAL=" (match-string 1 ts)))
26885 (setq rrule ""))
26886 (setq summary (or summary hd))
26887 (if (string-match org-bracket-link-regexp summary)
26888 (setq summary
26889 (replace-match (if (match-end 3)
26890 (match-string 3 summary)
26891 (match-string 1 summary))
26892 t t summary)))
26893 (if deadlinep (setq summary (concat "DL: " summary)))
26894 (if scheduledp (setq summary (concat "S: " summary)))
26895 (if (string-match "\\`<%%" ts)
26896 (with-current-buffer sexp-buffer
26897 (insert (substring ts 1 -1) " " summary "\n"))
26898 (princ (format "BEGIN:VEVENT
26900 %s%s
26901 SUMMARY:%s%s%s
26902 CATEGORIES:%s
26903 END:VEVENT\n"
26904 (org-ical-ts-to-string ts "DTSTART")
26905 (org-ical-ts-to-string ts2 "DTEND" inc)
26906 rrule summary
26907 (if (and desc (string-match "\\S-" desc))
26908 (concat "\nDESCRIPTION: " desc) "")
26909 (if (and location (string-match "\\S-" location))
26910 (concat "\nLOCATION: " location) "")
26911 category)))))
26913 (when (and org-icalendar-include-sexps
26914 (condition-case nil (require 'icalendar) (error nil))
26915 (fboundp 'icalendar-export-region))
26916 ;; Get all the literal sexps
26917 (goto-char (point-min))
26918 (while (re-search-forward "^&?%%(" nil t)
26919 (catch :skip
26920 (org-agenda-skip)
26921 (setq b (match-beginning 0))
26922 (goto-char (1- (match-end 0)))
26923 (forward-sexp 1)
26924 (end-of-line 1)
26925 (setq sexp (buffer-substring b (point)))
26926 (with-current-buffer sexp-buffer
26927 (insert sexp "\n"))
26928 (princ (org-diary-to-ical-string sexp-buffer)))))
26930 (when org-icalendar-include-todo
26931 (goto-char (point-min))
26932 (while (re-search-forward org-todo-line-regexp nil t)
26933 (catch :skip
26934 (org-agenda-skip)
26935 (when (boundp 'org-icalendar-verify-function)
26936 (unless (funcall org-icalendar-verify-function)
26937 (outline-next-heading)
26938 (backward-char 1)
26939 (throw :skip nil)))
26940 (setq state (match-string 2))
26941 (setq status (if (member state org-done-keywords)
26942 "COMPLETED" "NEEDS-ACTION"))
26943 (when (and state
26944 (or (not (member state org-done-keywords))
26945 (eq org-icalendar-include-todo 'all))
26946 (not (member org-archive-tag (org-get-tags-at)))
26948 (setq hd (match-string 3)
26949 summary (org-icalendar-cleanup-string
26950 (org-entry-get nil "SUMMARY"))
26951 desc (org-icalendar-cleanup-string
26952 (or (org-entry-get nil "DESCRIPTION")
26953 (and org-icalendar-include-body (org-get-entry)))
26954 t org-icalendar-include-body)
26955 location (org-icalendar-cleanup-string
26956 (org-entry-get nil "LOCATION")))
26957 (if (string-match org-bracket-link-regexp hd)
26958 (setq hd (replace-match (if (match-end 3) (match-string 3 hd)
26959 (match-string 1 hd))
26960 t t hd)))
26961 (if (string-match org-priority-regexp hd)
26962 (setq pri (string-to-char (match-string 2 hd))
26963 hd (concat (substring hd 0 (match-beginning 1))
26964 (substring hd (match-end 1))))
26965 (setq pri org-default-priority))
26966 (setq pri (floor (1+ (* 8. (/ (float (- org-lowest-priority pri))
26967 (- org-lowest-priority org-highest-priority))))))
26969 (princ (format "BEGIN:VTODO
26971 SUMMARY:%s%s%s
26972 CATEGORIES:%s
26973 SEQUENCE:1
26974 PRIORITY:%d
26975 STATUS:%s
26976 END:VTODO\n"
26978 (or summary hd)
26979 (if (and location (string-match "\\S-" location))
26980 (concat "\nLOCATION: " location) "")
26981 (if (and desc (string-match "\\S-" desc))
26982 (concat "\nDESCRIPTION: " desc) "")
26983 category pri status)))))))))
26985 (defun org-icalendar-cleanup-string (s &optional is-body maxlength)
26986 "Take out stuff and quote what needs to be quoted.
26987 When IS-BODY is non-nil, assume that this is the body of an item, clean up
26988 whitespace, newlines, drawers, and timestamps, and cut it down to MAXLENGTH
26989 characters."
26990 (if (not s)
26992 (when is-body
26993 (let ((re (concat "\\(" org-drawer-regexp "\\)[^\000]*?:END:.*\n?"))
26994 (re2 (concat "^[ \t]*" org-keyword-time-regexp ".*\n?")))
26995 (while (string-match re s) (setq s (replace-match "" t t s)))
26996 (while (string-match re2 s) (setq s (replace-match "" t t s)))))
26997 (let ((start 0))
26998 (while (string-match "\\([,;\\]\\)" s start)
26999 (setq start (+ (match-beginning 0) 2)
27000 s (replace-match "\\\\\\1" nil nil s))))
27001 (when is-body
27002 (while (string-match "[ \t]*\n[ \t]*" s)
27003 (setq s (replace-match "\\n" t t s))))
27004 (setq s (org-trim s))
27005 (if is-body
27006 (if maxlength
27007 (if (and (numberp maxlength)
27008 (> (length s) maxlength))
27009 (setq s (substring s 0 maxlength)))))
27012 (defun org-get-entry ()
27013 "Clean-up description string."
27014 (save-excursion
27015 (org-back-to-heading t)
27016 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
27018 (defun org-start-icalendar-file (name)
27019 "Start an iCalendar file by inserting the header."
27020 (let ((user user-full-name)
27021 (name (or name "unknown"))
27022 (timezone (cadr (current-time-zone))))
27023 (princ
27024 (format "BEGIN:VCALENDAR
27025 VERSION:2.0
27026 X-WR-CALNAME:%s
27027 PRODID:-//%s//Emacs with Org-mode//EN
27028 X-WR-TIMEZONE:%s
27029 CALSCALE:GREGORIAN\n" name user timezone))))
27031 (defun org-finish-icalendar-file ()
27032 "Finish an iCalendar file by inserting the END statement."
27033 (princ "END:VCALENDAR\n"))
27035 (defun org-ical-ts-to-string (s keyword &optional inc)
27036 "Take a time string S and convert it to iCalendar format.
27037 KEYWORD is added in front, to make a complete line like DTSTART....
27038 When INC is non-nil, increase the hour by two (if time string contains
27039 a time), or the day by one (if it does not contain a time)."
27040 (let ((t1 (org-parse-time-string s 'nodefault))
27041 t2 fmt have-time time)
27042 (if (and (car t1) (nth 1 t1) (nth 2 t1))
27043 (setq t2 t1 have-time t)
27044 (setq t2 (org-parse-time-string s)))
27045 (let ((s (car t2)) (mi (nth 1 t2)) (h (nth 2 t2))
27046 (d (nth 3 t2)) (m (nth 4 t2)) (y (nth 5 t2)))
27047 (when inc
27048 (if have-time
27049 (if org-agenda-default-appointment-duration
27050 (setq mi (+ org-agenda-default-appointment-duration mi))
27051 (setq h (+ 2 h)))
27052 (setq d (1+ d))))
27053 (setq time (encode-time s mi h d m y)))
27054 (setq fmt (if have-time ":%Y%m%dT%H%M%S" ";VALUE=DATE:%Y%m%d"))
27055 (concat keyword (format-time-string fmt time))))
27057 ;;; XOXO export
27059 (defun org-export-as-xoxo-insert-into (buffer &rest output)
27060 (with-current-buffer buffer
27061 (apply 'insert output)))
27062 (put 'org-export-as-xoxo-insert-into 'lisp-indent-function 1)
27064 (defun org-export-as-xoxo (&optional buffer)
27065 "Export the org buffer as XOXO.
27066 The XOXO buffer is named *xoxo-<source buffer name>*"
27067 (interactive (list (current-buffer)))
27068 ;; A quickie abstraction
27070 ;; Output everything as XOXO
27071 (with-current-buffer (get-buffer buffer)
27072 (let* ((pos (point))
27073 (opt-plist (org-combine-plists (org-default-export-plist)
27074 (org-infile-export-plist)))
27075 (filename (concat (file-name-as-directory
27076 (org-export-directory :xoxo opt-plist))
27077 (file-name-sans-extension
27078 (file-name-nondirectory buffer-file-name))
27079 ".html"))
27080 (out (find-file-noselect filename))
27081 (last-level 1)
27082 (hanging-li nil))
27083 (goto-char (point-min)) ;; CD: beginning-of-buffer is not allowed.
27084 ;; Check the output buffer is empty.
27085 (with-current-buffer out (erase-buffer))
27086 ;; Kick off the output
27087 (org-export-as-xoxo-insert-into out "<ol class='xoxo'>\n")
27088 (while (re-search-forward "^\\(\\*+\\)[ \t]+\\(.+\\)" (point-max) 't)
27089 (let* ((hd (match-string-no-properties 1))
27090 (level (length hd))
27091 (text (concat
27092 (match-string-no-properties 2)
27093 (save-excursion
27094 (goto-char (match-end 0))
27095 (let ((str ""))
27096 (catch 'loop
27097 (while 't
27098 (forward-line)
27099 (if (looking-at "^[ \t]\\(.*\\)")
27100 (setq str (concat str (match-string-no-properties 1)))
27101 (throw 'loop str)))))))))
27103 ;; Handle level rendering
27104 (cond
27105 ((> level last-level)
27106 (org-export-as-xoxo-insert-into out "\n<ol>\n"))
27108 ((< level last-level)
27109 (dotimes (- (- last-level level) 1)
27110 (if hanging-li
27111 (org-export-as-xoxo-insert-into out "</li>\n"))
27112 (org-export-as-xoxo-insert-into out "</ol>\n"))
27113 (when hanging-li
27114 (org-export-as-xoxo-insert-into out "</li>\n")
27115 (setq hanging-li nil)))
27117 ((equal level last-level)
27118 (if hanging-li
27119 (org-export-as-xoxo-insert-into out "</li>\n")))
27122 (setq last-level level)
27124 ;; And output the new li
27125 (setq hanging-li 't)
27126 (if (equal ?+ (elt text 0))
27127 (org-export-as-xoxo-insert-into out "<li class='" (substring text 1) "'>")
27128 (org-export-as-xoxo-insert-into out "<li>" text))))
27130 ;; Finally finish off the ol
27131 (dotimes (- last-level 1)
27132 (if hanging-li
27133 (org-export-as-xoxo-insert-into out "</li>\n"))
27134 (org-export-as-xoxo-insert-into out "</ol>\n"))
27136 (goto-char pos)
27137 ;; Finish the buffer off and clean it up.
27138 (switch-to-buffer-other-window out)
27139 (indent-region (point-min) (point-max) nil)
27140 (save-buffer)
27141 (goto-char (point-min))
27145 ;;;; Key bindings
27147 ;; Make `C-c C-x' a prefix key
27148 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
27150 ;; TAB key with modifiers
27151 (org-defkey org-mode-map "\C-i" 'org-cycle)
27152 (org-defkey org-mode-map [(tab)] 'org-cycle)
27153 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
27154 (org-defkey org-mode-map [(meta tab)] 'org-complete)
27155 (org-defkey org-mode-map "\M-\t" 'org-complete)
27156 (org-defkey org-mode-map "\M-\C-i" 'org-complete)
27157 ;; The following line is necessary under Suse GNU/Linux
27158 (unless (featurep 'xemacs)
27159 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
27160 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
27161 (define-key org-mode-map [backtab] 'org-shifttab)
27163 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
27164 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
27165 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
27167 ;; Cursor keys with modifiers
27168 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
27169 (org-defkey org-mode-map [(meta right)] 'org-metaright)
27170 (org-defkey org-mode-map [(meta up)] 'org-metaup)
27171 (org-defkey org-mode-map [(meta down)] 'org-metadown)
27173 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
27174 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
27175 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
27176 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
27178 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
27179 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
27180 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
27181 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
27183 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
27184 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
27186 ;;; Extra keys for tty access.
27187 ;; We only set them when really needed because otherwise the
27188 ;; menus don't show the simple keys
27190 (when (or (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
27191 (not window-system))
27192 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
27193 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
27194 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
27195 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
27196 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
27197 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
27198 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
27199 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
27200 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
27201 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
27202 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
27203 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
27204 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
27205 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
27206 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
27207 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
27208 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
27209 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
27210 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
27211 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
27212 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
27213 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft))
27215 ;; All the other keys
27217 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
27218 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
27219 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree)
27220 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
27221 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
27222 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-toggle-archive-tag)
27223 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
27224 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
27225 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
27226 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
27227 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
27228 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
27229 (org-defkey org-mode-map "\C-c\C-v" 'org-show-todo-tree)
27230 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
27231 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
27232 (org-defkey org-mode-map "\C-c\\" 'org-tags-sparse-tree) ; Minor-mode res.
27233 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
27234 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
27235 (org-defkey org-mode-map [(control return)] 'org-insert-heading-after-current)
27236 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
27237 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
27238 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
27239 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
27240 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
27241 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
27242 (org-defkey org-mode-map "\C-c\C-z" 'org-time-stamp) ; Alternative binding
27243 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
27244 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
27245 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
27246 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
27247 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
27248 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
27249 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
27250 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
27251 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
27252 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
27253 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
27254 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
27255 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
27256 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
27257 (org-defkey org-mode-map "\C-c^" 'org-sort)
27258 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
27259 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
27260 (org-defkey org-mode-map "\C-c#" 'org-update-checkbox-count)
27261 (org-defkey org-mode-map "\C-m" 'org-return)
27262 (org-defkey org-mode-map "\C-j" 'org-return-indent)
27263 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
27264 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
27265 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
27266 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
27267 (org-defkey org-mode-map "\C-c'" 'org-table-edit-formulas)
27268 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
27269 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
27270 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
27271 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
27272 (org-defkey org-mode-map "\C-c\C-q" 'org-table-wrap-region)
27273 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
27274 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
27275 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
27276 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
27277 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
27279 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-cut-special)
27280 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
27281 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
27282 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
27284 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
27285 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
27286 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
27287 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
27288 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
27289 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
27290 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
27291 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
27292 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
27293 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
27294 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
27295 (org-defkey org-mode-map "\C-c\C-xr" 'org-insert-columns-dblock)
27297 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
27299 (when (featurep 'xemacs)
27300 (org-defkey org-mode-map 'button3 'popup-mode-menu))
27302 (defsubst org-table-p () (org-at-table-p))
27304 (defun org-self-insert-command (N)
27305 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
27306 If the cursor is in a table looking at whitespace, the whitespace is
27307 overwritten, and the table is not marked as requiring realignment."
27308 (interactive "p")
27309 (if (and (org-table-p)
27310 (progn
27311 ;; check if we blank the field, and if that triggers align
27312 (and org-table-auto-blank-field
27313 (member last-command
27314 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
27315 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
27316 ;; got extra space, this field does not determine column width
27317 (let (org-table-may-need-update) (org-table-blank-field))
27318 ;; no extra space, this field may determine column width
27319 (org-table-blank-field)))
27321 (eq N 1)
27322 (looking-at "[^|\n]* |"))
27323 (let (org-table-may-need-update)
27324 (goto-char (1- (match-end 0)))
27325 (delete-backward-char 1)
27326 (goto-char (match-beginning 0))
27327 (self-insert-command N))
27328 (setq org-table-may-need-update t)
27329 (self-insert-command N)
27330 (org-fix-tags-on-the-fly)))
27332 (defun org-fix-tags-on-the-fly ()
27333 (when (and (equal (char-after (point-at-bol)) ?*)
27334 (org-on-heading-p))
27335 (org-align-tags-here org-tags-column)))
27337 (defun org-delete-backward-char (N)
27338 "Like `delete-backward-char', insert whitespace at field end in tables.
27339 When deleting backwards, in tables this function will insert whitespace in
27340 front of the next \"|\" separator, to keep the table aligned. The table will
27341 still be marked for re-alignment if the field did fill the entire column,
27342 because, in this case the deletion might narrow the column."
27343 (interactive "p")
27344 (if (and (org-table-p)
27345 (eq N 1)
27346 (string-match "|" (buffer-substring (point-at-bol) (point)))
27347 (looking-at ".*?|"))
27348 (let ((pos (point))
27349 (noalign (looking-at "[^|\n\r]* |"))
27350 (c org-table-may-need-update))
27351 (backward-delete-char N)
27352 (skip-chars-forward "^|")
27353 (insert " ")
27354 (goto-char (1- pos))
27355 ;; noalign: if there were two spaces at the end, this field
27356 ;; does not determine the width of the column.
27357 (if noalign (setq org-table-may-need-update c)))
27358 (backward-delete-char N)
27359 (org-fix-tags-on-the-fly)))
27361 (defun org-delete-char (N)
27362 "Like `delete-char', but insert whitespace at field end in tables.
27363 When deleting characters, in tables this function will insert whitespace in
27364 front of the next \"|\" separator, to keep the table aligned. The table will
27365 still be marked for re-alignment if the field did fill the entire column,
27366 because, in this case the deletion might narrow the column."
27367 (interactive "p")
27368 (if (and (org-table-p)
27369 (not (bolp))
27370 (not (= (char-after) ?|))
27371 (eq N 1))
27372 (if (looking-at ".*?|")
27373 (let ((pos (point))
27374 (noalign (looking-at "[^|\n\r]* |"))
27375 (c org-table-may-need-update))
27376 (replace-match (concat
27377 (substring (match-string 0) 1 -1)
27378 " |"))
27379 (goto-char pos)
27380 ;; noalign: if there were two spaces at the end, this field
27381 ;; does not determine the width of the column.
27382 (if noalign (setq org-table-may-need-update c)))
27383 (delete-char N))
27384 (delete-char N)
27385 (org-fix-tags-on-the-fly)))
27387 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
27388 (put 'org-self-insert-command 'delete-selection t)
27389 (put 'orgtbl-self-insert-command 'delete-selection t)
27390 (put 'org-delete-char 'delete-selection 'supersede)
27391 (put 'org-delete-backward-char 'delete-selection 'supersede)
27393 ;; Make `flyspell-mode' delay after some commands
27394 (put 'org-self-insert-command 'flyspell-delayed t)
27395 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
27396 (put 'org-delete-char 'flyspell-delayed t)
27397 (put 'org-delete-backward-char 'flyspell-delayed t)
27399 ;; Make pabbrev-mode expand after org-mode commands
27400 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
27401 (put 'orgybl-self-insert-command 'pabbrev-expand-after-command t)
27403 ;; How to do this: Measure non-white length of current string
27404 ;; If equal to column width, we should realign.
27406 (defun org-remap (map &rest commands)
27407 "In MAP, remap the functions given in COMMANDS.
27408 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
27409 (let (new old)
27410 (while commands
27411 (setq old (pop commands) new (pop commands))
27412 (if (fboundp 'command-remapping)
27413 (org-defkey map (vector 'remap old) new)
27414 (substitute-key-definition old new map global-map)))))
27416 (when (eq org-enable-table-editor 'optimized)
27417 ;; If the user wants maximum table support, we need to hijack
27418 ;; some standard editing functions
27419 (org-remap org-mode-map
27420 'self-insert-command 'org-self-insert-command
27421 'delete-char 'org-delete-char
27422 'delete-backward-char 'org-delete-backward-char)
27423 (org-defkey org-mode-map "|" 'org-force-self-insert))
27425 (defun org-shiftcursor-error ()
27426 "Throw an error because Shift-Cursor command was applied in wrong context."
27427 (error "This command is active in special context like tables, headlines or timestamps"))
27429 (defun org-shifttab (&optional arg)
27430 "Global visibility cycling or move to previous table field.
27431 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
27432 on context.
27433 See the individual commands for more information."
27434 (interactive "P")
27435 (cond
27436 ((org-at-table-p) (call-interactively 'org-table-previous-field))
27437 (arg (message "Content view to level: ")
27438 (org-content (prefix-numeric-value arg))
27439 (setq org-cycle-global-status 'overview))
27440 (t (call-interactively 'org-global-cycle))))
27442 (defun org-shiftmetaleft ()
27443 "Promote subtree or delete table column.
27444 Calls `org-promote-subtree', `org-outdent-item',
27445 or `org-table-delete-column', depending on context.
27446 See the individual commands for more information."
27447 (interactive)
27448 (cond
27449 ((org-at-table-p) (call-interactively 'org-table-delete-column))
27450 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
27451 ((org-at-item-p) (call-interactively 'org-outdent-item))
27452 (t (org-shiftcursor-error))))
27454 (defun org-shiftmetaright ()
27455 "Demote subtree or insert table column.
27456 Calls `org-demote-subtree', `org-indent-item',
27457 or `org-table-insert-column', depending on context.
27458 See the individual commands for more information."
27459 (interactive)
27460 (cond
27461 ((org-at-table-p) (call-interactively 'org-table-insert-column))
27462 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
27463 ((org-at-item-p) (call-interactively 'org-indent-item))
27464 (t (org-shiftcursor-error))))
27466 (defun org-shiftmetaup (&optional arg)
27467 "Move subtree up or kill table row.
27468 Calls `org-move-subtree-up' or `org-table-kill-row' or
27469 `org-move-item-up' depending on context. See the individual commands
27470 for more information."
27471 (interactive "P")
27472 (cond
27473 ((org-at-table-p) (call-interactively 'org-table-kill-row))
27474 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
27475 ((org-at-item-p) (call-interactively 'org-move-item-up))
27476 (t (org-shiftcursor-error))))
27477 (defun org-shiftmetadown (&optional arg)
27478 "Move subtree down or insert table row.
27479 Calls `org-move-subtree-down' or `org-table-insert-row' or
27480 `org-move-item-down', depending on context. See the individual
27481 commands for more information."
27482 (interactive "P")
27483 (cond
27484 ((org-at-table-p) (call-interactively 'org-table-insert-row))
27485 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
27486 ((org-at-item-p) (call-interactively 'org-move-item-down))
27487 (t (org-shiftcursor-error))))
27489 (defun org-metaleft (&optional arg)
27490 "Promote heading or move table column to left.
27491 Calls `org-do-promote' or `org-table-move-column', depending on context.
27492 With no specific context, calls the Emacs default `backward-word'.
27493 See the individual commands for more information."
27494 (interactive "P")
27495 (cond
27496 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
27497 ((or (org-on-heading-p) (org-region-active-p))
27498 (call-interactively 'org-do-promote))
27499 ((org-at-item-p) (call-interactively 'org-outdent-item))
27500 (t (call-interactively 'backward-word))))
27502 (defun org-metaright (&optional arg)
27503 "Demote subtree or move table column to right.
27504 Calls `org-do-demote' or `org-table-move-column', depending on context.
27505 With no specific context, calls the Emacs default `forward-word'.
27506 See the individual commands for more information."
27507 (interactive "P")
27508 (cond
27509 ((org-at-table-p) (call-interactively 'org-table-move-column))
27510 ((or (org-on-heading-p) (org-region-active-p))
27511 (call-interactively 'org-do-demote))
27512 ((org-at-item-p) (call-interactively 'org-indent-item))
27513 (t (call-interactively 'forward-word))))
27515 (defun org-metaup (&optional arg)
27516 "Move subtree up or move table row up.
27517 Calls `org-move-subtree-up' or `org-table-move-row' or
27518 `org-move-item-up', depending on context. See the individual commands
27519 for more information."
27520 (interactive "P")
27521 (cond
27522 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
27523 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
27524 ((org-at-item-p) (call-interactively 'org-move-item-up))
27525 (t (transpose-lines 1) (beginning-of-line -1))))
27527 (defun org-metadown (&optional arg)
27528 "Move subtree down or move table row down.
27529 Calls `org-move-subtree-down' or `org-table-move-row' or
27530 `org-move-item-down', depending on context. See the individual
27531 commands for more information."
27532 (interactive "P")
27533 (cond
27534 ((org-at-table-p) (call-interactively 'org-table-move-row))
27535 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
27536 ((org-at-item-p) (call-interactively 'org-move-item-down))
27537 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
27539 (defun org-shiftup (&optional arg)
27540 "Increase item in timestamp or increase priority of current headline.
27541 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
27542 depending on context. See the individual commands for more information."
27543 (interactive "P")
27544 (cond
27545 ((org-at-timestamp-p t)
27546 (call-interactively (if org-edit-timestamp-down-means-later
27547 'org-timestamp-down 'org-timestamp-up)))
27548 ((org-on-heading-p) (call-interactively 'org-priority-up))
27549 ((org-at-item-p) (call-interactively 'org-previous-item))
27550 (t (call-interactively 'org-beginning-of-item) (beginning-of-line 1))))
27552 (defun org-shiftdown (&optional arg)
27553 "Decrease item in timestamp or decrease priority of current headline.
27554 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
27555 depending on context. See the individual commands for more information."
27556 (interactive "P")
27557 (cond
27558 ((org-at-timestamp-p t)
27559 (call-interactively (if org-edit-timestamp-down-means-later
27560 'org-timestamp-up 'org-timestamp-down)))
27561 ((org-on-heading-p) (call-interactively 'org-priority-down))
27562 (t (call-interactively 'org-next-item))))
27564 (defun org-shiftright ()
27565 "Next TODO keyword or timestamp one day later, depending on context."
27566 (interactive)
27567 (cond
27568 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
27569 ((org-on-heading-p) (org-call-with-arg 'org-todo 'right))
27570 ((org-at-item-p) (org-call-with-arg 'org-cycle-list-bullet nil))
27571 ((org-at-property-p) (call-interactively 'org-property-next-allowed-value))
27572 (t (org-shiftcursor-error))))
27574 (defun org-shiftleft ()
27575 "Previous TODO keyword or timestamp one day earlier, depending on context."
27576 (interactive)
27577 (cond
27578 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
27579 ((org-on-heading-p) (org-call-with-arg 'org-todo 'left))
27580 ((org-at-item-p) (org-call-with-arg 'org-cycle-list-bullet 'previous))
27581 ((org-at-property-p)
27582 (call-interactively 'org-property-previous-allowed-value))
27583 (t (org-shiftcursor-error))))
27585 (defun org-shiftcontrolright ()
27586 "Switch to next TODO set."
27587 (interactive)
27588 (cond
27589 ((org-on-heading-p) (org-call-with-arg 'org-todo 'nextset))
27590 (t (org-shiftcursor-error))))
27592 (defun org-shiftcontrolleft ()
27593 "Switch to previous TODO set."
27594 (interactive)
27595 (cond
27596 ((org-on-heading-p) (org-call-with-arg 'org-todo 'previousset))
27597 (t (org-shiftcursor-error))))
27599 (defun org-ctrl-c-ret ()
27600 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
27601 (interactive)
27602 (cond
27603 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
27604 (t (call-interactively 'org-insert-heading))))
27606 (defun org-copy-special ()
27607 "Copy region in table or copy current subtree.
27608 Calls `org-table-copy' or `org-copy-subtree', depending on context.
27609 See the individual commands for more information."
27610 (interactive)
27611 (call-interactively
27612 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
27614 (defun org-cut-special ()
27615 "Cut region in table or cut current subtree.
27616 Calls `org-table-copy' or `org-cut-subtree', depending on context.
27617 See the individual commands for more information."
27618 (interactive)
27619 (call-interactively
27620 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
27622 (defun org-paste-special (arg)
27623 "Paste rectangular region into table, or past subtree relative to level.
27624 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
27625 See the individual commands for more information."
27626 (interactive "P")
27627 (if (org-at-table-p)
27628 (org-table-paste-rectangle)
27629 (org-paste-subtree arg)))
27631 (defun org-ctrl-c-ctrl-c (&optional arg)
27632 "Set tags in headline, or update according to changed information at point.
27634 This command does many different things, depending on context:
27636 - If the cursor is in a headline, prompt for tags and insert them
27637 into the current line, aligned to `org-tags-column'. When called
27638 with prefix arg, realign all tags in the current buffer.
27640 - If the cursor is in one of the special #+KEYWORD lines, this
27641 triggers scanning the buffer for these lines and updating the
27642 information.
27644 - If the cursor is inside a table, realign the table. This command
27645 works even if the automatic table editor has been turned off.
27647 - If the cursor is on a #+TBLFM line, re-apply the formulas to
27648 the entire table.
27650 - If the cursor is a the beginning of a dynamic block, update it.
27652 - If the cursor is inside a table created by the table.el package,
27653 activate that table.
27655 - If the current buffer is a remember buffer, close note and file it.
27656 with a prefix argument, file it without further interaction to the default
27657 location.
27659 - If the cursor is on a <<<target>>>, update radio targets and corresponding
27660 links in this buffer.
27662 - If the cursor is on a numbered item in a plain list, renumber the
27663 ordered list.
27665 - If the cursor is on a checkbox, toggle it."
27666 (interactive "P")
27667 (let ((org-enable-table-editor t))
27668 (cond
27669 ((or org-clock-overlays
27670 org-occur-highlights
27671 org-latex-fragment-image-overlays)
27672 (org-remove-clock-overlays)
27673 (org-remove-occur-highlights)
27674 (org-remove-latex-fragment-image-overlays)
27675 (message "Temporary highlights/overlays removed from current buffer"))
27676 ((and (local-variable-p 'org-finish-function (current-buffer))
27677 (fboundp org-finish-function))
27678 (funcall org-finish-function))
27679 ((org-at-property-p)
27680 (call-interactively 'org-property-action))
27681 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
27682 ((org-on-heading-p) (call-interactively 'org-set-tags))
27683 ((org-at-table.el-p)
27684 (require 'table)
27685 (beginning-of-line 1)
27686 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
27687 (call-interactively 'table-recognize-table))
27688 ((org-at-table-p)
27689 (org-table-maybe-eval-formula)
27690 (if arg
27691 (call-interactively 'org-table-recalculate)
27692 (org-table-maybe-recalculate-line))
27693 (call-interactively 'org-table-align))
27694 ((org-at-item-checkbox-p)
27695 (call-interactively 'org-toggle-checkbox))
27696 ((org-at-item-p)
27697 (call-interactively 'org-maybe-renumber-ordered-list))
27698 ((save-excursion (beginning-of-line 1) (looking-at "#\\+BEGIN:"))
27699 ;; Dynamic block
27700 (beginning-of-line 1)
27701 (org-update-dblock))
27702 ((save-excursion (beginning-of-line 1) (looking-at "#\\+\\([A-Z]+\\)"))
27703 (cond
27704 ((equal (match-string 1) "TBLFM")
27705 ;; Recalculate the table before this line
27706 (save-excursion
27707 (beginning-of-line 1)
27708 (skip-chars-backward " \r\n\t")
27709 (if (org-at-table-p)
27710 (org-call-with-arg 'org-table-recalculate t))))
27712 (call-interactively 'org-mode-restart))))
27713 (t (error "C-c C-c can do nothing useful at this location.")))))
27715 (defun org-mode-restart ()
27716 "Restart Org-mode, to scan again for special lines.
27717 Also updates the keyword regular expressions."
27718 (interactive)
27719 (let ((org-inhibit-startup t)) (org-mode))
27720 (message "Org-mode restarted to refresh keyword and special line setup"))
27722 (defun org-kill-note-or-show-branches ()
27723 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
27724 (interactive)
27725 (if (not org-finish-function)
27726 (call-interactively 'show-branches)
27727 (let ((org-note-abort t))
27728 (funcall org-finish-function))))
27730 (defun org-return (&optional indent)
27731 "Goto next table row or insert a newline.
27732 Calls `org-table-next-row' or `newline', depending on context.
27733 See the individual commands for more information."
27734 (interactive)
27735 (cond
27736 ((bobp) (if indent (newline-and-indent) (newline)))
27737 ((and (org-at-heading-p)
27738 (looking-at
27739 (org-re "\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$")))
27740 (org-show-entry)
27741 (end-of-line 1)
27742 (newline))
27743 ((org-at-table-p)
27744 (org-table-justify-field-maybe)
27745 (call-interactively 'org-table-next-row))
27746 (t (if indent (newline-and-indent) (newline)))))
27748 (defun org-return-indent ()
27749 "Goto next table row or insert a newline and indent.
27750 Calls `org-table-next-row' or `newline-and-indent', depending on
27751 context. See the individual commands for more information."
27752 (interactive)
27753 (org-return t))
27755 (defun org-ctrl-c-star ()
27756 "Compute table, or change heading status of lines.
27757 Calls `org-table-recalculate' or `org-toggle-region-headlines',
27758 depending on context. This will also turn a plain list item or a normal
27759 line into a subheading."
27760 (interactive)
27761 (cond
27762 ((org-at-table-p)
27763 (call-interactively 'org-table-recalculate))
27764 ((org-region-active-p)
27765 ;; Convert all lines in region to list items
27766 (call-interactively 'org-toggle-region-headings))
27767 ((org-on-heading-p)
27768 (org-toggle-region-headings (point-at-bol)
27769 (min (1+ (point-at-eol)) (point-max))))
27770 ((org-at-item-p)
27771 ;; Convert to heading
27772 (let ((level (save-match-data
27773 (save-excursion
27774 (condition-case nil
27775 (progn
27776 (org-back-to-heading t)
27777 (funcall outline-level))
27778 (error 0))))))
27779 (replace-match
27780 (concat (make-string (org-get-valid-level level 1) ?*) " ") t t)))
27781 (t (org-toggle-region-headings (point-at-bol)
27782 (min (1+ (point-at-eol)) (point-max))))))
27784 (defun org-ctrl-c-minus ()
27785 "Insert separator line in table or modify bullet status of line.
27786 Also turns a plain line or a region of lines into list items.
27787 Calls `org-table-insert-hline', `org-toggle-region-items', or
27788 `org-cycle-list-bullet', depending on context."
27789 (interactive)
27790 (cond
27791 ((org-at-table-p)
27792 (call-interactively 'org-table-insert-hline))
27793 ((org-on-heading-p)
27794 ;; Convert to item
27795 (save-excursion
27796 (beginning-of-line 1)
27797 (if (looking-at "\\*+ ")
27798 (replace-match (concat (make-string (- (match-end 0) (point) 1) ?\ ) "- ")))))
27799 ((org-region-active-p)
27800 ;; Convert all lines in region to list items
27801 (call-interactively 'org-toggle-region-items))
27802 ((org-in-item-p)
27803 (call-interactively 'org-cycle-list-bullet))
27804 (t (org-toggle-region-items (point-at-bol)
27805 (min (1+ (point-at-eol)) (point-max))))))
27807 (defun org-toggle-region-items (beg end)
27808 "Convert all lines in region to list items.
27809 If the first line is already an item, convert all list items in the region
27810 to normal lines."
27811 (interactive "r")
27812 (let (l2 l)
27813 (save-excursion
27814 (goto-char end)
27815 (setq l2 (org-current-line))
27816 (goto-char beg)
27817 (beginning-of-line 1)
27818 (setq l (1- (org-current-line)))
27819 (if (org-at-item-p)
27820 ;; We already have items, de-itemize
27821 (while (< (setq l (1+ l)) l2)
27822 (when (org-at-item-p)
27823 (goto-char (match-beginning 2))
27824 (delete-region (match-beginning 2) (match-end 2))
27825 (and (looking-at "[ \t]+") (replace-match "")))
27826 (beginning-of-line 2))
27827 (while (< (setq l (1+ l)) l2)
27828 (unless (org-at-item-p)
27829 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
27830 (replace-match "\\1- \\2")))
27831 (beginning-of-line 2))))))
27833 (defun org-toggle-region-headings (beg end)
27834 "Convert all lines in region to list items.
27835 If the first line is already an item, convert all list items in the region
27836 to normal lines."
27837 (interactive "r")
27838 (let (l2 l)
27839 (save-excursion
27840 (goto-char end)
27841 (setq l2 (org-current-line))
27842 (goto-char beg)
27843 (beginning-of-line 1)
27844 (setq l (1- (org-current-line)))
27845 (if (org-on-heading-p)
27846 ;; We already have headlines, de-star them
27847 (while (< (setq l (1+ l)) l2)
27848 (when (org-on-heading-p t)
27849 (and (looking-at outline-regexp) (replace-match "")))
27850 (beginning-of-line 2))
27851 (let* ((stars (save-excursion
27852 (re-search-backward org-complex-heading-regexp nil t)
27853 (or (match-string 1) "*")))
27854 (add-stars (if org-odd-levels-only "**" "*"))
27855 (rpl (concat stars add-stars " \\2")))
27856 (while (< (setq l (1+ l)) l2)
27857 (unless (org-on-heading-p)
27858 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
27859 (replace-match rpl)))
27860 (beginning-of-line 2)))))))
27862 (defun org-meta-return (&optional arg)
27863 "Insert a new heading or wrap a region in a table.
27864 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
27865 See the individual commands for more information."
27866 (interactive "P")
27867 (cond
27868 ((org-at-table-p)
27869 (call-interactively 'org-table-wrap-region))
27870 (t (call-interactively 'org-insert-heading))))
27872 ;;; Menu entries
27874 ;; Define the Org-mode menus
27875 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
27876 '("Tbl"
27877 ["Align" org-ctrl-c-ctrl-c (org-at-table-p)]
27878 ["Next Field" org-cycle (org-at-table-p)]
27879 ["Previous Field" org-shifttab (org-at-table-p)]
27880 ["Next Row" org-return (org-at-table-p)]
27881 "--"
27882 ["Blank Field" org-table-blank-field (org-at-table-p)]
27883 ["Edit Field" org-table-edit-field (org-at-table-p)]
27884 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
27885 "--"
27886 ("Column"
27887 ["Move Column Left" org-metaleft (org-at-table-p)]
27888 ["Move Column Right" org-metaright (org-at-table-p)]
27889 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
27890 ["Insert Column" org-shiftmetaright (org-at-table-p)])
27891 ("Row"
27892 ["Move Row Up" org-metaup (org-at-table-p)]
27893 ["Move Row Down" org-metadown (org-at-table-p)]
27894 ["Delete Row" org-shiftmetaup (org-at-table-p)]
27895 ["Insert Row" org-shiftmetadown (org-at-table-p)]
27896 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
27897 "--"
27898 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
27899 ("Rectangle"
27900 ["Copy Rectangle" org-copy-special (org-at-table-p)]
27901 ["Cut Rectangle" org-cut-special (org-at-table-p)]
27902 ["Paste Rectangle" org-paste-special (org-at-table-p)]
27903 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
27904 "--"
27905 ("Calculate"
27906 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
27907 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
27908 ["Edit Formulas" org-table-edit-formulas (org-at-table-p)]
27909 "--"
27910 ["Recalculate line" org-table-recalculate (org-at-table-p)]
27911 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
27912 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
27913 "--"
27914 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
27915 "--"
27916 ["Sum Column/Rectangle" org-table-sum
27917 (or (org-at-table-p) (org-region-active-p))]
27918 ["Which Column?" org-table-current-column (org-at-table-p)])
27919 ["Debug Formulas"
27920 org-table-toggle-formula-debugger
27921 :style toggle :selected org-table-formula-debug]
27922 ["Show Col/Row Numbers"
27923 org-table-toggle-coordinate-overlays
27924 :style toggle :selected org-table-overlay-coordinates]
27925 "--"
27926 ["Create" org-table-create (and (not (org-at-table-p))
27927 org-enable-table-editor)]
27928 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
27929 ["Import from File" org-table-import (not (org-at-table-p))]
27930 ["Export to File" org-table-export (org-at-table-p)]
27931 "--"
27932 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
27934 (easy-menu-define org-org-menu org-mode-map "Org menu"
27935 '("Org"
27936 ("Show/Hide"
27937 ["Cycle Visibility" org-cycle (or (bobp) (outline-on-heading-p))]
27938 ["Cycle Global Visibility" org-shifttab (not (org-at-table-p))]
27939 ["Sparse Tree" org-occur t]
27940 ["Reveal Context" org-reveal t]
27941 ["Show All" show-all t]
27942 "--"
27943 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
27944 "--"
27945 ["New Heading" org-insert-heading t]
27946 ("Navigate Headings"
27947 ["Up" outline-up-heading t]
27948 ["Next" outline-next-visible-heading t]
27949 ["Previous" outline-previous-visible-heading t]
27950 ["Next Same Level" outline-forward-same-level t]
27951 ["Previous Same Level" outline-backward-same-level t]
27952 "--"
27953 ["Jump" org-goto t])
27954 ("Edit Structure"
27955 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
27956 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
27957 "--"
27958 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
27959 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
27960 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
27961 "--"
27962 ["Promote Heading" org-metaleft (not (org-at-table-p))]
27963 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
27964 ["Demote Heading" org-metaright (not (org-at-table-p))]
27965 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
27966 "--"
27967 ["Sort Region/Children" org-sort (not (org-at-table-p))]
27968 "--"
27969 ["Convert to odd levels" org-convert-to-odd-levels t]
27970 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
27971 ("Editing"
27972 ["Emphasis..." org-emphasize t])
27973 ("Archive"
27974 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
27975 ; ["Check and Tag Children" (org-toggle-archive-tag (4))
27976 ; :active t :keys "C-u C-c C-x C-a"]
27977 ["Sparse trees open ARCHIVE trees"
27978 (setq org-sparse-tree-open-archived-trees
27979 (not org-sparse-tree-open-archived-trees))
27980 :style toggle :selected org-sparse-tree-open-archived-trees]
27981 ["Cycling opens ARCHIVE trees"
27982 (setq org-cycle-open-archived-trees (not org-cycle-open-archived-trees))
27983 :style toggle :selected org-cycle-open-archived-trees]
27984 ["Agenda includes ARCHIVE trees"
27985 (setq org-agenda-skip-archived-trees (not org-agenda-skip-archived-trees))
27986 :style toggle :selected (not org-agenda-skip-archived-trees)]
27987 "--"
27988 ["Move Subtree to Archive" org-advertized-archive-subtree t]
27989 ; ["Check and Move Children" (org-archive-subtree '(4))
27990 ; :active t :keys "C-u C-c C-x C-s"]
27992 "--"
27993 ("TODO Lists"
27994 ["TODO/DONE/-" org-todo t]
27995 ("Select keyword"
27996 ["Next keyword" org-shiftright (org-on-heading-p)]
27997 ["Previous keyword" org-shiftleft (org-on-heading-p)]
27998 ["Complete Keyword" org-complete (assq :todo-keyword (org-context))]
27999 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))]
28000 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))])
28001 ["Show TODO Tree" org-show-todo-tree t]
28002 ["Global TODO list" org-todo-list t]
28003 "--"
28004 ["Set Priority" org-priority t]
28005 ["Priority Up" org-shiftup t]
28006 ["Priority Down" org-shiftdown t])
28007 ("TAGS and Properties"
28008 ["Set Tags" 'org-ctrl-c-ctrl-c (org-at-heading-p)]
28009 ["Change tag in region" 'org-change-tag-in-region (org-region-active-p)]
28010 "--"
28011 ["Set property" 'org-set-property t]
28012 ["Column view of properties" org-columns t]
28013 ["Insert Column View DBlock" org-insert-columns-dblock t])
28014 ("Dates and Scheduling"
28015 ["Timestamp" org-time-stamp t]
28016 ["Timestamp (inactive)" org-time-stamp-inactive t]
28017 ("Change Date"
28018 ["1 Day Later" org-shiftright t]
28019 ["1 Day Earlier" org-shiftleft t]
28020 ["1 ... Later" org-shiftup t]
28021 ["1 ... Earlier" org-shiftdown t])
28022 ["Compute Time Range" org-evaluate-time-range t]
28023 ["Schedule Item" org-schedule t]
28024 ["Deadline" org-deadline t]
28025 "--"
28026 ["Custom time format" org-toggle-time-stamp-overlays
28027 :style radio :selected org-display-custom-times]
28028 "--"
28029 ["Goto Calendar" org-goto-calendar t]
28030 ["Date from Calendar" org-date-from-calendar t])
28031 ("Logging work"
28032 ["Clock in" org-clock-in t]
28033 ["Clock out" org-clock-out t]
28034 ["Clock cancel" org-clock-cancel t]
28035 ["Goto running clock" org-clock-goto t]
28036 ["Display times" org-clock-display t]
28037 ["Create clock table" org-clock-report t]
28038 "--"
28039 ["Record DONE time"
28040 (progn (setq org-log-done (not org-log-done))
28041 (message "Switching to %s will %s record a timestamp"
28042 (car org-done-keywords)
28043 (if org-log-done "automatically" "not")))
28044 :style toggle :selected org-log-done])
28045 "--"
28046 ["Agenda Command..." org-agenda t]
28047 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
28048 ("File List for Agenda")
28049 ("Special views current file"
28050 ["TODO Tree" org-show-todo-tree t]
28051 ["Check Deadlines" org-check-deadlines t]
28052 ["Timeline" org-timeline t]
28053 ["Tags Tree" org-tags-sparse-tree t])
28054 "--"
28055 ("Hyperlinks"
28056 ["Store Link (Global)" org-store-link t]
28057 ["Insert Link" org-insert-link t]
28058 ["Follow Link" org-open-at-point t]
28059 "--"
28060 ["Next link" org-next-link t]
28061 ["Previous link" org-previous-link t]
28062 "--"
28063 ["Descriptive Links"
28064 (progn (org-add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
28065 :style radio :selected (member '(org-link) buffer-invisibility-spec)]
28066 ["Literal Links"
28067 (progn
28068 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
28069 :style radio :selected (not (member '(org-link) buffer-invisibility-spec))])
28070 "--"
28071 ["Export/Publish..." org-export t]
28072 ("LaTeX"
28073 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
28074 :selected org-cdlatex-mode]
28075 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
28076 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
28077 ["Modify math symbol" org-cdlatex-math-modify
28078 (org-inside-LaTeX-fragment-p)]
28079 ["Export LaTeX fragments as images"
28080 (setq org-export-with-LaTeX-fragments (not org-export-with-LaTeX-fragments))
28081 :style toggle :selected org-export-with-LaTeX-fragments])
28082 "--"
28083 ("Documentation"
28084 ["Show Version" org-version t]
28085 ["Info Documentation" org-info t])
28086 ("Customize"
28087 ["Browse Org Group" org-customize t]
28088 "--"
28089 ["Expand This Menu" org-create-customize-menu
28090 (fboundp 'customize-menu-create)])
28091 "--"
28092 ["Refresh setup" org-mode-restart t]
28095 (defun org-info (&optional node)
28096 "Read documentation for Org-mode in the info system.
28097 With optional NODE, go directly to that node."
28098 (interactive)
28099 (info (format "(org)%s" (or node ""))))
28101 (defun org-install-agenda-files-menu ()
28102 (let ((bl (buffer-list)))
28103 (save-excursion
28104 (while bl
28105 (set-buffer (pop bl))
28106 (if (org-mode-p) (setq bl nil)))
28107 (when (org-mode-p)
28108 (easy-menu-change
28109 '("Org") "File List for Agenda"
28110 (append
28111 (list
28112 ["Edit File List" (org-edit-agenda-file-list) t]
28113 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
28114 ["Remove Current File from List" org-remove-file t]
28115 ["Cycle through agenda files" org-cycle-agenda-files t]
28116 ["Occur in all agenda files" org-occur-in-agenda-files t]
28117 "--")
28118 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
28120 ;;;; Documentation
28122 (defun org-customize ()
28123 "Call the customize function with org as argument."
28124 (interactive)
28125 (customize-browse 'org))
28127 (defun org-create-customize-menu ()
28128 "Create a full customization menu for Org-mode, insert it into the menu."
28129 (interactive)
28130 (if (fboundp 'customize-menu-create)
28131 (progn
28132 (easy-menu-change
28133 '("Org") "Customize"
28134 `(["Browse Org group" org-customize t]
28135 "--"
28136 ,(customize-menu-create 'org)
28137 ["Set" Custom-set t]
28138 ["Save" Custom-save t]
28139 ["Reset to Current" Custom-reset-current t]
28140 ["Reset to Saved" Custom-reset-saved t]
28141 ["Reset to Standard Settings" Custom-reset-standard t]))
28142 (message "\"Org\"-menu now contains full customization menu"))
28143 (error "Cannot expand menu (outdated version of cus-edit.el)")))
28145 ;;;; Miscellaneous stuff
28148 ;;; Generally useful functions
28150 (defun org-context ()
28151 "Return a list of contexts of the current cursor position.
28152 If several contexts apply, all are returned.
28153 Each context entry is a list with a symbol naming the context, and
28154 two positions indicating start and end of the context. Possible
28155 contexts are:
28157 :headline anywhere in a headline
28158 :headline-stars on the leading stars in a headline
28159 :todo-keyword on a TODO keyword (including DONE) in a headline
28160 :tags on the TAGS in a headline
28161 :priority on the priority cookie in a headline
28162 :item on the first line of a plain list item
28163 :item-bullet on the bullet/number of a plain list item
28164 :checkbox on the checkbox in a plain list item
28165 :table in an org-mode table
28166 :table-special on a special filed in a table
28167 :table-table in a table.el table
28168 :link on a hyperlink
28169 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
28170 :target on a <<target>>
28171 :radio-target on a <<<radio-target>>>
28172 :latex-fragment on a LaTeX fragment
28173 :latex-preview on a LaTeX fragment with overlayed preview image
28175 This function expects the position to be visible because it uses font-lock
28176 faces as a help to recognize the following contexts: :table-special, :link,
28177 and :keyword."
28178 (let* ((f (get-text-property (point) 'face))
28179 (faces (if (listp f) f (list f)))
28180 (p (point)) clist o)
28181 ;; First the large context
28182 (cond
28183 ((org-on-heading-p t)
28184 (push (list :headline (point-at-bol) (point-at-eol)) clist)
28185 (when (progn
28186 (beginning-of-line 1)
28187 (looking-at org-todo-line-tags-regexp))
28188 (push (org-point-in-group p 1 :headline-stars) clist)
28189 (push (org-point-in-group p 2 :todo-keyword) clist)
28190 (push (org-point-in-group p 4 :tags) clist))
28191 (goto-char p)
28192 (skip-chars-backward "^[\n\r \t") (or (eobp) (backward-char 1))
28193 (if (looking-at "\\[#[A-Z0-9]\\]")
28194 (push (org-point-in-group p 0 :priority) clist)))
28196 ((org-at-item-p)
28197 (push (org-point-in-group p 2 :item-bullet) clist)
28198 (push (list :item (point-at-bol)
28199 (save-excursion (org-end-of-item) (point)))
28200 clist)
28201 (and (org-at-item-checkbox-p)
28202 (push (org-point-in-group p 0 :checkbox) clist)))
28204 ((org-at-table-p)
28205 (push (list :table (org-table-begin) (org-table-end)) clist)
28206 (if (memq 'org-formula faces)
28207 (push (list :table-special
28208 (previous-single-property-change p 'face)
28209 (next-single-property-change p 'face)) clist)))
28210 ((org-at-table-p 'any)
28211 (push (list :table-table) clist)))
28212 (goto-char p)
28214 ;; Now the small context
28215 (cond
28216 ((org-at-timestamp-p)
28217 (push (org-point-in-group p 0 :timestamp) clist))
28218 ((memq 'org-link faces)
28219 (push (list :link
28220 (previous-single-property-change p 'face)
28221 (next-single-property-change p 'face)) clist))
28222 ((memq 'org-special-keyword faces)
28223 (push (list :keyword
28224 (previous-single-property-change p 'face)
28225 (next-single-property-change p 'face)) clist))
28226 ((org-on-target-p)
28227 (push (org-point-in-group p 0 :target) clist)
28228 (goto-char (1- (match-beginning 0)))
28229 (if (looking-at org-radio-target-regexp)
28230 (push (org-point-in-group p 0 :radio-target) clist))
28231 (goto-char p))
28232 ((setq o (car (delq nil
28233 (mapcar
28234 (lambda (x)
28235 (if (memq x org-latex-fragment-image-overlays) x))
28236 (org-overlays-at (point))))))
28237 (push (list :latex-fragment
28238 (org-overlay-start o) (org-overlay-end o)) clist)
28239 (push (list :latex-preview
28240 (org-overlay-start o) (org-overlay-end o)) clist))
28241 ((org-inside-LaTeX-fragment-p)
28242 ;; FIXME: positions wrong.
28243 (push (list :latex-fragment (point) (point)) clist)))
28245 (setq clist (nreverse (delq nil clist)))
28246 clist))
28248 ;; FIXME: Compare with at-regexp-p Do we need both?
28249 (defun org-in-regexp (re &optional nlines visually)
28250 "Check if point is inside a match of regexp.
28251 Normally only the current line is checked, but you can include NLINES extra
28252 lines both before and after point into the search.
28253 If VISUALLY is set, require that the cursor is not after the match but
28254 really on, so that the block visually is on the match."
28255 (catch 'exit
28256 (let ((pos (point))
28257 (eol (point-at-eol (+ 1 (or nlines 0))))
28258 (inc (if visually 1 0)))
28259 (save-excursion
28260 (beginning-of-line (- 1 (or nlines 0)))
28261 (while (re-search-forward re eol t)
28262 (if (and (<= (match-beginning 0) pos)
28263 (>= (+ inc (match-end 0)) pos))
28264 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
28266 (defun org-at-regexp-p (regexp)
28267 "Is point inside a match of REGEXP in the current line?"
28268 (catch 'exit
28269 (save-excursion
28270 (let ((pos (point)) (end (point-at-eol)))
28271 (beginning-of-line 1)
28272 (while (re-search-forward regexp end t)
28273 (if (and (<= (match-beginning 0) pos)
28274 (>= (match-end 0) pos))
28275 (throw 'exit t)))
28276 nil))))
28278 (defun org-occur-in-agenda-files (regexp &optional nlines)
28279 "Call `multi-occur' with buffers for all agenda files."
28280 (interactive "sOrg-files matching: \np")
28281 (let* ((files (org-agenda-files))
28282 (tnames (mapcar 'file-truename files))
28283 (extra org-agenda-text-search-extra-files)
28285 (while (setq f (pop extra))
28286 (unless (member (file-truename f) tnames)
28287 (add-to-list 'files f 'append)
28288 (add-to-list 'tnames (file-truename f) 'append)))
28289 (multi-occur
28290 (mapcar (lambda (x) (or (get-file-buffer x) (find-file-noselect x))) files)
28291 regexp)))
28293 (if (boundp 'occur-mode-find-occurrence-hook)
28294 ;; Emacs 23
28295 (add-hook 'occur-mode-find-occurrence-hook
28296 (lambda ()
28297 (when (org-mode-p)
28298 (org-reveal))))
28299 ;; Emacs 22
28300 (defadvice occur-mode-goto-occurrence
28301 (after org-occur-reveal activate)
28302 (and (org-mode-p) (org-reveal)))
28303 (defadvice occur-mode-goto-occurrence-other-window
28304 (after org-occur-reveal activate)
28305 (and (org-mode-p) (org-reveal)))
28306 (defadvice occur-mode-display-occurrence
28307 (after org-occur-reveal activate)
28308 (when (org-mode-p)
28309 (let ((pos (occur-mode-find-occurrence)))
28310 (with-current-buffer (marker-buffer pos)
28311 (save-excursion
28312 (goto-char pos)
28313 (org-reveal)))))))
28315 (defun org-uniquify (list)
28316 "Remove duplicate elements from LIST."
28317 (let (res)
28318 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
28319 res))
28321 (defun org-delete-all (elts list)
28322 "Remove all elements in ELTS from LIST."
28323 (while elts
28324 (setq list (delete (pop elts) list)))
28325 list)
28327 (defun org-back-over-empty-lines ()
28328 "Move backwards over witespace, to the beginning of the first empty line.
28329 Returns the number o empty lines passed."
28330 (let ((pos (point)))
28331 (skip-chars-backward " \t\n\r")
28332 (beginning-of-line 2)
28333 (goto-char (min (point) pos))
28334 (count-lines (point) pos)))
28336 (defun org-skip-whitespace ()
28337 (skip-chars-forward " \t\n\r"))
28339 (defun org-point-in-group (point group &optional context)
28340 "Check if POINT is in match-group GROUP.
28341 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
28342 match. If the match group does ot exist or point is not inside it,
28343 return nil."
28344 (and (match-beginning group)
28345 (>= point (match-beginning group))
28346 (<= point (match-end group))
28347 (if context
28348 (list context (match-beginning group) (match-end group))
28349 t)))
28351 (defun org-switch-to-buffer-other-window (&rest args)
28352 "Switch to buffer in a second window on the current frame.
28353 In particular, do not allow pop-up frames."
28354 (let (pop-up-frames special-display-buffer-names special-display-regexps
28355 special-display-function)
28356 (apply 'switch-to-buffer-other-window args)))
28358 (defun org-combine-plists (&rest plists)
28359 "Create a single property list from all plists in PLISTS.
28360 The process starts by copying the first list, and then setting properties
28361 from the other lists. Settings in the last list are the most significant
28362 ones and overrule settings in the other lists."
28363 (let ((rtn (copy-sequence (pop plists)))
28364 p v ls)
28365 (while plists
28366 (setq ls (pop plists))
28367 (while ls
28368 (setq p (pop ls) v (pop ls))
28369 (setq rtn (plist-put rtn p v))))
28370 rtn))
28372 (defun org-move-line-down (arg)
28373 "Move the current line down. With prefix argument, move it past ARG lines."
28374 (interactive "p")
28375 (let ((col (current-column))
28376 beg end pos)
28377 (beginning-of-line 1) (setq beg (point))
28378 (beginning-of-line 2) (setq end (point))
28379 (beginning-of-line (+ 1 arg))
28380 (setq pos (move-marker (make-marker) (point)))
28381 (insert (delete-and-extract-region beg end))
28382 (goto-char pos)
28383 (move-to-column col)))
28385 (defun org-move-line-up (arg)
28386 "Move the current line up. With prefix argument, move it past ARG lines."
28387 (interactive "p")
28388 (let ((col (current-column))
28389 beg end pos)
28390 (beginning-of-line 1) (setq beg (point))
28391 (beginning-of-line 2) (setq end (point))
28392 (beginning-of-line (- arg))
28393 (setq pos (move-marker (make-marker) (point)))
28394 (insert (delete-and-extract-region beg end))
28395 (goto-char pos)
28396 (move-to-column col)))
28398 (defun org-replace-escapes (string table)
28399 "Replace %-escapes in STRING with values in TABLE.
28400 TABLE is an association list with keys like \"%a\" and string values.
28401 The sequences in STRING may contain normal field width and padding information,
28402 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
28403 so values can contain further %-escapes if they are define later in TABLE."
28404 (let ((case-fold-search nil)
28405 e re rpl)
28406 (while (setq e (pop table))
28407 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
28408 (while (string-match re string)
28409 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
28410 (cdr e)))
28411 (setq string (replace-match rpl t t string))))
28412 string))
28415 (defun org-sublist (list start end)
28416 "Return a section of LIST, from START to END.
28417 Counting starts at 1."
28418 (let (rtn (c start))
28419 (setq list (nthcdr (1- start) list))
28420 (while (and list (<= c end))
28421 (push (pop list) rtn)
28422 (setq c (1+ c)))
28423 (nreverse rtn)))
28425 (defun org-find-base-buffer-visiting (file)
28426 "Like `find-buffer-visiting' but alway return the base buffer and
28427 not an indirect buffer"
28428 (let ((buf (find-buffer-visiting file)))
28429 (if buf
28430 (or (buffer-base-buffer buf) buf)
28431 nil)))
28433 (defun org-image-file-name-regexp ()
28434 "Return regexp matching the file names of images."
28435 (if (fboundp 'image-file-name-regexp)
28436 (image-file-name-regexp)
28437 (let ((image-file-name-extensions
28438 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
28439 "xbm" "xpm" "pbm" "pgm" "ppm")))
28440 (concat "\\."
28441 (regexp-opt (nconc (mapcar 'upcase
28442 image-file-name-extensions)
28443 image-file-name-extensions)
28445 "\\'"))))
28447 (defun org-file-image-p (file)
28448 "Return non-nil if FILE is an image."
28449 (save-match-data
28450 (string-match (org-image-file-name-regexp) file)))
28452 ;;; Paragraph filling stuff.
28453 ;; We want this to be just right, so use the full arsenal.
28455 (defun org-indent-line-function ()
28456 "Indent line like previous, but further if previous was headline or item."
28457 (interactive)
28458 (let* ((pos (point))
28459 (itemp (org-at-item-p))
28460 column bpos bcol tpos tcol bullet btype bullet-type)
28461 ;; Find the previous relevant line
28462 (beginning-of-line 1)
28463 (cond
28464 ((looking-at "#") (setq column 0))
28465 ((looking-at "\\*+ ") (setq column 0))
28467 (beginning-of-line 0)
28468 (while (and (not (bobp)) (looking-at "[ \t]*[\n:#|]"))
28469 (beginning-of-line 0))
28470 (cond
28471 ((looking-at "\\*+[ \t]+")
28472 (goto-char (match-end 0))
28473 (setq column (current-column)))
28474 ((org-in-item-p)
28475 (org-beginning-of-item)
28476 ; (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
28477 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*\\(\\[[- X]\\][ \t]*\\)?")
28478 (setq bpos (match-beginning 1) tpos (match-end 0)
28479 bcol (progn (goto-char bpos) (current-column))
28480 tcol (progn (goto-char tpos) (current-column))
28481 bullet (match-string 1)
28482 bullet-type (if (string-match "[0-9]" bullet) "n" bullet))
28483 (if (not itemp)
28484 (setq column tcol)
28485 (goto-char pos)
28486 (beginning-of-line 1)
28487 (if (looking-at "\\S-")
28488 (progn
28489 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
28490 (setq bullet (match-string 1)
28491 btype (if (string-match "[0-9]" bullet) "n" bullet))
28492 (setq column (if (equal btype bullet-type) bcol tcol)))
28493 (setq column (org-get-indentation)))))
28494 (t (setq column (org-get-indentation))))))
28495 (goto-char pos)
28496 (if (<= (current-column) (current-indentation))
28497 (indent-line-to column)
28498 (save-excursion (indent-line-to column)))
28499 (setq column (current-column))
28500 (beginning-of-line 1)
28501 (if (looking-at
28502 "\\([ \t]+\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
28503 (replace-match (concat "\\1" (format org-property-format
28504 (match-string 2) (match-string 3)))
28505 t nil))
28506 (move-to-column column)))
28508 (defun org-set-autofill-regexps ()
28509 (interactive)
28510 ;; In the paragraph separator we include headlines, because filling
28511 ;; text in a line directly attached to a headline would otherwise
28512 ;; fill the headline as well.
28513 (org-set-local 'comment-start-skip "^#+[ \t]*")
28514 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|]")
28515 ;; The paragraph starter includes hand-formatted lists.
28516 (org-set-local 'paragraph-start
28517 "\f\\|[ ]*$\\|\\*+ \\|\f\\|[ \t]*\\([-+*][ \t]+\\|[0-9]+[.)][ \t]+\\)\\|[ \t]*[:|]")
28518 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
28519 ;; But only if the user has not turned off tables or fixed-width regions
28520 (org-set-local
28521 'auto-fill-inhibit-regexp
28522 (concat "\\*+ \\|#\\+"
28523 "\\|[ \t]*" org-keyword-time-regexp
28524 (if (or org-enable-table-editor org-enable-fixed-width-editor)
28525 (concat
28526 "\\|[ \t]*["
28527 (if org-enable-table-editor "|" "")
28528 (if org-enable-fixed-width-editor ":" "")
28529 "]"))))
28530 ;; We use our own fill-paragraph function, to make sure that tables
28531 ;; and fixed-width regions are not wrapped. That function will pass
28532 ;; through to `fill-paragraph' when appropriate.
28533 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
28534 ; Adaptive filling: To get full control, first make sure that
28535 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
28536 (org-set-local 'adaptive-fill-regexp "\000")
28537 (org-set-local 'adaptive-fill-function
28538 'org-adaptive-fill-function)
28539 (org-set-local
28540 'align-mode-rules-list
28541 '((org-in-buffer-settings
28542 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
28543 (modes . '(org-mode))))))
28545 (defun org-fill-paragraph (&optional justify)
28546 "Re-align a table, pass through to fill-paragraph if no table."
28547 (let ((table-p (org-at-table-p))
28548 (table.el-p (org-at-table.el-p)))
28549 (cond ((and (equal (char-after (point-at-bol)) ?*)
28550 (save-excursion (goto-char (point-at-bol))
28551 (looking-at outline-regexp)))
28552 t) ; skip headlines
28553 (table.el-p t) ; skip table.el tables
28554 (table-p (org-table-align) t) ; align org-mode tables
28555 (t nil)))) ; call paragraph-fill
28557 ;; For reference, this is the default value of adaptive-fill-regexp
28558 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
28560 (defun org-adaptive-fill-function ()
28561 "Return a fill prefix for org-mode files.
28562 In particular, this makes sure hanging paragraphs for hand-formatted lists
28563 work correctly."
28564 (cond ((looking-at "#[ \t]+")
28565 (match-string 0))
28566 ((looking-at "[ \t]*\\([-*+] \\|[0-9]+[.)] \\)?")
28567 (save-excursion
28568 (goto-char (match-end 0))
28569 (make-string (current-column) ?\ )))
28570 (t nil)))
28572 ;;;; Functions extending outline functionality
28575 (defun org-beginning-of-line (&optional arg)
28576 "Go to the beginning of the current line. If that is invisible, continue
28577 to a visible line beginning. This makes the function of C-a more intuitive.
28578 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
28579 first attempt, and only move to after the tags when the cursor is already
28580 beyond the end of the headline."
28581 (interactive "P")
28582 (let ((pos (point)))
28583 (beginning-of-line 1)
28584 (if (bobp)
28586 (backward-char 1)
28587 (if (org-invisible-p)
28588 (while (and (not (bobp)) (org-invisible-p))
28589 (backward-char 1)
28590 (beginning-of-line 1))
28591 (forward-char 1)))
28592 (when org-special-ctrl-a/e
28593 (cond
28594 ((and (looking-at org-todo-line-regexp)
28595 (= (char-after (match-end 1)) ?\ ))
28596 (goto-char
28597 (if (eq org-special-ctrl-a/e t)
28598 (cond ((> pos (match-beginning 3)) (match-beginning 3))
28599 ((= pos (point)) (match-beginning 3))
28600 (t (point)))
28601 (cond ((> pos (point)) (point))
28602 ((not (eq last-command this-command)) (point))
28603 (t (match-beginning 3))))))
28604 ((org-at-item-p)
28605 (goto-char
28606 (if (eq org-special-ctrl-a/e t)
28607 (cond ((> pos (match-end 4)) (match-end 4))
28608 ((= pos (point)) (match-end 4))
28609 (t (point)))
28610 (cond ((> pos (point)) (point))
28611 ((not (eq last-command this-command)) (point))
28612 (t (match-end 4))))))))))
28614 (defun org-end-of-line (&optional arg)
28615 "Go to the end of the line.
28616 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
28617 first attempt, and only move to after the tags when the cursor is already
28618 beyond the end of the headline."
28619 (interactive "P")
28620 (if (or (not org-special-ctrl-a/e)
28621 (not (org-on-heading-p)))
28622 (end-of-line arg)
28623 (let ((pos (point)))
28624 (beginning-of-line 1)
28625 (if (looking-at (org-re ".*?\\([ \t]*\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
28626 (if (eq org-special-ctrl-a/e t)
28627 (if (or (< pos (match-beginning 1))
28628 (= pos (match-end 0)))
28629 (goto-char (match-beginning 1))
28630 (goto-char (match-end 0)))
28631 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
28632 (goto-char (match-end 0))
28633 (goto-char (match-beginning 1))))
28634 (end-of-line arg)))))
28636 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
28637 (define-key org-mode-map "\C-e" 'org-end-of-line)
28639 (defun org-kill-line (&optional arg)
28640 "Kill line, to tags or end of line."
28641 (interactive "P")
28642 (cond
28643 ((or (not org-special-ctrl-k)
28644 (bolp)
28645 (not (org-on-heading-p)))
28646 (call-interactively 'kill-line))
28647 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$"))
28648 (kill-region (point) (match-beginning 1))
28649 (org-set-tags nil t))
28650 (t (kill-region (point) (point-at-eol)))))
28652 (define-key org-mode-map "\C-k" 'org-kill-line)
28654 (defun org-invisible-p ()
28655 "Check if point is at a character currently not visible."
28656 ;; Early versions of noutline don't have `outline-invisible-p'.
28657 (if (fboundp 'outline-invisible-p)
28658 (outline-invisible-p)
28659 (get-char-property (point) 'invisible)))
28661 (defun org-invisible-p2 ()
28662 "Check if point is at a character currently not visible."
28663 (save-excursion
28664 (if (and (eolp) (not (bobp))) (backward-char 1))
28665 ;; Early versions of noutline don't have `outline-invisible-p'.
28666 (if (fboundp 'outline-invisible-p)
28667 (outline-invisible-p)
28668 (get-char-property (point) 'invisible))))
28670 (defalias 'org-back-to-heading 'outline-back-to-heading)
28671 (defalias 'org-on-heading-p 'outline-on-heading-p)
28672 (defalias 'org-at-heading-p 'outline-on-heading-p)
28673 (defun org-at-heading-or-item-p ()
28674 (or (org-on-heading-p) (org-at-item-p)))
28676 (defun org-on-target-p ()
28677 (or (org-in-regexp org-radio-target-regexp)
28678 (org-in-regexp org-target-regexp)))
28680 (defun org-up-heading-all (arg)
28681 "Move to the heading line of which the present line is a subheading.
28682 This function considers both visible and invisible heading lines.
28683 With argument, move up ARG levels."
28684 (if (fboundp 'outline-up-heading-all)
28685 (outline-up-heading-all arg) ; emacs 21 version of outline.el
28686 (outline-up-heading arg t))) ; emacs 22 version of outline.el
28688 (defun org-up-heading-safe ()
28689 "Move to the heading line of which the present line is a subheading.
28690 This version will not throw an error. It will return the level of the
28691 headline found, or nil if no higher level is found."
28692 (let ((pos (point)) start-level level
28693 (re (concat "^" outline-regexp)))
28694 (catch 'exit
28695 (outline-back-to-heading t)
28696 (setq start-level (funcall outline-level))
28697 (if (equal start-level 1) (throw 'exit nil))
28698 (while (re-search-backward re nil t)
28699 (setq level (funcall outline-level))
28700 (if (< level start-level) (throw 'exit level)))
28701 nil)))
28703 (defun org-first-sibling-p ()
28704 "Is this heading the first child of its parents?"
28705 (interactive)
28706 (let ((re (concat "^" outline-regexp))
28707 level l)
28708 (unless (org-at-heading-p t)
28709 (error "Not at a heading"))
28710 (setq level (funcall outline-level))
28711 (save-excursion
28712 (if (not (re-search-backward re nil t))
28714 (setq l (funcall outline-level))
28715 (< l level)))))
28717 (defun org-goto-sibling (&optional previous)
28718 "Goto the next sibling, even if it is invisible.
28719 When PREVIOUS is set, go to the previous sibling instead. Returns t
28720 when a sibling was found. When none is found, return nil and don't
28721 move point."
28722 (let ((fun (if previous 're-search-backward 're-search-forward))
28723 (pos (point))
28724 (re (concat "^" outline-regexp))
28725 level l)
28726 (when (condition-case nil (org-back-to-heading t) (error nil))
28727 (setq level (funcall outline-level))
28728 (catch 'exit
28729 (or previous (forward-char 1))
28730 (while (funcall fun re nil t)
28731 (setq l (funcall outline-level))
28732 (when (< l level) (goto-char pos) (throw 'exit nil))
28733 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
28734 (goto-char pos)
28735 nil))))
28737 (defun org-show-siblings ()
28738 "Show all siblings of the current headline."
28739 (save-excursion
28740 (while (org-goto-sibling) (org-flag-heading nil)))
28741 (save-excursion
28742 (while (org-goto-sibling 'previous)
28743 (org-flag-heading nil))))
28745 (defun org-show-hidden-entry ()
28746 "Show an entry where even the heading is hidden."
28747 (save-excursion
28748 (org-show-entry)))
28750 (defun org-flag-heading (flag &optional entry)
28751 "Flag the current heading. FLAG non-nil means make invisible.
28752 When ENTRY is non-nil, show the entire entry."
28753 (save-excursion
28754 (org-back-to-heading t)
28755 ;; Check if we should show the entire entry
28756 (if entry
28757 (progn
28758 (org-show-entry)
28759 (save-excursion
28760 (and (outline-next-heading)
28761 (org-flag-heading nil))))
28762 (outline-flag-region (max (point-min) (1- (point)))
28763 (save-excursion (outline-end-of-heading) (point))
28764 flag))))
28766 (defun org-end-of-subtree (&optional invisible-OK to-heading)
28767 ;; This is an exact copy of the original function, but it uses
28768 ;; `org-back-to-heading', to make it work also in invisible
28769 ;; trees. And is uses an invisible-OK argument.
28770 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
28771 (org-back-to-heading invisible-OK)
28772 (let ((first t)
28773 (level (funcall outline-level)))
28774 (while (and (not (eobp))
28775 (or first (> (funcall outline-level) level)))
28776 (setq first nil)
28777 (outline-next-heading))
28778 (unless to-heading
28779 (if (memq (preceding-char) '(?\n ?\^M))
28780 (progn
28781 ;; Go to end of line before heading
28782 (forward-char -1)
28783 (if (memq (preceding-char) '(?\n ?\^M))
28784 ;; leave blank line before heading
28785 (forward-char -1))))))
28786 (point))
28788 (defun org-show-subtree ()
28789 "Show everything after this heading at deeper levels."
28790 (outline-flag-region
28791 (point)
28792 (save-excursion
28793 (outline-end-of-subtree) (outline-next-heading) (point))
28794 nil))
28796 (defun org-show-entry ()
28797 "Show the body directly following this heading.
28798 Show the heading too, if it is currently invisible."
28799 (interactive)
28800 (save-excursion
28801 (condition-case nil
28802 (progn
28803 (org-back-to-heading t)
28804 (outline-flag-region
28805 (max (point-min) (1- (point)))
28806 (save-excursion
28807 (re-search-forward
28808 (concat "[\r\n]\\(" outline-regexp "\\)") nil 'move)
28809 (or (match-beginning 1) (point-max)))
28810 nil))
28811 (error nil))))
28813 (defun org-make-options-regexp (kwds)
28814 "Make a regular expression for keyword lines."
28815 (concat
28817 "#?[ \t]*\\+\\("
28818 (mapconcat 'regexp-quote kwds "\\|")
28819 "\\):[ \t]*"
28820 "\\(.+\\)"))
28822 ;; Make isearch reveal the necessary context
28823 (defun org-isearch-end ()
28824 "Reveal context after isearch exits."
28825 (when isearch-success ; only if search was successful
28826 (if (featurep 'xemacs)
28827 ;; Under XEmacs, the hook is run in the correct place,
28828 ;; we directly show the context.
28829 (org-show-context 'isearch)
28830 ;; In Emacs the hook runs *before* restoring the overlays.
28831 ;; So we have to use a one-time post-command-hook to do this.
28832 ;; (Emacs 22 has a special variable, see function `org-mode')
28833 (unless (and (boundp 'isearch-mode-end-hook-quit)
28834 isearch-mode-end-hook-quit)
28835 ;; Only when the isearch was not quitted.
28836 (org-add-hook 'post-command-hook 'org-isearch-post-command
28837 'append 'local)))))
28839 (defun org-isearch-post-command ()
28840 "Remove self from hook, and show context."
28841 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
28842 (org-show-context 'isearch))
28845 ;;;; Integration with and fixes for other packages
28847 ;;; Imenu support
28849 (defvar org-imenu-markers nil
28850 "All markers currently used by Imenu.")
28851 (make-variable-buffer-local 'org-imenu-markers)
28853 (defun org-imenu-new-marker (&optional pos)
28854 "Return a new marker for use by Imenu, and remember the marker."
28855 (let ((m (make-marker)))
28856 (move-marker m (or pos (point)))
28857 (push m org-imenu-markers)
28860 (defun org-imenu-get-tree ()
28861 "Produce the index for Imenu."
28862 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
28863 (setq org-imenu-markers nil)
28864 (let* ((n org-imenu-depth)
28865 (re (concat "^" outline-regexp))
28866 (subs (make-vector (1+ n) nil))
28867 (last-level 0)
28868 m tree level head)
28869 (save-excursion
28870 (save-restriction
28871 (widen)
28872 (goto-char (point-max))
28873 (while (re-search-backward re nil t)
28874 (setq level (org-reduced-level (funcall outline-level)))
28875 (when (<= level n)
28876 (looking-at org-complex-heading-regexp)
28877 (setq head (org-match-string-no-properties 4)
28878 m (org-imenu-new-marker))
28879 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
28880 (if (>= level last-level)
28881 (push (cons head m) (aref subs level))
28882 (push (cons head (aref subs (1+ level))) (aref subs level))
28883 (loop for i from (1+ level) to n do (aset subs i nil)))
28884 (setq last-level level)))))
28885 (aref subs 1)))
28887 (eval-after-load "imenu"
28888 '(progn
28889 (add-hook 'imenu-after-jump-hook
28890 (lambda () (org-show-context 'org-goto)))))
28892 ;; Speedbar support
28894 (defun org-speedbar-set-agenda-restriction ()
28895 "Restrict future agenda commands to the location at point in speedbar.
28896 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
28897 (interactive)
28898 (let (p m tp np dir txt w)
28899 (cond
28900 ((setq p (text-property-any (point-at-bol) (point-at-eol)
28901 'org-imenu t))
28902 (setq m (get-text-property p 'org-imenu-marker))
28903 (save-excursion
28904 (save-restriction
28905 (set-buffer (marker-buffer m))
28906 (goto-char m)
28907 (org-agenda-set-restriction-lock 'subtree))))
28908 ((setq p (text-property-any (point-at-bol) (point-at-eol)
28909 'speedbar-function 'speedbar-find-file))
28910 (setq tp (previous-single-property-change
28911 (1+ p) 'speedbar-function)
28912 np (next-single-property-change
28913 tp 'speedbar-function)
28914 dir (speedbar-line-directory)
28915 txt (buffer-substring-no-properties (or tp (point-min))
28916 (or np (point-max))))
28917 (save-excursion
28918 (save-restriction
28919 (set-buffer (find-file-noselect
28920 (let ((default-directory dir))
28921 (expand-file-name txt))))
28922 (unless (org-mode-p)
28923 (error "Cannot restrict to non-Org-mode file"))
28924 (org-agenda-set-restriction-lock 'file))))
28925 (t (error "Don't know how to restrict Org-mode's agenda")))
28926 (org-move-overlay org-speedbar-restriction-lock-overlay
28927 (point-at-bol) (point-at-eol))
28928 (setq current-prefix-arg nil)
28929 (org-agenda-maybe-redo)))
28931 (eval-after-load "speedbar"
28932 '(progn
28933 (speedbar-add-supported-extension ".org")
28934 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
28935 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
28936 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
28937 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
28938 (add-hook 'speedbar-visiting-tag-hook
28939 (lambda () (org-show-context 'org-goto)))))
28942 ;;; Fixes and Hacks
28944 ;; Make flyspell not check words in links, to not mess up our keymap
28945 (defun org-mode-flyspell-verify ()
28946 "Don't let flyspell put overlays at active buttons."
28947 (not (get-text-property (point) 'keymap)))
28949 ;; Make `bookmark-jump' show the jump location if it was hidden.
28950 (eval-after-load "bookmark"
28951 '(if (boundp 'bookmark-after-jump-hook)
28952 ;; We can use the hook
28953 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
28954 ;; Hook not available, use advice
28955 (defadvice bookmark-jump (after org-make-visible activate)
28956 "Make the position visible."
28957 (org-bookmark-jump-unhide))))
28959 (defun org-bookmark-jump-unhide ()
28960 "Unhide the current position, to show the bookmark location."
28961 (and (org-mode-p)
28962 (or (org-invisible-p)
28963 (save-excursion (goto-char (max (point-min) (1- (point))))
28964 (org-invisible-p)))
28965 (org-show-context 'bookmark-jump)))
28967 ;; Make session.el ignore our circular variable
28968 (eval-after-load "session"
28969 '(add-to-list 'session-globals-exclude 'org-mark-ring))
28971 ;;;; Experimental code
28973 (defun org-closed-in-range ()
28974 "Sparse tree of items closed in a certain time range.
28975 Still experimental, may disappear in the future."
28976 (interactive)
28977 ;; Get the time interval from the user.
28978 (let* ((time1 (time-to-seconds
28979 (org-read-date nil 'to-time nil "Starting date: ")))
28980 (time2 (time-to-seconds
28981 (org-read-date nil 'to-time nil "End date:")))
28982 ;; callback function
28983 (callback (lambda ()
28984 (let ((time
28985 (time-to-seconds
28986 (apply 'encode-time
28987 (org-parse-time-string
28988 (match-string 1))))))
28989 ;; check if time in interval
28990 (and (>= time time1) (<= time time2))))))
28991 ;; make tree, check each match with the callback
28992 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
28995 ;;;; Finish up
28997 (provide 'org)
28999 (run-hooks 'org-load-hook)
29001 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
29002 ;;; org.el ends here