Fixed bug related to repeating time stamps.
[org-mode.git] / lisp / org.el
blob92dad4b7dea870471059242c2dcd97e2524fe1c7
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: 6.00pre-1
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 (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
68 (defvar org-table-formula-constants-local nil
69 "Local version of `org-table-formula-constants'.")
70 (make-variable-buffer-local 'org-table-formula-constants-local)
72 ;;;; Require other packages
74 (eval-when-compile
75 (require 'cl)
76 (require 'gnus-sum)
77 (require 'calendar))
78 ;; For XEmacs, noutline is not yet provided by outline.el, so arrange for
79 ;; the file noutline.el being loaded.
80 (if (featurep 'xemacs) (condition-case nil (require 'noutline)))
81 ;; We require noutline, which might be provided in outline.el
82 (require 'outline) (require 'noutline)
83 ;; Other stuff we need.
84 (require 'time-date)
85 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
86 (require 'easymenu)
88 (require 'org-macs)
89 (require 'org-compat)
91 ;;;; Customization variables
93 ;;; Version
95 (defconst org-version "6.00pre-1"
96 "The version number of the file org.el.")
98 (defun org-version (&optional here)
99 "Show the org-mode version in the echo area.
100 With prefix arg HERE, insert it at point."
101 (interactive "P")
102 (let ((version (format "Org-mode version %s" org-version)))
103 (message version)
104 (if here
105 (insert version))))
107 ;;; Compatibility constants
109 ;;; The custom variables
111 (defgroup org nil
112 "Outline-based notes management and organizer."
113 :tag "Org"
114 :group 'outlines
115 :group 'hypermedia
116 :group 'calendar)
118 (defcustom org-load-hook nil
119 "Hook that is run after org.el has been loaded."
120 :group 'org
121 :type 'hook)
123 (defvar org-modules) ; defined below
124 (defvar org-modules-loaded nil
125 "Have the modules been loaded already?")
127 (defun org-load-modules-maybe (&optional force)
128 "Load all extensions listed in `org-default-extensions'."
129 (when (or force (not org-modules-loaded))
130 (mapc (lambda (ext)
131 (condition-case nil (require ext)
132 (error (message "Problems while trying to load feature `%s'" ext))))
133 org-modules)
134 (setq org-modules-loaded t)))
136 (defun org-set-modules (var value)
137 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
138 (set var value)
139 (when (featurep 'org)
140 (org-load-modules-maybe 'force)))
142 (defcustom org-modules '(org-bbdb org-gnus org-info org-irc org-mhe org-rmail org-vm org-wl)
143 "Modules that should always be loaded together with org.el.
144 If the description starts with <A>, this means the extension
145 will be autoloaded when needed, preloading is not necessary.
146 If a description starts with <C>, the file is not part of emacs
147 and loading it will require that you have downloaded and properly installed
148 the org-mode distribution."
149 :group 'org
150 :set 'org-set-modules
151 :type
152 '(set :greedy t
153 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
154 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
155 (const :tag " info: Links to Info nodes" org-info)
156 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
157 (const :tag " mac-message: Links to messages in Apple Mail" org-mac-message)
158 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
159 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
160 (const :tag " vm: Links to VM folders/messages" org-vm)
161 (const :tag " wl: Links to Wanderlust folders/messages" org-wl)
162 (const :tag " mouse: Additional mouse support" org-mouse)
163 ; (const :tag "A export-latex: LaTeX export" org-export-latex)
164 ; (const :tag "A publish: Publishing" org-publish)
166 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
167 (const :tag "C bibtex: Org links to BibTeX entries" org-bibtex)
168 (const :tag "C depend: TODO dependencies for Org-mode" org-depend)
169 (const :tag "C elisp-symbol: Org links to emacs-lisp symbols" org-elisp-symbol)
170 (const :tag "C expiry: Expiry mechanism for Org entries" org-expiry)
171 (const :tag "C id: Global id's for identifying entries" org-id)
172 (const :tag "C interactive-query: Interactive modification of tags query" org-interactive-query)
173 (const :tag "C iswitchb: Use iswitchb to select Org buffer" org-iswitchb)
174 (const :tag "C mairix: Hook mairix search into Org for different MUAs" org-mairix)
175 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
176 (const :tag "C mew: Support for links to messages in Mew" org-mew)
177 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
178 (const :tag "C registry: A registry for Org links" org-registry)
179 (const :tag "C org2rem: Convert org appointments into reminders" org2rem)
180 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
181 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)))
183 ;; FIXME: Needs a separate group...
184 (defcustom org-completion-fallback-command 'hippie-expand
185 "The expansion command called by \\[org-complete] in normal context.
186 Normal means, no org-mode-specific context."
187 :group 'org
188 :type 'function)
190 (defgroup org-startup nil
191 "Options concerning startup of Org-mode."
192 :tag "Org Startup"
193 :group 'org)
195 (defcustom org-startup-folded t
196 "Non-nil means, entering Org-mode will switch to OVERVIEW.
197 This can also be configured on a per-file basis by adding one of
198 the following lines anywhere in the buffer:
200 #+STARTUP: fold
201 #+STARTUP: nofold
202 #+STARTUP: content"
203 :group 'org-startup
204 :type '(choice
205 (const :tag "nofold: show all" nil)
206 (const :tag "fold: overview" t)
207 (const :tag "content: all headlines" content)))
209 (defcustom org-startup-truncated t
210 "Non-nil means, entering Org-mode will set `truncate-lines'.
211 This is useful since some lines containing links can be very long and
212 uninteresting. Also tables look terrible when wrapped."
213 :group 'org-startup
214 :type 'boolean)
216 (defcustom org-startup-align-all-tables nil
217 "Non-nil means, align all tables when visiting a file.
218 This is useful when the column width in tables is forced with <N> cookies
219 in table fields. Such tables will look correct only after the first re-align.
220 This can also be configured on a per-file basis by adding one of
221 the following lines anywhere in the buffer:
222 #+STARTUP: align
223 #+STARTUP: noalign"
224 :group 'org-startup
225 :type 'boolean)
227 (defcustom org-insert-mode-line-in-empty-file nil
228 "Non-nil means insert the first line setting Org-mode in empty files.
229 When the function `org-mode' is called interactively in an empty file, this
230 normally means that the file name does not automatically trigger Org-mode.
231 To ensure that the file will always be in Org-mode in the future, a
232 line enforcing Org-mode will be inserted into the buffer, if this option
233 has been set."
234 :group 'org-startup
235 :type 'boolean)
237 (defcustom org-replace-disputed-keys nil
238 "Non-nil means use alternative key bindings for some keys.
239 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
240 These keys are also used by other packages like `CUA-mode' or `windmove.el'.
241 If you want to use Org-mode together with one of these other modes,
242 or more generally if you would like to move some Org-mode commands to
243 other keys, set this variable and configure the keys with the variable
244 `org-disputed-keys'.
246 This option is only relevant at load-time of Org-mode, and must be set
247 *before* org.el is loaded. Changing it requires a restart of Emacs to
248 become effective."
249 :group 'org-startup
250 :type 'boolean)
252 (if (fboundp 'defvaralias)
253 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys))
255 (defcustom org-disputed-keys
256 '(([(shift up)] . [(meta p)])
257 ([(shift down)] . [(meta n)])
258 ([(shift left)] . [(meta -)])
259 ([(shift right)] . [(meta +)])
260 ([(control shift right)] . [(meta shift +)])
261 ([(control shift left)] . [(meta shift -)]))
262 "Keys for which Org-mode and other modes compete.
263 This is an alist, cars are the default keys, second element specifies
264 the alternative to use when `org-replace-disputed-keys' is t.
266 Keys can be specified in any syntax supported by `define-key'.
267 The value of this option takes effect only at Org-mode's startup,
268 therefore you'll have to restart Emacs to apply it after changing."
269 :group 'org-startup
270 :type 'alist)
272 (defun org-key (key)
273 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
274 Or return the original if not disputed."
275 (if org-replace-disputed-keys
276 (let* ((nkey (key-description key))
277 (x (org-find-if (lambda (x)
278 (equal (key-description (car x)) nkey))
279 org-disputed-keys)))
280 (if x (cdr x) key))
281 key))
283 (defun org-find-if (predicate seq)
284 (catch 'exit
285 (while seq
286 (if (funcall predicate (car seq))
287 (throw 'exit (car seq))
288 (pop seq)))))
290 (defun org-defkey (keymap key def)
291 "Define a key, possibly translated, as returned by `org-key'."
292 (define-key keymap (org-key key) def))
294 (defcustom org-ellipsis nil
295 "The ellipsis to use in the Org-mode outline.
296 When nil, just use the standard three dots. When a string, use that instead,
297 When a face, use the standart 3 dots, but with the specified face.
298 The change affects only Org-mode (which will then use its own display table).
299 Changing this requires executing `M-x org-mode' in a buffer to become
300 effective."
301 :group 'org-startup
302 :type '(choice (const :tag "Default" nil)
303 (face :tag "Face" :value org-warning)
304 (string :tag "String" :value "...#")))
306 (defvar org-display-table nil
307 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
309 (defgroup org-keywords nil
310 "Keywords in Org-mode."
311 :tag "Org Keywords"
312 :group 'org)
314 (defcustom org-deadline-string "DEADLINE:"
315 "String to mark deadline entries.
316 A deadline is this string, followed by a time stamp. Should be a word,
317 terminated by a colon. You can insert a schedule keyword and
318 a timestamp with \\[org-deadline].
319 Changes become only effective after restarting Emacs."
320 :group 'org-keywords
321 :type 'string)
323 (defcustom org-scheduled-string "SCHEDULED:"
324 "String to mark scheduled TODO entries.
325 A schedule is this string, followed by a time stamp. Should be a word,
326 terminated by a colon. You can insert a schedule keyword and
327 a timestamp with \\[org-schedule].
328 Changes become only effective after restarting Emacs."
329 :group 'org-keywords
330 :type 'string)
332 (defcustom org-closed-string "CLOSED:"
333 "String used as the prefix for timestamps logging closing a TODO entry."
334 :group 'org-keywords
335 :type 'string)
337 (defcustom org-clock-string "CLOCK:"
338 "String used as prefix for timestamps clocking work hours on an item."
339 :group 'org-keywords
340 :type 'string)
342 (defcustom org-comment-string "COMMENT"
343 "Entries starting with this keyword will never be exported.
344 An entry can be toggled between COMMENT and normal with
345 \\[org-toggle-comment].
346 Changes become only effective after restarting Emacs."
347 :group 'org-keywords
348 :type 'string)
350 (defcustom org-quote-string "QUOTE"
351 "Entries starting with this keyword will be exported in fixed-width font.
352 Quoting applies only to the text in the entry following the headline, and does
353 not extend beyond the next headline, even if that is lower level.
354 An entry can be toggled between QUOTE and normal with
355 \\[org-toggle-fixed-width-section]."
356 :group 'org-keywords
357 :type 'string)
359 (defconst org-repeat-re
360 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*\\([.+]?\\+[0-9]+[dwmy]\\)"
361 "Regular expression for specifying repeated events.
362 After a match, group 1 contains the repeat expression.")
364 (defgroup org-structure nil
365 "Options concerning the general structure of Org-mode files."
366 :tag "Org Structure"
367 :group 'org)
369 (defgroup org-reveal-location nil
370 "Options about how to make context of a location visible."
371 :tag "Org Reveal Location"
372 :group 'org-structure)
374 (defconst org-context-choice
375 '(choice
376 (const :tag "Always" t)
377 (const :tag "Never" nil)
378 (repeat :greedy t :tag "Individual contexts"
379 (cons
380 (choice :tag "Context"
381 (const agenda)
382 (const org-goto)
383 (const occur-tree)
384 (const tags-tree)
385 (const link-search)
386 (const mark-goto)
387 (const bookmark-jump)
388 (const isearch)
389 (const default))
390 (boolean))))
391 "Contexts for the reveal options.")
393 (defcustom org-show-hierarchy-above '((default . t))
394 "Non-nil means, show full hierarchy when revealing a location.
395 Org-mode often shows locations in an org-mode file which might have
396 been invisible before. When this is set, the hierarchy of headings
397 above the exposed location is shown.
398 Turning this off for example for sparse trees makes them very compact.
399 Instead of t, this can also be an alist specifying this option for different
400 contexts. Valid contexts are
401 agenda when exposing an entry from the agenda
402 org-goto when using the command `org-goto' on key C-c C-j
403 occur-tree when using the command `org-occur' on key C-c /
404 tags-tree when constructing a sparse tree based on tags matches
405 link-search when exposing search matches associated with a link
406 mark-goto when exposing the jump goal of a mark
407 bookmark-jump when exposing a bookmark location
408 isearch when exiting from an incremental search
409 default default for all contexts not set explicitly"
410 :group 'org-reveal-location
411 :type org-context-choice)
413 (defcustom org-show-following-heading '((default . nil))
414 "Non-nil means, show following heading when revealing a location.
415 Org-mode often shows locations in an org-mode file which might have
416 been invisible before. When this is set, the heading following the
417 match is shown.
418 Turning this off for example for sparse trees makes them very compact,
419 but makes it harder to edit the location of the match. In such a case,
420 use the command \\[org-reveal] to show more context.
421 Instead of t, this can also be an alist specifying this option for different
422 contexts. See `org-show-hierarchy-above' for valid contexts."
423 :group 'org-reveal-location
424 :type org-context-choice)
426 (defcustom org-show-siblings '((default . nil) (isearch t))
427 "Non-nil means, show all sibling heading when revealing a location.
428 Org-mode often shows locations in an org-mode file which might have
429 been invisible before. When this is set, the sibling of the current entry
430 heading are all made visible. If `org-show-hierarchy-above' is t,
431 the same happens on each level of the hierarchy above the current entry.
433 By default this is on for the isearch context, off for all other contexts.
434 Turning this off for example for sparse trees makes them very compact,
435 but makes it harder to edit the location of the match. In such a case,
436 use the command \\[org-reveal] to show more context.
437 Instead of t, this can also be an alist specifying this option for different
438 contexts. See `org-show-hierarchy-above' for valid contexts."
439 :group 'org-reveal-location
440 :type org-context-choice)
442 (defcustom org-show-entry-below '((default . nil))
443 "Non-nil means, show the entry below a headline when revealing a location.
444 Org-mode often shows locations in an org-mode file which might have
445 been invisible before. When this is set, the text below the headline that is
446 exposed is also shown.
448 By default this is off for all contexts.
449 Instead of t, this can also be an alist specifying this option for different
450 contexts. See `org-show-hierarchy-above' for valid contexts."
451 :group 'org-reveal-location
452 :type org-context-choice)
454 (defcustom org-indirect-buffer-display 'other-window
455 "How should indirect tree buffers be displayed?
456 This applies to indirect buffers created with the commands
457 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
458 Valid values are:
459 current-window Display in the current window
460 other-window Just display in another window.
461 dedicated-frame Create one new frame, and re-use it each time.
462 new-frame Make a new frame each time. Note that in this case
463 previously-made indirect buffers are kept, and you need to
464 kill these buffers yourself."
465 :group 'org-structure
466 :group 'org-agenda-windows
467 :type '(choice
468 (const :tag "In current window" current-window)
469 (const :tag "In current frame, other window" other-window)
470 (const :tag "Each time a new frame" new-frame)
471 (const :tag "One dedicated frame" dedicated-frame)))
473 (defgroup org-cycle nil
474 "Options concerning visibility cycling in Org-mode."
475 :tag "Org Cycle"
476 :group 'org-structure)
478 (defcustom org-drawers '("PROPERTIES" "CLOCK")
479 "Names of drawers. Drawers are not opened by cycling on the headline above.
480 Drawers only open with a TAB on the drawer line itself. A drawer looks like
481 this:
482 :DRAWERNAME:
483 .....
484 :END:
485 The drawer \"PROPERTIES\" is special for capturing properties through
486 the property API.
488 Drawers can be defined on the per-file basis with a line like:
490 #+DRAWERS: HIDDEN STATE PROPERTIES"
491 :group 'org-structure
492 :type '(repeat (string :tag "Drawer Name")))
494 (defcustom org-cycle-global-at-bob nil
495 "Cycle globally if cursor is at beginning of buffer and not at a headline.
496 This makes it possible to do global cycling without having to use S-TAB or
497 C-u TAB. For this special case to work, the first line of the buffer
498 must not be a headline - it may be empty ot some other text. When used in
499 this way, `org-cycle-hook' is disables temporarily, to make sure the
500 cursor stays at the beginning of the buffer.
501 When this option is nil, don't do anything special at the beginning
502 of the buffer."
503 :group 'org-cycle
504 :type 'boolean)
506 (defcustom org-cycle-emulate-tab t
507 "Where should `org-cycle' emulate TAB.
508 nil Never
509 white Only in completely white lines
510 whitestart Only at the beginning of lines, before the first non-white char
511 t Everywhere except in headlines
512 exc-hl-bol Everywhere except at the start of a headline
513 If TAB is used in a place where it does not emulate TAB, the current subtree
514 visibility is cycled."
515 :group 'org-cycle
516 :type '(choice (const :tag "Never" nil)
517 (const :tag "Only in completely white lines" white)
518 (const :tag "Before first char in a line" whitestart)
519 (const :tag "Everywhere except in headlines" t)
520 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)
523 (defcustom org-cycle-separator-lines 2
524 "Number of empty lines needed to keep an empty line between collapsed trees.
525 If you leave an empty line between the end of a subtree and the following
526 headline, this empty line is hidden when the subtree is folded.
527 Org-mode will leave (exactly) one empty line visible if the number of
528 empty lines is equal or larger to the number given in this variable.
529 So the default 2 means, at least 2 empty lines after the end of a subtree
530 are needed to produce free space between a collapsed subtree and the
531 following headline.
533 Special case: when 0, never leave empty lines in collapsed view."
534 :group 'org-cycle
535 :type 'integer)
537 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
538 org-cycle-hide-drawers
539 org-cycle-show-empty-lines
540 org-optimize-window-after-visibility-change)
541 "Hook that is run after `org-cycle' has changed the buffer visibility.
542 The function(s) in this hook must accept a single argument which indicates
543 the new state that was set by the most recent `org-cycle' command. The
544 argument is a symbol. After a global state change, it can have the values
545 `overview', `content', or `all'. After a local state change, it can have
546 the values `folded', `children', or `subtree'."
547 :group 'org-cycle
548 :type 'hook)
550 (defgroup org-edit-structure nil
551 "Options concerning structure editing in Org-mode."
552 :tag "Org Edit Structure"
553 :group 'org-structure)
555 (defcustom org-odd-levels-only nil
556 "Non-nil means, skip even levels and only use odd levels for the outline.
557 This has the effect that two stars are being added/taken away in
558 promotion/demotion commands. It also influences how levels are
559 handled by the exporters.
560 Changing it requires restart of `font-lock-mode' to become effective
561 for fontification also in regions already fontified.
562 You may also set this on a per-file basis by adding one of the following
563 lines to the buffer:
565 #+STARTUP: odd
566 #+STARTUP: oddeven"
567 :group 'org-edit-structure
568 :group 'org-font-lock
569 :type 'boolean)
571 (defcustom org-adapt-indentation t
572 "Non-nil means, adapt indentation when promoting and demoting.
573 When this is set and the *entire* text in an entry is indented, the
574 indentation is increased by one space in a demotion command, and
575 decreased by one in a promotion command. If any line in the entry
576 body starts at column 0, indentation is not changed at all."
577 :group 'org-edit-structure
578 :type 'boolean)
580 (defcustom org-special-ctrl-a/e nil
581 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
582 When t, `C-a' will bring back the cursor to the beginning of the
583 headline text, i.e. after the stars and after a possible TODO keyword.
584 In an item, this will be the position after the bullet.
585 When the cursor is already at that position, another `C-a' will bring
586 it to the beginning of the line.
587 `C-e' will jump to the end of the headline, ignoring the presence of tags
588 in the headline. A second `C-e' will then jump to the true end of the
589 line, after any tags.
590 When set to the symbol `reversed', the first `C-a' or `C-e' works normally,
591 and only a directly following, identical keypress will bring the cursor
592 to the special positions."
593 :group 'org-edit-structure
594 :type '(choice
595 (const :tag "off" nil)
596 (const :tag "after bullet first" t)
597 (const :tag "border first" reversed)))
599 (if (fboundp 'defvaralias)
600 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e))
602 (defcustom org-special-ctrl-k nil
603 "Non-nil means `C-k' will behave specially in headlines.
604 When nil, `C-k' will call the default `kill-line' command.
605 When t, the following will happen while the cursor is in the headline:
607 - When the cursor is at the beginning of a headline, kill the entire
608 line and possible the folded subtree below the line.
609 - When in the middle of the headline text, kill the headline up to the tags.
610 - When after the headline text, kill the tags."
611 :group 'org-edit-structure
612 :type 'boolean)
614 (defcustom org-M-RET-may-split-line '((default . t))
615 "Non-nil means, M-RET will split the line at the cursor position.
616 When nil, it will go to the end of the line before making a
617 new line.
618 You may also set this option in a different way for different
619 contexts. Valid contexts are:
621 headline when creating a new headline
622 item when creating a new item
623 table in a table field
624 default the value to be used for all contexts not explicitly
625 customized"
626 :group 'org-structure
627 :group 'org-table
628 :type '(choice
629 (const :tag "Always" t)
630 (const :tag "Never" nil)
631 (repeat :greedy t :tag "Individual contexts"
632 (cons
633 (choice :tag "Context"
634 (const headline)
635 (const item)
636 (const table)
637 (const default))
638 (boolean)))))
641 (defcustom org-blank-before-new-entry '((heading . nil)
642 (plain-list-item . nil))
643 "Should `org-insert-heading' leave a blank line before new heading/item?
644 The value is an alist, with `heading' and `plain-list-item' as car,
645 and a boolean flag as cdr."
646 :group 'org-edit-structure
647 :type '(list
648 (cons (const heading) (boolean))
649 (cons (const plain-list-item) (boolean))))
651 (defcustom org-insert-heading-hook nil
652 "Hook being run after inserting a new heading."
653 :group 'org-edit-structure
654 :type 'hook)
656 (defcustom org-enable-fixed-width-editor t
657 "Non-nil means, lines starting with \":\" are treated as fixed-width.
658 This currently only means, they are never auto-wrapped.
659 When nil, such lines will be treated like ordinary lines.
660 See also the QUOTE keyword."
661 :group 'org-edit-structure
662 :type 'boolean)
664 (defcustom org-goto-auto-isearch t
665 "Non-nil means, typing characters in org-goto starts incremental search."
666 :group 'org-edit-structure
667 :type 'boolean)
669 (defgroup org-sparse-trees nil
670 "Options concerning sparse trees in Org-mode."
671 :tag "Org Sparse Trees"
672 :group 'org-structure)
674 (defcustom org-highlight-sparse-tree-matches t
675 "Non-nil means, highlight all matches that define a sparse tree.
676 The highlights will automatically disappear the next time the buffer is
677 changed by an edit command."
678 :group 'org-sparse-trees
679 :type 'boolean)
681 (defcustom org-remove-highlights-with-change t
682 "Non-nil means, any change to the buffer will remove temporary highlights.
683 Such highlights are created by `org-occur' and `org-clock-display'.
684 When nil, `C-c C-c needs to be used to get rid of the highlights.
685 The highlights created by `org-preview-latex-fragment' always need
686 `C-c C-c' to be removed."
687 :group 'org-sparse-trees
688 :group 'org-time
689 :type 'boolean)
692 (defcustom org-occur-hook '(org-first-headline-recenter)
693 "Hook that is run after `org-occur' has constructed a sparse tree.
694 This can be used to recenter the window to show as much of the structure
695 as possible."
696 :group 'org-sparse-trees
697 :type 'hook)
699 (defgroup org-plain-lists nil
700 "Options concerning plain lists in Org-mode."
701 :tag "Org Plain lists"
702 :group 'org-structure)
704 (defcustom org-cycle-include-plain-lists nil
705 "Non-nil means, include plain lists into visibility cycling.
706 This means that during cycling, plain list items will *temporarily* be
707 interpreted as outline headlines with a level given by 1000+i where i is the
708 indentation of the bullet. In all other operations, plain list items are
709 not seen as headlines. For example, you cannot assign a TODO keyword to
710 such an item."
711 :group 'org-plain-lists
712 :type 'boolean)
714 (defcustom org-plain-list-ordered-item-terminator t
715 "The character that makes a line with leading number an ordered list item.
716 Valid values are ?. and ?\). To get both terminators, use t. While
717 ?. may look nicer, it creates the danger that a line with leading
718 number may be incorrectly interpreted as an item. ?\) therefore is
719 the safe choice."
720 :group 'org-plain-lists
721 :type '(choice (const :tag "dot like in \"2.\"" ?.)
722 (const :tag "paren like in \"2)\"" ?\))
723 (const :tab "both" t)))
725 (defcustom org-auto-renumber-ordered-lists t
726 "Non-nil means, automatically renumber ordered plain lists.
727 Renumbering happens when the sequence have been changed with
728 \\[org-shiftmetaup] or \\[org-shiftmetadown]. After other editing commands,
729 use \\[org-ctrl-c-ctrl-c] to trigger renumbering."
730 :group 'org-plain-lists
731 :type 'boolean)
733 (defcustom org-provide-checkbox-statistics t
734 "Non-nil means, update checkbox statistics after insert and toggle.
735 When this is set, checkbox statistics is updated each time you either insert
736 a new checkbox with \\[org-insert-todo-heading] or toggle a checkbox
737 with \\[org-ctrl-c-ctrl-c\\]."
738 :group 'org-plain-lists
739 :type 'boolean)
741 (defgroup org-archive nil
742 "Options concerning archiving in Org-mode."
743 :tag "Org Archive"
744 :group 'org-structure)
746 (defcustom org-archive-tag "ARCHIVE"
747 "The tag that marks a subtree as archived.
748 An archived subtree does not open during visibility cycling, and does
749 not contribute to the agenda listings.
750 After changing this, font-lock must be restarted in the relevant buffers to
751 get the proper fontification."
752 :group 'org-archive
753 :group 'org-keywords
754 :type 'string)
756 (defcustom org-agenda-skip-archived-trees t
757 "Non-nil means, the agenda will skip any items located in archived trees.
758 An archived tree is a tree marked with the tag ARCHIVE."
759 :group 'org-archive
760 :group 'org-agenda-skip
761 :type 'boolean)
763 (defcustom org-cycle-open-archived-trees nil
764 "Non-nil means, `org-cycle' will open archived trees.
765 An archived tree is a tree marked with the tag ARCHIVE.
766 When nil, archived trees will stay folded. You can still open them with
767 normal outline commands like `show-all', but not with the cycling commands."
768 :group 'org-archive
769 :group 'org-cycle
770 :type 'boolean)
772 (defcustom org-sparse-tree-open-archived-trees nil
773 "Non-nil means sparse tree construction shows matches in archived trees.
774 When nil, matches in these trees are highlighted, but the trees are kept in
775 collapsed state."
776 :group 'org-archive
777 :group 'org-sparse-trees
778 :type 'boolean)
780 (defcustom org-archive-location "%s_archive::"
781 "The location where subtrees should be archived.
782 This string consists of two parts, separated by a double-colon.
784 The first part is a file name - when omitted, archiving happens in the same
785 file. %s will be replaced by the current file name (without directory part).
786 Archiving to a different file is useful to keep archived entries from
787 contributing to the Org-mode Agenda.
789 The part after the double colon is a headline. The archived entries will be
790 filed under that headline. When omitted, the subtrees are simply filed away
791 at the end of the file, as top-level entries.
793 Here are a few examples:
794 \"%s_archive::\"
795 If the current file is Projects.org, archive in file
796 Projects.org_archive, as top-level trees. This is the default.
798 \"::* Archived Tasks\"
799 Archive in the current file, under the top-level headline
800 \"* Archived Tasks\".
802 \"~/org/archive.org::\"
803 Archive in file ~/org/archive.org (absolute path), as top-level trees.
805 \"basement::** Finished Tasks\"
806 Archive in file ./basement (relative path), as level 3 trees
807 below the level 2 heading \"** Finished Tasks\".
809 You may set this option on a per-file basis by adding to the buffer a
810 line like
812 #+ARCHIVE: basement::** Finished Tasks"
813 :group 'org-archive
814 :type 'string)
816 (defcustom org-archive-mark-done t
817 "Non-nil means, mark entries as DONE when they are moved to the archive file.
818 This can be a string to set the keyword to use. When t, Org-mode will
819 use the first keyword in its list that means done."
820 :group 'org-archive
821 :type '(choice
822 (const :tag "No" nil)
823 (const :tag "Yes" t)
824 (string :tag "Use this keyword")))
826 (defcustom org-archive-stamp-time t
827 "Non-nil means, add a time stamp to entries moved to an archive file.
828 This variable is obsolete and has no effect anymore, instead add ot remove
829 `time' from the variablle `org-archive-save-context-info'."
830 :group 'org-archive
831 :type 'boolean)
833 (defcustom org-archive-save-context-info '(time file olpath category todo itags)
834 "Parts of context info that should be stored as properties when archiving.
835 When a subtree is moved to an archive file, it looses information given by
836 context, like inherited tags, the category, and possibly also the TODO
837 state (depending on the variable `org-archive-mark-done').
838 This variable can be a list of any of the following symbols:
840 time The time of archiving.
841 file The file where the entry originates.
842 itags The local tags, in the headline of the subtree.
843 ltags The tags the subtree inherits from further up the hierarchy.
844 todo The pre-archive TODO state.
845 category The category, taken from file name or #+CATEGORY lines.
846 olpath The outline path to the item. These are all headlines above
847 the current item, separated by /, like a file path.
849 For each symbol present in the list, a property will be created in
850 the archived entry, with a prefix \"PRE_ARCHIVE_\", to remember this
851 information."
852 :group 'org-archive
853 :type '(set :greedy t
854 (const :tag "Time" time)
855 (const :tag "File" file)
856 (const :tag "Category" category)
857 (const :tag "TODO state" todo)
858 (const :tag "TODO state" priority)
859 (const :tag "Inherited tags" itags)
860 (const :tag "Outline path" olpath)
861 (const :tag "Local tags" ltags)))
863 (defgroup org-imenu-and-speedbar nil
864 "Options concerning imenu and speedbar in Org-mode."
865 :tag "Org Imenu and Speedbar"
866 :group 'org-structure)
868 (defcustom org-imenu-depth 2
869 "The maximum level for Imenu access to Org-mode headlines.
870 This also applied for speedbar access."
871 :group 'org-imenu-and-speedbar
872 :type 'number)
874 (defgroup org-table nil
875 "Options concerning tables in Org-mode."
876 :tag "Org Table"
877 :group 'org)
879 (defcustom org-enable-table-editor 'optimized
880 "Non-nil means, lines starting with \"|\" are handled by the table editor.
881 When nil, such lines will be treated like ordinary lines.
883 When equal to the symbol `optimized', the table editor will be optimized to
884 do the following:
885 - Automatic overwrite mode in front of whitespace in table fields.
886 This makes the structure of the table stay in tact as long as the edited
887 field does not exceed the column width.
888 - Minimize the number of realigns. Normally, the table is aligned each time
889 TAB or RET are pressed to move to another field. With optimization this
890 happens only if changes to a field might have changed the column width.
891 Optimization requires replacing the functions `self-insert-command',
892 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
893 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
894 very good at guessing when a re-align will be necessary, but you can always
895 force one with \\[org-ctrl-c-ctrl-c].
897 If you would like to use the optimized version in Org-mode, but the
898 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
900 This variable can be used to turn on and off the table editor during a session,
901 but in order to toggle optimization, a restart is required.
903 See also the variable `org-table-auto-blank-field'."
904 :group 'org-table
905 :type '(choice
906 (const :tag "off" nil)
907 (const :tag "on" t)
908 (const :tag "on, optimized" optimized)))
910 (defcustom org-table-tab-recognizes-table.el t
911 "Non-nil means, TAB will automatically notice a table.el table.
912 When it sees such a table, it moves point into it and - if necessary -
913 calls `table-recognize-table'."
914 :group 'org-table-editing
915 :type 'boolean)
917 (defgroup org-link nil
918 "Options concerning links in Org-mode."
919 :tag "Org Link"
920 :group 'org)
922 (defvar org-link-abbrev-alist-local nil
923 "Buffer-local version of `org-link-abbrev-alist', which see.
924 The value of this is taken from the #+LINK lines.")
925 (make-variable-buffer-local 'org-link-abbrev-alist-local)
927 (defcustom org-link-abbrev-alist nil
928 "Alist of link abbreviations.
929 The car of each element is a string, to be replaced at the start of a link.
930 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
931 links in Org-mode buffers can have an optional tag after a double colon, e.g.
933 [[linkkey:tag][description]]
935 If REPLACE is a string, the tag will simply be appended to create the link.
936 If the string contains \"%s\", the tag will be inserted there.
938 REPLACE may also be a function that will be called with the tag as the
939 only argument to create the link, which should be returned as a string.
941 See the manual for examples."
942 :group 'org-link
943 :type 'alist)
945 (defcustom org-descriptive-links t
946 "Non-nil means, hide link part and only show description of bracket links.
947 Bracket links are like [[link][descritpion]]. This variable sets the initial
948 state in new org-mode buffers. The setting can then be toggled on a
949 per-buffer basis from the Org->Hyperlinks menu."
950 :group 'org-link
951 :type 'boolean)
953 (defcustom org-link-file-path-type 'adaptive
954 "How the path name in file links should be stored.
955 Valid values are:
957 relative Relative to the current directory, i.e. the directory of the file
958 into which the link is being inserted.
959 absolute Absolute path, if possible with ~ for home directory.
960 noabbrev Absolute path, no abbreviation of home directory.
961 adaptive Use relative path for files in the current directory and sub-
962 directories of it. For other files, use an absolute path."
963 :group 'org-link
964 :type '(choice
965 (const relative)
966 (const absolute)
967 (const noabbrev)
968 (const adaptive)))
970 (defcustom org-activate-links '(bracket angle plain radio tag date)
971 "Types of links that should be activated in Org-mode files.
972 This is a list of symbols, each leading to the activation of a certain link
973 type. In principle, it does not hurt to turn on most link types - there may
974 be a small gain when turning off unused link types. The types are:
976 bracket The recommended [[link][description]] or [[link]] links with hiding.
977 angular Links in angular brackes that may contain whitespace like
978 <bbdb:Carsten Dominik>.
979 plain Plain links in normal text, no whitespace, like http://google.com.
980 radio Text that is matched by a radio target, see manual for details.
981 tag Tag settings in a headline (link to tag search).
982 date Time stamps (link to calendar).
984 Changing this variable requires a restart of Emacs to become effective."
985 :group 'org-link
986 :type '(set (const :tag "Double bracket links (new style)" bracket)
987 (const :tag "Angular bracket links (old style)" angular)
988 (const :tag "Plain text links" plain)
989 (const :tag "Radio target matches" radio)
990 (const :tag "Tags" tag)
991 (const :tag "Timestamps" date)))
993 (defgroup org-link-store nil
994 "Options concerning storing links in Org-mode."
995 :tag "Org Store Link"
996 :group 'org-link)
998 (defcustom org-email-link-description-format "Email %c: %.30s"
999 "Format of the description part of a link to an email or usenet message.
1000 The following %-excapes will be replaced by corresponding information:
1002 %F full \"From\" field
1003 %f name, taken from \"From\" field, address if no name
1004 %T full \"To\" field
1005 %t first name in \"To\" field, address if no name
1006 %c correspondent. Unually \"from NAME\", but if you sent it yourself, it
1007 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1008 %s subject
1009 %m message-id.
1011 You may use normal field width specification between the % and the letter.
1012 This is for example useful to limit the length of the subject.
1014 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1015 :group 'org-link-store
1016 :type 'string)
1018 (defcustom org-from-is-user-regexp
1019 (let (r1 r2)
1020 (when (and user-mail-address (not (string= user-mail-address "")))
1021 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1022 (when (and user-full-name (not (string= user-full-name "")))
1023 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1024 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1025 "Regexp mached against the \"From:\" header of an email or usenet message.
1026 It should match if the message is from the user him/herself."
1027 :group 'org-link-store
1028 :type 'regexp)
1030 (defcustom org-context-in-file-links t
1031 "Non-nil means, file links from `org-store-link' contain context.
1032 A search string will be added to the file name with :: as separator and
1033 used to find the context when the link is activated by the command
1034 `org-open-at-point'.
1035 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1036 negates this setting for the duration of the command."
1037 :group 'org-link-store
1038 :type 'boolean)
1040 (defcustom org-keep-stored-link-after-insertion nil
1041 "Non-nil means, keep link in list for entire session.
1043 The command `org-store-link' adds a link pointing to the current
1044 location to an internal list. These links accumulate during a session.
1045 The command `org-insert-link' can be used to insert links into any
1046 Org-mode file (offering completion for all stored links). When this
1047 option is nil, every link which has been inserted once using \\[org-insert-link]
1048 will be removed from the list, to make completing the unused links
1049 more efficient."
1050 :group 'org-link-store
1051 :type 'boolean)
1053 (defgroup org-link-follow nil
1054 "Options concerning following links in Org-mode."
1055 :tag "Org Follow Link"
1056 :group 'org-link)
1058 (defcustom org-follow-link-hook nil
1059 "Hook that is run after a link has been followed."
1060 :group 'org-link-follow
1061 :type 'hook)
1063 (defcustom org-tab-follows-link nil
1064 "Non-nil means, on links TAB will follow the link.
1065 Needs to be set before org.el is loaded."
1066 :group 'org-link-follow
1067 :type 'boolean)
1069 (defcustom org-return-follows-link nil
1070 "Non-nil means, on links RET will follow the link.
1071 Needs to be set before org.el is loaded."
1072 :group 'org-link-follow
1073 :type 'boolean)
1075 (defcustom org-mouse-1-follows-link
1076 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1077 "Non-nil means, mouse-1 on a link will follow the link.
1078 A longer mouse click will still set point. Does not work on XEmacs.
1079 Needs to be set before org.el is loaded."
1080 :group 'org-link-follow
1081 :type 'boolean)
1083 (defcustom org-mark-ring-length 4
1084 "Number of different positions to be recorded in the ring
1085 Changing this requires a restart of Emacs to work correctly."
1086 :group 'org-link-follow
1087 :type 'interger)
1089 (defcustom org-link-frame-setup
1090 '((vm . vm-visit-folder-other-frame)
1091 (gnus . gnus-other-frame)
1092 (file . find-file-other-window))
1093 "Setup the frame configuration for following links.
1094 When following a link with Emacs, it may often be useful to display
1095 this link in another window or frame. This variable can be used to
1096 set this up for the different types of links.
1097 For VM, use any of
1098 `vm-visit-folder'
1099 `vm-visit-folder-other-frame'
1100 For Gnus, use any of
1101 `gnus'
1102 `gnus-other-frame'
1103 For FILE, use any of
1104 `find-file'
1105 `find-file-other-window'
1106 `find-file-other-frame'
1107 For the calendar, use the variable `calendar-setup'.
1108 For BBDB, it is currently only possible to display the matches in
1109 another window."
1110 :group 'org-link-follow
1111 :type '(list
1112 (cons (const vm)
1113 (choice
1114 (const vm-visit-folder)
1115 (const vm-visit-folder-other-window)
1116 (const vm-visit-folder-other-frame)))
1117 (cons (const gnus)
1118 (choice
1119 (const gnus)
1120 (const gnus-other-frame)))
1121 (cons (const file)
1122 (choice
1123 (const find-file)
1124 (const find-file-other-window)
1125 (const find-file-other-frame)))))
1127 (defcustom org-display-internal-link-with-indirect-buffer nil
1128 "Non-nil means, use indirect buffer to display infile links.
1129 Activating internal links (from one location in a file to another location
1130 in the same file) normally just jumps to the location. When the link is
1131 activated with a C-u prefix (or with mouse-3), the link is displayed in
1132 another window. When this option is set, the other window actually displays
1133 an indirect buffer clone of the current buffer, to avoid any visibility
1134 changes to the current buffer."
1135 :group 'org-link-follow
1136 :type 'boolean)
1138 (defcustom org-open-non-existing-files nil
1139 "Non-nil means, `org-open-file' will open non-existing files.
1140 When nil, an error will be generated."
1141 :group 'org-link-follow
1142 :type 'boolean)
1144 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1145 "Function and arguments to call for following mailto links.
1146 This is a list with the first element being a lisp function, and the
1147 remaining elements being arguments to the function. In string arguments,
1148 %a will be replaced by the address, and %s will be replaced by the subject
1149 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1150 :group 'org-link-follow
1151 :type '(choice
1152 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1153 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1154 (const :tag "message-mail" (message-mail "%a" "%s"))
1155 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1157 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1158 "Non-nil means, ask for confirmation before executing shell links.
1159 Shell links can be dangerous: just think about a link
1161 [[shell:rm -rf ~/*][Google Search]]
1163 This link would show up in your Org-mode document as \"Google Search\",
1164 but really it would remove your entire home directory.
1165 Therefore we advise against setting this variable to nil.
1166 Just change it to `y-or-n-p' of you want to confirm with a
1167 single keystroke rather than having to type \"yes\"."
1168 :group 'org-link-follow
1169 :type '(choice
1170 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1171 (const :tag "with y-or-n (faster)" y-or-n-p)
1172 (const :tag "no confirmation (dangerous)" nil)))
1174 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1175 "Non-nil means, ask for confirmation before executing Emacs Lisp links.
1176 Elisp links can be dangerous: just think about a link
1178 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1180 This link would show up in your Org-mode document as \"Google Search\",
1181 but really it would remove your entire home directory.
1182 Therefore we advise against setting this variable to nil.
1183 Just change it to `y-or-n-p' of you want to confirm with a
1184 single keystroke rather than having to type \"yes\"."
1185 :group 'org-link-follow
1186 :type '(choice
1187 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1188 (const :tag "with y-or-n (faster)" y-or-n-p)
1189 (const :tag "no confirmation (dangerous)" nil)))
1191 (defconst org-file-apps-defaults-gnu
1192 '((remote . emacs)
1193 (t . mailcap))
1194 "Default file applications on a UNIX or GNU/Linux system.
1195 See `org-file-apps'.")
1197 (defconst org-file-apps-defaults-macosx
1198 '((remote . emacs)
1199 (t . "open %s")
1200 ("ps" . "gv %s")
1201 ("ps.gz" . "gv %s")
1202 ("eps" . "gv %s")
1203 ("eps.gz" . "gv %s")
1204 ("dvi" . "xdvi %s")
1205 ("fig" . "xfig %s"))
1206 "Default file applications on a MacOS X system.
1207 The system \"open\" is known as a default, but we use X11 applications
1208 for some files for which the OS does not have a good default.
1209 See `org-file-apps'.")
1211 (defconst org-file-apps-defaults-windowsnt
1212 (list
1213 '(remote . emacs)
1214 (cons t
1215 (list (if (featurep 'xemacs)
1216 'mswindows-shell-execute
1217 'w32-shell-execute)
1218 "open" 'file)))
1219 "Default file applications on a Windows NT system.
1220 The system \"open\" is used for most files.
1221 See `org-file-apps'.")
1223 (defcustom org-file-apps
1225 ("txt" . emacs)
1226 ("tex" . emacs)
1227 ("ltx" . emacs)
1228 ("org" . emacs)
1229 ("el" . emacs)
1230 ("bib" . emacs)
1232 "External applications for opening `file:path' items in a document.
1233 Org-mode uses system defaults for different file types, but
1234 you can use this variable to set the application for a given file
1235 extension. The entries in this list are cons cells where the car identifies
1236 files and the cdr the corresponding command. Possible values for the
1237 file identifier are
1238 \"ext\" A string identifying an extension
1239 `directory' Matches a directory
1240 `remote' Matches a remote file, accessible through tramp or efs.
1241 Remote files most likely should be visited through Emacs
1242 because external applications cannot handle such paths.
1243 t Default for all remaining files
1245 Possible values for the command are:
1246 `emacs' The file will be visited by the current Emacs process.
1247 `default' Use the default application for this file type.
1248 string A command to be executed by a shell; %s will be replaced
1249 by the path to the file.
1250 sexp A Lisp form which will be evaluated. The file path will
1251 be available in the Lisp variable `file'.
1252 For more examples, see the system specific constants
1253 `org-file-apps-defaults-macosx'
1254 `org-file-apps-defaults-windowsnt'
1255 `org-file-apps-defaults-gnu'."
1256 :group 'org-link-follow
1257 :type '(repeat
1258 (cons (choice :value ""
1259 (string :tag "Extension")
1260 (const :tag "Default for unrecognized files" t)
1261 (const :tag "Remote file" remote)
1262 (const :tag "Links to a directory" directory))
1263 (choice :value ""
1264 (const :tag "Visit with Emacs" emacs)
1265 (const :tag "Use system default" default)
1266 (string :tag "Command")
1267 (sexp :tag "Lisp form")))))
1269 (defgroup org-refile nil
1270 "Options concerning refiling entries in Org-mode."
1271 :tag "Org Remember"
1272 :group 'org)
1274 (defcustom org-directory "~/org"
1275 "Directory with org files.
1276 This directory will be used as default to prompt for org files.
1277 Used by the hooks for remember.el."
1278 :group 'org-refile
1279 :group 'org-remember
1280 :type 'directory)
1282 (defcustom org-default-notes-file "~/.notes"
1283 "Default target for storing notes.
1284 Used by the hooks for remember.el. This can be a string, or nil to mean
1285 the value of `remember-data-file'.
1286 You can set this on a per-template basis with the variable
1287 `org-remember-templates'."
1288 :group 'org-refile
1289 :group 'org-remember
1290 :type '(choice
1291 (const :tag "Default from remember-data-file" nil)
1292 file))
1294 (defcustom org-goto-interface 'outline
1295 "The default interface to be used for `org-goto'.
1296 Allowed vaues are:
1297 outline The interface shows an outline of the relevant file
1298 and the correct heading is found by moving through
1299 the outline or by searching with incremental search.
1300 outline-path-completion Headlines in the current buffer are offered via
1301 completion."
1302 :group 'org-refile
1303 :type '(choice
1304 (const :tag "Outline" outline)
1305 (const :tag "Outline-path-completion" outline-path-completion)))
1307 (defcustom org-reverse-note-order nil
1308 "Non-nil means, store new notes at the beginning of a file or entry.
1309 When nil, new notes will be filed to the end of a file or entry.
1310 This can also be a list with cons cells of regular expressions that
1311 are matched against file names, and values."
1312 :group 'org-remember
1313 :type '(choice
1314 (const :tag "Reverse always" t)
1315 (const :tag "Reverse never" nil)
1316 (repeat :tag "By file name regexp"
1317 (cons regexp boolean))))
1319 (defcustom org-refile-targets nil
1320 "Targets for refiling entries with \\[org-refile].
1321 This is list of cons cells. Each cell contains:
1322 - a specification of the files to be considered, either a list of files,
1323 or a symbol whose function or value fields will be used to retrieve
1324 a file name or a list of file names. Nil means, refile to a different
1325 heading in the current buffer.
1326 - A specification of how to find candidate refile targets. This may be
1327 any of
1328 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
1329 This tag has to be present in all target headlines, inheritance will
1330 not be considered.
1331 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
1332 todo keyword.
1333 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1334 headlines that are refiling targets.
1335 - a cons cell (:level . N). Any headline of level N is considered a target.
1336 - a cons cell (:maxlevel . N). Any headline with level <= N is a target."
1337 ;; FIXME: what if there are a var and func with same name???
1338 :group 'org-remember
1339 :type '(repeat
1340 (cons
1341 (choice :value org-agenda-files
1342 (const :tag "All agenda files" org-agenda-files)
1343 (const :tag "Current buffer" nil)
1344 (function) (variable) (file))
1345 (choice :tag "Identify target headline by"
1346 (cons :tag "Specific tag" (const :tag) (string))
1347 (cons :tag "TODO keyword" (const :todo) (string))
1348 (cons :tag "Regular expression" (const :regexp) (regexp))
1349 (cons :tag "Level number" (const :level) (integer))
1350 (cons :tag "Max Level number" (const :maxlevel) (integer))))))
1352 (defcustom org-refile-use-outline-path nil
1353 "Non-nil means, provide refile targets as paths.
1354 So a level 3 headline will be available as level1/level2/level3.
1355 When the value is `file', also include the file name (without directory)
1356 into the path. When `full-file-path', include the full file path."
1357 :group 'org-remember
1358 :type '(choice
1359 (const :tag "Not" nil)
1360 (const :tag "Yes" t)
1361 (const :tag "Start with file name" file)
1362 (const :tag "Start with full file path" full-file-path)))
1364 (defgroup org-todo nil
1365 "Options concerning TODO items in Org-mode."
1366 :tag "Org TODO"
1367 :group 'org)
1369 (defgroup org-progress nil
1370 "Options concerning Progress logging in Org-mode."
1371 :tag "Org Progress"
1372 :group 'org-time)
1374 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
1375 "List of TODO entry keyword sequences and their interpretation.
1376 \\<org-mode-map>This is a list of sequences.
1378 Each sequence starts with a symbol, either `sequence' or `type',
1379 indicating if the keywords should be interpreted as a sequence of
1380 action steps, or as different types of TODO items. The first
1381 keywords are states requiring action - these states will select a headline
1382 for inclusion into the global TODO list Org-mode produces. If one of
1383 the \"keywords\" is the vertical bat \"|\" the remaining keywords
1384 signify that no further action is necessary. If \"|\" is not found,
1385 the last keyword is treated as the only DONE state of the sequence.
1387 The command \\[org-todo] cycles an entry through these states, and one
1388 additional state where no keyword is present. For details about this
1389 cycling, see the manual.
1391 TODO keywords and interpretation can also be set on a per-file basis with
1392 the special #+SEQ_TODO and #+TYP_TODO lines.
1394 Each keyword can optionally specify a character for fast state selection
1395 \(in combination with the variable `org-use-fast-todo-selection')
1396 and specifiers for state change logging, using the same syntax
1397 that is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says
1398 that the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
1399 indicates to record a time stamp each time this state is selected.
1401 Each keyword may also specify if a timestamp or a note should be
1402 recorded when entering or leaving the state, by adding additional
1403 characters in the parenthesis after the keyword. This looks like this:
1404 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
1405 record only the time of the state change. With X and Y being either
1406 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
1407 Y when leaving the state if and only if the *target* state does not
1408 define X. You may omit any of the fast-selection key or X or /Y,
1409 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
1411 For backward compatibility, this variable may also be just a list
1412 of keywords - in this case the interptetation (sequence or type) will be
1413 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
1414 :group 'org-todo
1415 :group 'org-keywords
1416 :type '(choice
1417 (repeat :tag "Old syntax, just keywords"
1418 (string :tag "Keyword"))
1419 (repeat :tag "New syntax"
1420 (cons
1421 (choice
1422 :tag "Interpretation"
1423 (const :tag "Sequence (cycling hits every state)" sequence)
1424 (const :tag "Type (cycling directly to DONE)" type))
1425 (repeat
1426 (string :tag "Keyword"))))))
1428 (defvar org-todo-keywords-1 nil
1429 "All TODO and DONE keywords active in a buffer.")
1430 (make-variable-buffer-local 'org-todo-keywords-1)
1431 (defvar org-todo-keywords-for-agenda nil)
1432 (defvar org-done-keywords-for-agenda nil)
1433 (defvar org-not-done-keywords nil)
1434 (make-variable-buffer-local 'org-not-done-keywords)
1435 (defvar org-done-keywords nil)
1436 (make-variable-buffer-local 'org-done-keywords)
1437 (defvar org-todo-heads nil)
1438 (make-variable-buffer-local 'org-todo-heads)
1439 (defvar org-todo-sets nil)
1440 (make-variable-buffer-local 'org-todo-sets)
1441 (defvar org-todo-log-states nil)
1442 (make-variable-buffer-local 'org-todo-log-states)
1443 (defvar org-todo-kwd-alist nil)
1444 (make-variable-buffer-local 'org-todo-kwd-alist)
1445 (defvar org-todo-key-alist nil)
1446 (make-variable-buffer-local 'org-todo-key-alist)
1447 (defvar org-todo-key-trigger nil)
1448 (make-variable-buffer-local 'org-todo-key-trigger)
1450 (defcustom org-todo-interpretation 'sequence
1451 "Controls how TODO keywords are interpreted.
1452 This variable is in principle obsolete and is only used for
1453 backward compatibility, if the interpretation of todo keywords is
1454 not given already in `org-todo-keywords'. See that variable for
1455 more information."
1456 :group 'org-todo
1457 :group 'org-keywords
1458 :type '(choice (const sequence)
1459 (const type)))
1461 (defcustom org-use-fast-todo-selection 'prefix
1462 "Non-nil means, use the fast todo selection scheme with C-c C-t.
1463 This variable describes if and under what circumstances the cycling
1464 mechanism for TODO keywords will be replaced by a single-key, direct
1465 selection scheme.
1467 When nil, fast selection is never used.
1469 When the symbol `prefix', it will be used when `org-todo' is called with
1470 a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and `C-u t'
1471 in an agenda buffer.
1473 When t, fast selection is used by default. In this case, the prefix
1474 argument forces cycling instead.
1476 In all cases, the special interface is only used if access keys have actually
1477 been assigned by the user, i.e. if keywords in the configuration are followed
1478 by a letter in parenthesis, like TODO(t)."
1479 :group 'org-todo
1480 :type '(choice
1481 (const :tag "Never" nil)
1482 (const :tag "By default" t)
1483 (const :tag "Only with C-u C-c C-t" prefix)))
1485 (defcustom org-after-todo-state-change-hook nil
1486 "Hook which is run after the state of a TODO item was changed.
1487 The new state (a string with a TODO keyword, or nil) is available in the
1488 Lisp variable `state'."
1489 :group 'org-todo
1490 :type 'hook)
1492 (defcustom org-log-done nil
1493 "Non-nil means, record a CLOSED timestamp when moving an entry to DONE.
1494 When equal to the list (done), also prompt for a closing note.
1495 This can also be configured on a per-file basis by adding one of
1496 the following lines anywhere in the buffer:
1498 #+STARTUP: logdone
1499 #+STARTUP: lognotedone
1500 #+STARTUP: nologdone"
1501 :group 'org-todo
1502 :group 'org-progress
1503 :type '(choice
1504 (const :tag "No logging" nil)
1505 (const :tag "Record CLOSED timestamp" time)
1506 (const :tag "Record CLOSED timestamp with closing note." note)))
1508 ;; Normalize old uses of org-log-done.
1509 (cond
1510 ((eq org-log-done t) (setq org-log-done 'time))
1511 ((and (listp org-log-done) (memq 'done org-log-done))
1512 (setq org-log-done 'note)))
1514 ;; FIXME: document
1515 (defcustom org-log-note-clock-out nil
1516 "Non-nil means, recored a note when clocking out of an item.
1517 This can also be configured on a per-file basis by adding one of
1518 the following lines anywhere in the buffer:
1520 #+STARTUP: lognoteclock-out
1521 #+STARTUP: nolognoteclock-out"
1522 :group 'org-todo
1523 :group 'org-progress
1524 :type 'boolean)
1526 (defcustom org-log-done-with-time t
1527 "Non-nil means, the CLOSED time stamp will contain date and time.
1528 When nil, only the date will be recorded."
1529 :group 'org-progress
1530 :type 'boolean)
1532 (defcustom org-log-note-headings
1533 '((done . "CLOSING NOTE %t")
1534 (state . "State %-12s %t")
1535 (note . "Note taken on %t")
1536 (clock-out . ""))
1537 "Headings for notes added to entries.
1538 The value is an alist, with the car being a symbol indicating the note
1539 context, and the cdr is the heading to be used. The heading may also be the
1540 empty string.
1541 %t in the heading will be replaced by a time stamp.
1542 %s will be replaced by the new TODO state, in double quotes.
1543 %u will be replaced by the user name.
1544 %U will be replaced by the full user name."
1545 :group 'org-todo
1546 :group 'org-progress
1547 :type '(list :greedy t
1548 (cons (const :tag "Heading when closing an item" done) string)
1549 (cons (const :tag
1550 "Heading when changing todo state (todo sequence only)"
1551 state) string)
1552 (cons (const :tag "Heading when just taking a note" note) string)
1553 (cons (const :tag "Heading when clocking out" clock-out) string)))
1555 (unless (assq 'note org-log-note-headings)
1556 (push '(note . "%t") org-log-note-headings))
1558 (defcustom org-log-states-order-reversed t
1559 "Non-nil means, the latest state change note will be directly after heading.
1560 When nil, the notes will be orderer according to time."
1561 :group 'org-todo
1562 :group 'org-progress
1563 :type 'boolean)
1565 (defcustom org-log-repeat 'time
1566 "Non-nil means, record moving through the DONE state when triggering repeat.
1567 An auto-repeating tasks is immediately switched back to TODO when marked
1568 done. If you are not logging state changes (by adding \"@\" or \"!\" to
1569 the TODO keyword definition, or recording a cloing note by setting
1570 `org-log-done', there will be no record of the task moving trhough DONE.
1571 This variable forces taking a note anyway. Possible values are:
1573 nil Don't force a record
1574 time Record a time stamp
1575 note Record a note
1577 This option can also be set with on a per-file-basis with
1579 #+STARTUP: logrepeat
1580 #+STARTUP: lognoterepeat
1581 #+STARTUP: nologrepeat
1583 You can have local logging settings for a subtree by setting the LOGGING
1584 property to one or more of these keywords."
1585 :group 'org-todo
1586 :group 'org-progress
1587 :type '(choice
1588 (const :tag "Don't force a record" nil)
1589 (const :tag "Force recording the DONE state" time)
1590 (const :tag "Force recording a note with the DONE state" note)))
1592 (defcustom org-clock-into-drawer 2
1593 "Should clocking info be wrapped into a drawer?
1594 When t, clocking info will always be inserted into a :CLOCK: drawer.
1595 If necessary, the drawer will be created.
1596 When nil, the drawer will not be created, but used when present.
1597 When an integer and the number of clocking entries in an item
1598 reaches or exceeds this number, a drawer will be created."
1599 :group 'org-todo
1600 :group 'org-progress
1601 :type '(choice
1602 (const :tag "Always" t)
1603 (const :tag "Only when drawer exists" nil)
1604 (integer :tag "When at least N clock entries")))
1606 (defcustom org-clock-out-when-done t
1607 "When t, the clock will be stopped when the relevant entry is marked DONE.
1608 Nil means, clock will keep running until stopped explicitly with
1609 `C-c C-x C-o', or until the clock is started in a different item."
1610 :group 'org-progress
1611 :type 'boolean)
1613 (defcustom org-clock-in-switch-to-state nil
1614 "Set task to a special todo state while clocking it.
1615 The value should be the state to which the entry should be switched."
1616 :group 'org-progress
1617 :group 'org-todo
1618 :type '(choice
1619 (const :tag "Don't force a state" nil)
1620 (string :tag "State")))
1622 (defgroup org-priorities nil
1623 "Priorities in Org-mode."
1624 :tag "Org Priorities"
1625 :group 'org-todo)
1627 (defcustom org-highest-priority ?A
1628 "The highest priority of TODO items. A character like ?A, ?B etc.
1629 Must have a smaller ASCII number than `org-lowest-priority'."
1630 :group 'org-priorities
1631 :type 'character)
1633 (defcustom org-lowest-priority ?C
1634 "The lowest priority of TODO items. A character like ?A, ?B etc.
1635 Must have a larger ASCII number than `org-highest-priority'."
1636 :group 'org-priorities
1637 :type 'character)
1639 (defcustom org-default-priority ?B
1640 "The default priority of TODO items.
1641 This is the priority an item get if no explicit priority is given."
1642 :group 'org-priorities
1643 :type 'character)
1645 (defcustom org-priority-start-cycle-with-default t
1646 "Non-nil means, start with default priority when starting to cycle.
1647 When this is nil, the first step in the cycle will be (depending on the
1648 command used) one higher or lower that the default priority."
1649 :group 'org-priorities
1650 :type 'boolean)
1652 (defgroup org-time nil
1653 "Options concerning time stamps and deadlines in Org-mode."
1654 :tag "Org Time"
1655 :group 'org)
1657 (defcustom org-insert-labeled-timestamps-at-point nil
1658 "Non-nil means, SCHEDULED and DEADLINE timestamps are inserted at point.
1659 When nil, these labeled time stamps are forces into the second line of an
1660 entry, just after the headline. When scheduling from the global TODO list,
1661 the time stamp will always be forced into the second line."
1662 :group 'org-time
1663 :type 'boolean)
1665 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
1666 "Formats for `format-time-string' which are used for time stamps.
1667 It is not recommended to change this constant.")
1669 (defcustom org-time-stamp-rounding-minutes '(0 5)
1670 "Number of minutes to round time stamps to.
1671 These are two values, the first applies when first creating a time stamp.
1672 The second applies when changing it with the commands `S-up' and `S-down'.
1673 When changing the time stamp, this means that it will change in steps
1674 of N minutes, as given by the second value.
1676 When a setting is 0 or 1, insert the time unmodified. Useful rounding
1677 numbers should be factors of 60, so for example 5, 10, 15.
1679 When this is larger than 1, you can still force an exact time-stamp by using
1680 a double prefix argument to a time-stamp command like `C-c .' or `C-c !',
1681 and by using a prefix arg to `S-up/down' to specify the exact number
1682 of minutes to shift."
1683 :group 'org-time
1684 :get '(lambda (var) ; Make sure all entries have 5 elements
1685 (if (integerp (default-value var))
1686 (list (default-value var) 5)
1687 (default-value var)))
1688 :type '(list
1689 (integer :tag "when inserting times")
1690 (integer :tag "when modifying times")))
1692 ;; Make sure old customizations of this variable don't lead to problems.
1693 (when (integerp org-time-stamp-rounding-minutes)
1694 (setq org-time-stamp-rounding-minutes
1695 (list org-time-stamp-rounding-minutes
1696 org-time-stamp-rounding-minutes)))
1698 (defcustom org-display-custom-times nil
1699 "Non-nil means, overlay custom formats over all time stamps.
1700 The formats are defined through the variable `org-time-stamp-custom-formats'.
1701 To turn this on on a per-file basis, insert anywhere in the file:
1702 #+STARTUP: customtime"
1703 :group 'org-time
1704 :set 'set-default
1705 :type 'sexp)
1706 (make-variable-buffer-local 'org-display-custom-times)
1708 (defcustom org-time-stamp-custom-formats
1709 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
1710 "Custom formats for time stamps. See `format-time-string' for the syntax.
1711 These are overlayed over the default ISO format if the variable
1712 `org-display-custom-times' is set. Time like %H:%M should be at the
1713 end of the second format."
1714 :group 'org-time
1715 :type 'sexp)
1717 (defun org-time-stamp-format (&optional long inactive)
1718 "Get the right format for a time string."
1719 (let ((f (if long (cdr org-time-stamp-formats)
1720 (car org-time-stamp-formats))))
1721 (if inactive
1722 (concat "[" (substring f 1 -1) "]")
1723 f)))
1725 (defcustom org-deadline-warning-days 14
1726 "No. of days before expiration during which a deadline becomes active.
1727 This variable governs the display in sparse trees and in the agenda.
1728 When 0 or negative, it means use this number (the absolute value of it)
1729 even if a deadline has a different individual lead time specified."
1730 :group 'org-time
1731 :group 'org-agenda-daily/weekly
1732 :type 'number)
1734 (defcustom org-read-date-prefer-future t
1735 "Non-nil means, assume future for incomplete date input from user.
1736 This affects the following situations:
1737 1. The user gives a day, but no month.
1738 For example, if today is the 15th, and you enter \"3\", Org-mode will
1739 read this as the third of *next* month. However, if you enter \"17\",
1740 it will be considered as *this* month.
1741 2. The user gives a month but not a year.
1742 For example, if it is april and you enter \"feb 2\", this will be read
1743 as feb 2, *next* year. \"May 5\", however, will be this year.
1745 Currently this does not work for ISO week specifications.
1747 When this option is nil, the current month and year will always be used
1748 as defaults."
1749 :group 'org-time
1750 :type 'boolean)
1752 (defcustom org-read-date-display-live t
1753 "Non-nil means, display current interpretation of date prompt live.
1754 This display will be in an overlay, in the minibuffer."
1755 :group 'org-time
1756 :type 'boolean)
1758 (defcustom org-read-date-popup-calendar t
1759 "Non-nil means, pop up a calendar when prompting for a date.
1760 In the calendar, the date can be selected with mouse-1. However, the
1761 minibuffer will also be active, and you can simply enter the date as well.
1762 When nil, only the minibuffer will be available."
1763 :group 'org-time
1764 :type 'boolean)
1765 (if (fboundp 'defvaralias)
1766 (defvaralias 'org-popup-calendar-for-date-prompt
1767 'org-read-date-popup-calendar))
1769 (defcustom org-extend-today-until 0
1770 "The hour when your day really ends.
1771 This has influence for the following applications:
1772 - When switching the agenda to \"today\". It it is still earlier than
1773 the time given here, the day recognized as TODAY is actually yesterday.
1774 - When a date is read from the user and it is still before the time given
1775 here, the current date and time will be assumed to be yesterday, 23:59.
1777 FIXME:
1778 IMPORTANT: This is still a very experimental feature, it may disappear
1779 again or it may be extended to mean more things."
1780 :group 'org-time
1781 :type 'number)
1783 (defcustom org-edit-timestamp-down-means-later nil
1784 "Non-nil means, S-down will increase the time in a time stamp.
1785 When nil, S-up will increase."
1786 :group 'org-time
1787 :type 'boolean)
1789 (defcustom org-calendar-follow-timestamp-change t
1790 "Non-nil means, make the calendar window follow timestamp changes.
1791 When a timestamp is modified and the calendar window is visible, it will be
1792 moved to the new date."
1793 :group 'org-time
1794 :type 'boolean)
1796 (defcustom org-clock-heading-function nil
1797 "When non-nil, should be a function to create `org-clock-heading'.
1798 This is the string shown in the mode line when a clock is running.
1799 The function is called with point at the beginning of the headline."
1800 :group 'org-time ; FIXME: Should we have a separate group????
1801 :type 'function)
1803 (defgroup org-tags nil
1804 "Options concerning tags in Org-mode."
1805 :tag "Org Tags"
1806 :group 'org)
1808 (defcustom org-tag-alist nil
1809 "List of tags allowed in Org-mode files.
1810 When this list is nil, Org-mode will base TAG input on what is already in the
1811 buffer.
1812 The value of this variable is an alist, the car of each entry must be a
1813 keyword as a string, the cdr may be a character that is used to select
1814 that tag through the fast-tag-selection interface.
1815 See the manual for details."
1816 :group 'org-tags
1817 :type '(repeat
1818 (choice
1819 (cons (string :tag "Tag name")
1820 (character :tag "Access char"))
1821 (const :tag "Start radio group" (:startgroup))
1822 (const :tag "End radio group" (:endgroup)))))
1824 (defcustom org-use-fast-tag-selection 'auto
1825 "Non-nil means, use fast tag selection scheme.
1826 This is a special interface to select and deselect tags with single keys.
1827 When nil, fast selection is never used.
1828 When the symbol `auto', fast selection is used if and only if selection
1829 characters for tags have been configured, either through the variable
1830 `org-tag-alist' or through a #+TAGS line in the buffer.
1831 When t, fast selection is always used and selection keys are assigned
1832 automatically if necessary."
1833 :group 'org-tags
1834 :type '(choice
1835 (const :tag "Always" t)
1836 (const :tag "Never" nil)
1837 (const :tag "When selection characters are configured" 'auto)))
1839 (defcustom org-fast-tag-selection-single-key nil
1840 "Non-nil means, fast tag selection exits after first change.
1841 When nil, you have to press RET to exit it.
1842 During fast tag selection, you can toggle this flag with `C-c'.
1843 This variable can also have the value `expert'. In this case, the window
1844 displaying the tags menu is not even shown, until you press C-c again."
1845 :group 'org-tags
1846 :type '(choice
1847 (const :tag "No" nil)
1848 (const :tag "Yes" t)
1849 (const :tag "Expert" expert)))
1851 (defvar org-fast-tag-selection-include-todo nil
1852 "Non-nil means, fast tags selection interface will also offer TODO states.
1853 This is an undocumented feature, you should not rely on it.")
1855 (defcustom org-tags-column -80
1856 "The column to which tags should be indented in a headline.
1857 If this number is positive, it specifies the column. If it is negative,
1858 it means that the tags should be flushright to that column. For example,
1859 -80 works well for a normal 80 character screen."
1860 :group 'org-tags
1861 :type 'integer)
1863 (defcustom org-auto-align-tags t
1864 "Non-nil means, realign tags after pro/demotion of TODO state change.
1865 These operations change the length of a headline and therefore shift
1866 the tags around. With this options turned on, after each such operation
1867 the tags are again aligned to `org-tags-column'."
1868 :group 'org-tags
1869 :type 'boolean)
1871 (defcustom org-use-tag-inheritance t
1872 "Non-nil means, tags in levels apply also for sublevels.
1873 When nil, only the tags directly given in a specific line apply there.
1874 If you turn off this option, you very likely want to turn on the
1875 companion option `org-tags-match-list-sublevels'.
1877 This may also be a list of tags that should be inherited, or a regexp that
1878 matches tags that should be inherited."
1879 :group 'org-tags
1880 :type '(choice
1881 (const :tag "Not" nil)
1882 (const :tag "Always" t)
1883 (repeat :tag "Specific tags" (string :tag "Tag"))
1884 (regexp :tag "Tags matched by regexp")))
1886 (defun org-tag-inherit-p (tag)
1887 "Check if TAG is one that should be inherited."
1888 (cond
1889 ((eq org-use-tag-inheritance t) t)
1890 ((not org-use-tag-inheritance) nil)
1891 ((stringp org-use-tag-inheritance)
1892 (string-match org-use-tag-inheritance tag))
1893 ((listp org-use-tag-inheritance)
1894 (member tag org-use-tag-inheritance))
1895 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
1897 (defcustom org-tags-match-list-sublevels nil
1898 "Non-nil means list also sublevels of headlines matching tag search.
1899 Because of tag inheritance (see variable `org-use-tag-inheritance'),
1900 the sublevels of a headline matching a tag search often also match
1901 the same search. Listing all of them can create very long lists.
1902 Setting this variable to nil causes subtrees of a match to be skipped.
1903 This option is off by default, because inheritance in on. If you turn
1904 inheritance off, you very likely want to turn this option on.
1906 As a special case, if the tag search is restricted to TODO items, the
1907 value of this variable is ignored and sublevels are always checked, to
1908 make sure all corresponding TODO items find their way into the list."
1909 :group 'org-tags
1910 :type 'boolean)
1912 (defvar org-tags-history nil
1913 "History of minibuffer reads for tags.")
1914 (defvar org-last-tags-completion-table nil
1915 "The last used completion table for tags.")
1916 (defvar org-after-tags-change-hook nil
1917 "Hook that is run after the tags in a line have changed.")
1919 (defgroup org-properties nil
1920 "Options concerning properties in Org-mode."
1921 :tag "Org Properties"
1922 :group 'org)
1924 (defcustom org-property-format "%-10s %s"
1925 "How property key/value pairs should be formatted by `indent-line'.
1926 When `indent-line' hits a property definition, it will format the line
1927 according to this format, mainly to make sure that the values are
1928 lined-up with respect to each other."
1929 :group 'org-properties
1930 :type 'string)
1932 (defcustom org-use-property-inheritance nil
1933 "Non-nil means, properties apply also for sublevels.
1935 This setting is chiefly used during property searches. Turning it on can
1936 cause significant overhead when doing a search, which is why it is not
1937 on by default.
1939 When nil, only the properties directly given in the current entry count.
1940 When t, every property is inherited. The value may also be a list of
1941 properties that should have inheritance, or a regular expression matching
1942 properties that should be inherited.
1944 However, note that some special properties use inheritance under special
1945 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
1946 and the properties ending in \"_ALL\" when they are used as descriptor
1947 for valid values of a property.
1949 Note for programmers:
1950 When querying an entry with `org-entry-get', you can control if inheritance
1951 should be used. By default, `org-entry-get' looks only at the local
1952 properties. You can request inheritance by setting the inherit argument
1953 to t (to force inheritance) or to `selective' (to respect the setting
1954 in this variable)."
1955 :group 'org-properties
1956 :type '(choice
1957 (const :tag "Not" nil)
1958 (const :tag "Always" t)
1959 (repeat :tag "Specific properties" (string :tag "Property"))
1960 (regexp :tag "Properties matched by regexp")))
1962 (defun org-property-inherit-p (property)
1963 "Check if PROPERTY is one that should be inherited."
1964 (cond
1965 ((eq org-use-property-inheritance t) t)
1966 ((not org-use-property-inheritance) nil)
1967 ((stringp org-use-property-inheritance)
1968 (string-match org-use-property-inheritance property))
1969 ((listp org-use-property-inheritance)
1970 (member property org-use-property-inheritance))
1971 (t (error "Invalid setting of `org-use-property-inheritance'"))))
1973 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
1974 "The default column format, if no other format has been defined.
1975 This variable can be set on the per-file basis by inserting a line
1977 #+COLUMNS: %25ITEM ....."
1978 :group 'org-properties
1979 :type 'string)
1981 (defcustom org-global-properties nil
1982 "List of property/value pairs that can be inherited by any entry.
1983 You can set buffer-local values for this by adding lines like
1985 #+PROPERTY: NAME VALUE"
1986 :group 'org-properties
1987 :type '(repeat
1988 (cons (string :tag "Property")
1989 (string :tag "Value"))))
1991 (defvar org-local-properties nil
1992 "List of property/value pairs that can be inherited by any entry.
1993 Valid for the current buffer.
1994 This variable is populated from #+PROPERTY lines.")
1996 (defgroup org-agenda nil
1997 "Options concerning agenda views in Org-mode."
1998 :tag "Org Agenda"
1999 :group 'org)
2001 (defvar org-category nil
2002 "Variable used by org files to set a category for agenda display.
2003 Such files should use a file variable to set it, for example
2005 # -*- mode: org; org-category: \"ELisp\"
2007 or contain a special line
2009 #+CATEGORY: ELisp
2011 If the file does not specify a category, then file's base name
2012 is used instead.")
2013 (make-variable-buffer-local 'org-category)
2015 (defcustom org-agenda-files nil
2016 "The files to be used for agenda display.
2017 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
2018 \\[org-remove-file]. You can also use customize to edit the list.
2020 If an entry is a directory, all files in that directory that are matched by
2021 `org-agenda-file-regexp' will be part of the file list.
2023 If the value of the variable is not a list but a single file name, then
2024 the list of agenda files is actually stored and maintained in that file, one
2025 agenda file per line."
2026 :group 'org-agenda
2027 :type '(choice
2028 (repeat :tag "List of files and directories" file)
2029 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
2031 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
2032 "Regular expression to match files for `org-agenda-files'.
2033 If any element in the list in that variable contains a directory instead
2034 of a normal file, all files in that directory that are matched by this
2035 regular expression will be included."
2036 :group 'org-agenda
2037 :type 'regexp)
2039 (defcustom org-agenda-text-search-extra-files nil
2040 "List of extra files to be searched by text search commands.
2041 These files will be search in addition to the agenda files bu the
2042 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
2043 Note that these files will only be searched for text search commands,
2044 not for the other agenda views like todo lists, tag earches or the weekly
2045 agenda. This variable is intended to list notes and possibly archive files
2046 that should also be searched by these two commands."
2047 :group 'org-agenda
2048 :type '(repeat file))
2050 (if (fboundp 'defvaralias)
2051 (defvaralias 'org-agenda-multi-occur-extra-files
2052 'org-agenda-text-search-extra-files))
2054 (defcustom org-agenda-skip-unavailable-files nil
2055 "t means to just skip non-reachable files in `org-agenda-files'.
2056 Nil means to remove them, after a query, from the list."
2057 :group 'org-agenda
2058 :type 'boolean)
2060 (defcustom org-calendar-to-agenda-key [?c]
2061 "The key to be installed in `calendar-mode-map' for switching to the agenda.
2062 The command `org-calendar-goto-agenda' will be bound to this key. The
2063 default is the character `c' because then `c' can be used to switch back and
2064 forth between agenda and calendar."
2065 :group 'org-agenda
2066 :type 'sexp)
2068 (eval-after-load "calendar"
2069 '(org-defkey calendar-mode-map org-calendar-to-agenda-key
2070 'org-calendar-goto-agenda))
2072 (defgroup org-latex nil
2073 "Options for embedding LaTeX code into Org-mode."
2074 :tag "Org LaTeX"
2075 :group 'org)
2077 (defcustom org-format-latex-options
2078 '(:foreground default :background default :scale 1.0
2079 :html-foreground "Black" :html-background "Transparent" :html-scale 1.0
2080 :matchers ("begin" "$" "$$" "\\(" "\\["))
2081 "Options for creating images from LaTeX fragments.
2082 This is a property list with the following properties:
2083 :foreground the foreground color for images embedded in emacs, e.g. \"Black\".
2084 `default' means use the forground of the default face.
2085 :background the background color, or \"Transparent\".
2086 `default' means use the background of the default face.
2087 :scale a scaling factor for the size of the images
2088 :html-foreground, :html-background, :html-scale
2089 The same numbers for HTML export.
2090 :matchers a list indicating which matchers should be used to
2091 find LaTeX fragments. Valid members of this list are:
2092 \"begin\" find environments
2093 \"$\" find math expressions surrounded by $...$
2094 \"$$\" find math expressions surrounded by $$....$$
2095 \"\\(\" find math expressions surrounded by \\(...\\)
2096 \"\\ [\" find math expressions surrounded by \\ [...\\]"
2097 :group 'org-latex
2098 :type 'plist)
2100 (defcustom org-format-latex-header "\\documentclass{article}
2101 \\usepackage{fullpage} % do not remove
2102 \\usepackage{amssymb}
2103 \\usepackage[usenames]{color}
2104 \\usepackage{amsmath}
2105 \\usepackage{latexsym}
2106 \\usepackage[mathscr]{eucal}
2107 \\pagestyle{empty} % do not remove"
2108 "The document header used for processing LaTeX fragments."
2109 :group 'org-latex
2110 :type 'string)
2113 (defgroup org-font-lock nil
2114 "Font-lock settings for highlighting in Org-mode."
2115 :tag "Org Font Lock"
2116 :group 'org)
2118 (defcustom org-level-color-stars-only nil
2119 "Non-nil means fontify only the stars in each headline.
2120 When nil, the entire headline is fontified.
2121 Changing it requires restart of `font-lock-mode' to become effective
2122 also in regions already fontified."
2123 :group 'org-font-lock
2124 :type 'boolean)
2126 (defcustom org-hide-leading-stars nil
2127 "Non-nil means, hide the first N-1 stars in a headline.
2128 This works by using the face `org-hide' for these stars. This
2129 face is white for a light background, and black for a dark
2130 background. You may have to customize the face `org-hide' to
2131 make this work.
2132 Changing it requires restart of `font-lock-mode' to become effective
2133 also in regions already fontified.
2134 You may also set this on a per-file basis by adding one of the following
2135 lines to the buffer:
2137 #+STARTUP: hidestars
2138 #+STARTUP: showstars"
2139 :group 'org-font-lock
2140 :type 'boolean)
2142 (defcustom org-fontify-done-headline nil
2143 "Non-nil means, change the face of a headline if it is marked DONE.
2144 Normally, only the TODO/DONE keyword indicates the state of a headline.
2145 When this is non-nil, the headline after the keyword is set to the
2146 `org-headline-done' as an additional indication."
2147 :group 'org-font-lock
2148 :type 'boolean)
2150 (defcustom org-fontify-emphasized-text t
2151 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
2152 Changing this variable requires a restart of Emacs to take effect."
2153 :group 'org-font-lock
2154 :type 'boolean)
2156 (defcustom org-highlight-latex-fragments-and-specials nil
2157 "Non-nil means, fontify what is treated specially by the exporters."
2158 :group 'org-font-lock
2159 :type 'boolean)
2161 (defcustom org-hide-emphasis-markers nil
2162 "Non-nil mean font-lock should hide the emphasis marker characters."
2163 :group 'org-font-lock
2164 :type 'boolean)
2166 (defvar org-emph-re nil
2167 "Regular expression for matching emphasis.")
2168 (defvar org-verbatim-re nil
2169 "Regular expression for matching verbatim text.")
2170 (defvar org-emphasis-regexp-components) ; defined just below
2171 (defvar org-emphasis-alist) ; defined just below
2172 (defun org-set-emph-re (var val)
2173 "Set variable and compute the emphasis regular expression."
2174 (set var val)
2175 (when (and (boundp 'org-emphasis-alist)
2176 (boundp 'org-emphasis-regexp-components)
2177 org-emphasis-alist org-emphasis-regexp-components)
2178 (let* ((e org-emphasis-regexp-components)
2179 (pre (car e))
2180 (post (nth 1 e))
2181 (border (nth 2 e))
2182 (body (nth 3 e))
2183 (nl (nth 4 e))
2184 (stacked (and nil (nth 5 e))) ; stacked is no longer allowed, forced to nil
2185 (body1 (concat body "*?"))
2186 (markers (mapconcat 'car org-emphasis-alist ""))
2187 (vmarkers (mapconcat
2188 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
2189 org-emphasis-alist "")))
2190 ;; make sure special characters appear at the right position in the class
2191 (if (string-match "\\^" markers)
2192 (setq markers (concat (replace-match "" t t markers) "^")))
2193 (if (string-match "-" markers)
2194 (setq markers (concat (replace-match "" t t markers) "-")))
2195 (if (string-match "\\^" vmarkers)
2196 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
2197 (if (string-match "-" vmarkers)
2198 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
2199 (if (> nl 0)
2200 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
2201 (int-to-string nl) "\\}")))
2202 ;; Make the regexp
2203 (setq org-emph-re
2204 (concat "\\([" pre (if (and nil stacked) markers) "]\\|^\\)"
2205 "\\("
2206 "\\([" markers "]\\)"
2207 "\\("
2208 "[^" border "]\\|"
2209 "[^" border (if (and nil stacked) markers) "]"
2210 body1
2211 "[^" border (if (and nil stacked) markers) "]"
2212 "\\)"
2213 "\\3\\)"
2214 "\\([" post (if (and nil stacked) markers) "]\\|$\\)"))
2215 (setq org-verbatim-re
2216 (concat "\\([" pre "]\\|^\\)"
2217 "\\("
2218 "\\([" vmarkers "]\\)"
2219 "\\("
2220 "[^" border "]\\|"
2221 "[^" border "]"
2222 body1
2223 "[^" border "]"
2224 "\\)"
2225 "\\3\\)"
2226 "\\([" post "]\\|$\\)")))))
2228 (defcustom org-emphasis-regexp-components
2229 '(" \t('\"" "- \t.,:?;'\")" " \t\r\n,\"'" "." 1)
2230 "Components used to build the regular expression for emphasis.
2231 This is a list with 6 entries. Terminology: In an emphasis string
2232 like \" *strong word* \", we call the initial space PREMATCH, the final
2233 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
2234 and \"trong wor\" is the body. The different components in this variable
2235 specify what is allowed/forbidden in each part:
2237 pre Chars allowed as prematch. Beginning of line will be allowed too.
2238 post Chars allowed as postmatch. End of line will be allowed too.
2239 border The chars *forbidden* as border characters.
2240 body-regexp A regexp like \".\" to match a body character. Don't use
2241 non-shy groups here, and don't allow newline here.
2242 newline The maximum number of newlines allowed in an emphasis exp.
2244 Use customize to modify this, or restart Emacs after changing it."
2245 :group 'org-font-lock
2246 :set 'org-set-emph-re
2247 :type '(list
2248 (sexp :tag "Allowed chars in pre ")
2249 (sexp :tag "Allowed chars in post ")
2250 (sexp :tag "Forbidden chars in border ")
2251 (sexp :tag "Regexp for body ")
2252 (integer :tag "number of newlines allowed")
2253 (option (boolean :tag "Stacking (DISABLED) "))))
2255 (defcustom org-emphasis-alist
2256 '(("*" bold "<b>" "</b>")
2257 ("/" italic "<i>" "</i>")
2258 ("_" underline "<u>" "</u>")
2259 ("=" org-code "<code>" "</code>" verbatim)
2260 ("~" org-verbatim "" "" verbatim)
2261 ("+" (:strike-through t) "<del>" "</del>")
2263 "Special syntax for emphasized text.
2264 Text starting and ending with a special character will be emphasized, for
2265 example *bold*, _underlined_ and /italic/. This variable sets the marker
2266 characters, the face to be used by font-lock for highlighting in Org-mode
2267 Emacs buffers, and the HTML tags to be used for this.
2268 Use customize to modify this, or restart Emacs after changing it."
2269 :group 'org-font-lock
2270 :set 'org-set-emph-re
2271 :type '(repeat
2272 (list
2273 (string :tag "Marker character")
2274 (choice
2275 (face :tag "Font-lock-face")
2276 (plist :tag "Face property list"))
2277 (string :tag "HTML start tag")
2278 (string :tag "HTML end tag")
2279 (option (const verbatim)))))
2281 ;;; The faces
2283 (defgroup org-faces nil
2284 "Faces in Org-mode."
2285 :tag "Org Faces"
2286 :group 'org-font-lock)
2288 (defface org-hide
2289 '((((background light)) (:foreground "white"))
2290 (((background dark)) (:foreground "black")))
2291 "Face used to hide leading stars in headlines.
2292 The forground color of this face should be equal to the background
2293 color of the frame."
2294 :group 'org-faces)
2296 (defface org-level-1 ;; font-lock-function-name-face
2297 (org-compatible-face 'outline-1
2298 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
2299 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
2300 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
2301 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
2302 (((class color) (min-colors 8)) (:foreground "blue" :bold t))
2303 (t (:bold t))))
2304 "Face used for level 1 headlines."
2305 :group 'org-faces)
2307 (defface org-level-2 ;; font-lock-variable-name-face
2308 (org-compatible-face 'outline-2
2309 '((((class color) (min-colors 16) (background light)) (:foreground "DarkGoldenrod"))
2310 (((class color) (min-colors 16) (background dark)) (:foreground "LightGoldenrod"))
2311 (((class color) (min-colors 8) (background light)) (:foreground "yellow"))
2312 (((class color) (min-colors 8) (background dark)) (:foreground "yellow" :bold t))
2313 (t (:bold t))))
2314 "Face used for level 2 headlines."
2315 :group 'org-faces)
2317 (defface org-level-3 ;; font-lock-keyword-face
2318 (org-compatible-face 'outline-3
2319 '((((class color) (min-colors 88) (background light)) (:foreground "Purple"))
2320 (((class color) (min-colors 88) (background dark)) (:foreground "Cyan1"))
2321 (((class color) (min-colors 16) (background light)) (:foreground "Purple"))
2322 (((class color) (min-colors 16) (background dark)) (:foreground "Cyan"))
2323 (((class color) (min-colors 8) (background light)) (:foreground "purple" :bold t))
2324 (((class color) (min-colors 8) (background dark)) (:foreground "cyan" :bold t))
2325 (t (:bold t))))
2326 "Face used for level 3 headlines."
2327 :group 'org-faces)
2329 (defface org-level-4 ;; font-lock-comment-face
2330 (org-compatible-face 'outline-4
2331 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
2332 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
2333 (((class color) (min-colors 16) (background light)) (:foreground "red"))
2334 (((class color) (min-colors 16) (background dark)) (:foreground "red1"))
2335 (((class color) (min-colors 8) (background light)) (:foreground "red" :bold t))
2336 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
2337 (t (:bold t))))
2338 "Face used for level 4 headlines."
2339 :group 'org-faces)
2341 (defface org-level-5 ;; font-lock-type-face
2342 (org-compatible-face 'outline-5
2343 '((((class color) (min-colors 16) (background light)) (:foreground "ForestGreen"))
2344 (((class color) (min-colors 16) (background dark)) (:foreground "PaleGreen"))
2345 (((class color) (min-colors 8)) (:foreground "green"))))
2346 "Face used for level 5 headlines."
2347 :group 'org-faces)
2349 (defface org-level-6 ;; font-lock-constant-face
2350 (org-compatible-face 'outline-6
2351 '((((class color) (min-colors 16) (background light)) (:foreground "CadetBlue"))
2352 (((class color) (min-colors 16) (background dark)) (:foreground "Aquamarine"))
2353 (((class color) (min-colors 8)) (:foreground "magenta"))))
2354 "Face used for level 6 headlines."
2355 :group 'org-faces)
2357 (defface org-level-7 ;; font-lock-builtin-face
2358 (org-compatible-face 'outline-7
2359 '((((class color) (min-colors 16) (background light)) (:foreground "Orchid"))
2360 (((class color) (min-colors 16) (background dark)) (:foreground "LightSteelBlue"))
2361 (((class color) (min-colors 8)) (:foreground "blue"))))
2362 "Face used for level 7 headlines."
2363 :group 'org-faces)
2365 (defface org-level-8 ;; font-lock-string-face
2366 (org-compatible-face 'outline-8
2367 '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
2368 (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
2369 (((class color) (min-colors 8)) (:foreground "green"))))
2370 "Face used for level 8 headlines."
2371 :group 'org-faces)
2373 (defface org-special-keyword ;; font-lock-string-face
2374 (org-compatible-face nil
2375 '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
2376 (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
2377 (t (:italic t))))
2378 "Face used for special keywords."
2379 :group 'org-faces)
2381 (defface org-drawer ;; font-lock-function-name-face
2382 (org-compatible-face nil
2383 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
2384 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
2385 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
2386 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
2387 (((class color) (min-colors 8)) (:foreground "blue" :bold t))
2388 (t (:bold t))))
2389 "Face used for drawers."
2390 :group 'org-faces)
2392 (defface org-property-value nil
2393 "Face used for the value of a property."
2394 :group 'org-faces)
2396 (defface org-column
2397 (org-compatible-face nil
2398 '((((class color) (min-colors 16) (background light))
2399 (:background "grey90"))
2400 (((class color) (min-colors 16) (background dark))
2401 (:background "grey30"))
2402 (((class color) (min-colors 8))
2403 (:background "cyan" :foreground "black"))
2404 (t (:inverse-video t))))
2405 "Face for column display of entry properties."
2406 :group 'org-faces)
2408 (when (fboundp 'set-face-attribute)
2409 ;; Make sure that a fixed-width face is used when we have a column table.
2410 (set-face-attribute 'org-column nil
2411 :height (face-attribute 'default :height)
2412 :family (face-attribute 'default :family)))
2414 (defface org-warning
2415 (org-compatible-face 'font-lock-warning-face
2416 '((((class color) (min-colors 16) (background light)) (:foreground "Red1" :bold t))
2417 (((class color) (min-colors 16) (background dark)) (:foreground "Pink" :bold t))
2418 (((class color) (min-colors 8) (background light)) (:foreground "red" :bold t))
2419 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
2420 (t (:bold t))))
2421 "Face for deadlines and TODO keywords."
2422 :group 'org-faces)
2424 (defface org-archived ; similar to shadow
2425 (org-compatible-face 'shadow
2426 '((((class color grayscale) (min-colors 88) (background light))
2427 (:foreground "grey50"))
2428 (((class color grayscale) (min-colors 88) (background dark))
2429 (:foreground "grey70"))
2430 (((class color) (min-colors 8) (background light))
2431 (:foreground "green"))
2432 (((class color) (min-colors 8) (background dark))
2433 (:foreground "yellow"))))
2434 "Face for headline with the ARCHIVE tag."
2435 :group 'org-faces)
2437 (defface org-link
2438 '((((class color) (background light)) (:foreground "Purple" :underline t))
2439 (((class color) (background dark)) (:foreground "Cyan" :underline t))
2440 (t (:underline t)))
2441 "Face for links."
2442 :group 'org-faces)
2444 (defface org-ellipsis
2445 '((((class color) (background light)) (:foreground "DarkGoldenrod" :underline t))
2446 (((class color) (background dark)) (:foreground "LightGoldenrod" :underline t))
2447 (t (:strike-through t)))
2448 "Face for the ellipsis in folded text."
2449 :group 'org-faces)
2451 (defface org-target
2452 '((((class color) (background light)) (:underline t))
2453 (((class color) (background dark)) (:underline t))
2454 (t (:underline t)))
2455 "Face for links."
2456 :group 'org-faces)
2458 (defface org-date
2459 '((((class color) (background light)) (:foreground "Purple" :underline t))
2460 (((class color) (background dark)) (:foreground "Cyan" :underline t))
2461 (t (:underline t)))
2462 "Face for links."
2463 :group 'org-faces)
2465 (defface org-sexp-date
2466 '((((class color) (background light)) (:foreground "Purple"))
2467 (((class color) (background dark)) (:foreground "Cyan"))
2468 (t (:underline t)))
2469 "Face for links."
2470 :group 'org-faces)
2472 (defface org-tag
2473 '((t (:bold t)))
2474 "Face for tags."
2475 :group 'org-faces)
2477 (defface org-todo ; font-lock-warning-face
2478 (org-compatible-face nil
2479 '((((class color) (min-colors 16) (background light)) (:foreground "Red1" :bold t))
2480 (((class color) (min-colors 16) (background dark)) (:foreground "Pink" :bold t))
2481 (((class color) (min-colors 8) (background light)) (:foreground "red" :bold t))
2482 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
2483 (t (:inverse-video t :bold t))))
2484 "Face for TODO keywords."
2485 :group 'org-faces)
2487 (defface org-done ;; font-lock-type-face
2488 (org-compatible-face nil
2489 '((((class color) (min-colors 16) (background light)) (:foreground "ForestGreen" :bold t))
2490 (((class color) (min-colors 16) (background dark)) (:foreground "PaleGreen" :bold t))
2491 (((class color) (min-colors 8)) (:foreground "green"))
2492 (t (:bold t))))
2493 "Face used for todo keywords that indicate DONE items."
2494 :group 'org-faces)
2496 (defface org-headline-done ;; font-lock-string-face
2497 (org-compatible-face nil
2498 '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
2499 (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
2500 (((class color) (min-colors 8) (background light)) (:bold nil))))
2501 "Face used to indicate that a headline is DONE.
2502 This face is only used if `org-fontify-done-headline' is set. If applies
2503 to the part of the headline after the DONE keyword."
2504 :group 'org-faces)
2506 (defcustom org-todo-keyword-faces nil
2507 "Faces for specific TODO keywords.
2508 This is a list of cons cells, with TODO keywords in the car
2509 and faces in the cdr. The face can be a symbol, or a property
2510 list of attributes, like (:foreground \"blue\" :weight bold :underline t)."
2511 :group 'org-faces
2512 :group 'org-todo
2513 :type '(repeat
2514 (cons
2515 (string :tag "keyword")
2516 (sexp :tag "face"))))
2518 (defface org-table ;; font-lock-function-name-face
2519 (org-compatible-face nil
2520 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
2521 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
2522 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
2523 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
2524 (((class color) (min-colors 8) (background light)) (:foreground "blue"))
2525 (((class color) (min-colors 8) (background dark)))))
2526 "Face used for tables."
2527 :group 'org-faces)
2529 (defface org-formula
2530 (org-compatible-face nil
2531 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
2532 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
2533 (((class color) (min-colors 8) (background light)) (:foreground "red"))
2534 (((class color) (min-colors 8) (background dark)) (:foreground "red"))
2535 (t (:bold t :italic t))))
2536 "Face for formulas."
2537 :group 'org-faces)
2539 (defface org-code
2540 (org-compatible-face nil
2541 '((((class color grayscale) (min-colors 88) (background light))
2542 (:foreground "grey50"))
2543 (((class color grayscale) (min-colors 88) (background dark))
2544 (:foreground "grey70"))
2545 (((class color) (min-colors 8) (background light))
2546 (:foreground "green"))
2547 (((class color) (min-colors 8) (background dark))
2548 (:foreground "yellow"))))
2549 "Face for fixed-with text like code snippets."
2550 :group 'org-faces
2551 :version "22.1")
2553 (defface org-verbatim
2554 (org-compatible-face nil
2555 '((((class color grayscale) (min-colors 88) (background light))
2556 (:foreground "grey50" :underline t))
2557 (((class color grayscale) (min-colors 88) (background dark))
2558 (:foreground "grey70" :underline t))
2559 (((class color) (min-colors 8) (background light))
2560 (:foreground "green" :underline t))
2561 (((class color) (min-colors 8) (background dark))
2562 (:foreground "yellow" :underline t))))
2563 "Face for fixed-with text like code snippets."
2564 :group 'org-faces
2565 :version "22.1")
2567 (defface org-agenda-structure ;; font-lock-function-name-face
2568 (org-compatible-face nil
2569 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
2570 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
2571 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
2572 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
2573 (((class color) (min-colors 8)) (:foreground "blue" :bold t))
2574 (t (:bold t))))
2575 "Face used in agenda for captions and dates."
2576 :group 'org-faces)
2578 (defface org-scheduled-today
2579 (org-compatible-face nil
2580 '((((class color) (min-colors 88) (background light)) (:foreground "DarkGreen"))
2581 (((class color) (min-colors 88) (background dark)) (:foreground "PaleGreen"))
2582 (((class color) (min-colors 8)) (:foreground "green"))
2583 (t (:bold t :italic t))))
2584 "Face for items scheduled for a certain day."
2585 :group 'org-faces)
2587 (defface org-scheduled-previously
2588 (org-compatible-face nil
2589 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
2590 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
2591 (((class color) (min-colors 8) (background light)) (:foreground "red"))
2592 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
2593 (t (:bold t))))
2594 "Face for items scheduled previously, and not yet done."
2595 :group 'org-faces)
2597 (defface org-upcoming-deadline
2598 (org-compatible-face nil
2599 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
2600 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
2601 (((class color) (min-colors 8) (background light)) (:foreground "red"))
2602 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
2603 (t (:bold t))))
2604 "Face for items scheduled previously, and not yet done."
2605 :group 'org-faces)
2607 (defcustom org-agenda-deadline-faces
2608 '((1.0 . org-warning)
2609 (0.5 . org-upcoming-deadline)
2610 (0.0 . default))
2611 "Faces for showing deadlines in the agenda.
2612 This is a list of cons cells. The cdr of each cell is a face to be used,
2613 and it can also just be like '(:foreground \"yellow\").
2614 Each car is a fraction of the head-warning time that must have passed for
2615 this the face in the cdr to be used for display. The numbers must be
2616 given in descending order. The head-warning time is normally taken
2617 from `org-deadline-warning-days', but can also be specified in the deadline
2618 timestamp itself, like this:
2620 DEADLINE: <2007-08-13 Mon -8d>
2622 You may use d for days, w for weeks, m for months and y for years. Months
2623 and years will only be treated in an approximate fashion (30.4 days for a
2624 month and 365.24 days for a year)."
2625 :group 'org-faces
2626 :group 'org-agenda-daily/weekly
2627 :type '(repeat
2628 (cons
2629 (number :tag "Fraction of head-warning time passed")
2630 (sexp :tag "Face"))))
2632 ;; FIXME: this is not a good face yet.
2633 (defface org-agenda-restriction-lock
2634 (org-compatible-face nil
2635 '((((class color) (min-colors 88) (background light)) (:background "yellow1"))
2636 (((class color) (min-colors 88) (background dark)) (:background "skyblue4"))
2637 (((class color) (min-colors 16) (background light)) (:background "yellow1"))
2638 (((class color) (min-colors 16) (background dark)) (:background "skyblue4"))
2639 (((class color) (min-colors 8)) (:background "cyan" :foreground "black"))
2640 (t (:inverse-video t))))
2641 "Face for showing the agenda restriction lock."
2642 :group 'org-faces)
2644 (defface org-time-grid ;; font-lock-variable-name-face
2645 (org-compatible-face nil
2646 '((((class color) (min-colors 16) (background light)) (:foreground "DarkGoldenrod"))
2647 (((class color) (min-colors 16) (background dark)) (:foreground "LightGoldenrod"))
2648 (((class color) (min-colors 8)) (:foreground "yellow" :weight light))))
2649 "Face used for time grids."
2650 :group 'org-faces)
2652 (defconst org-level-faces
2653 '(org-level-1 org-level-2 org-level-3 org-level-4
2654 org-level-5 org-level-6 org-level-7 org-level-8
2657 (defcustom org-n-level-faces (length org-level-faces)
2658 "The number of different faces to be used for headlines.
2659 Org-mode defines 8 different headline faces, so this can be at most 8.
2660 If it is less than 8, the level-1 face gets re-used for level N+1 etc."
2661 :type 'number
2662 :group 'org-faces)
2664 ;;; Functions and variables from ther packages
2665 ;; Declared here to avoid compiler warnings
2667 ;; XEmacs only
2668 (defvar outline-mode-menu-heading)
2669 (defvar outline-mode-menu-show)
2670 (defvar outline-mode-menu-hide)
2671 (defvar zmacs-regions) ; XEmacs regions
2673 ;; Emacs only
2674 (defvar mark-active)
2676 ;; Various packages
2677 ;; FIXME: get the argument lists for the UNKNOWN stuff
2678 (declare-function bibtex-beginning-of-entry "bibtex" ())
2679 (declare-function bibtex-generate-autokey "bibtex" ())
2680 (declare-function bibtex-parse-entry "bibtex" (&optional content))
2681 (declare-function bibtex-url "bibtex" (&optional pos no-browse))
2682 (declare-function calendar-absolute-from-iso "cal-iso" (&optional date))
2683 (declare-function calendar-forward-day "cal-move" (arg))
2684 (declare-function calendar-goto-date "cal-move" (date))
2685 (declare-function calendar-goto-today "cal-move" ())
2686 (declare-function calendar-iso-from-absolute "cal-iso" (&optional date))
2687 (defvar calc-embedded-close-formula)
2688 (defvar calc-embedded-open-formula)
2689 (declare-function cdlatex-tab "ext:cdlatex" ())
2690 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
2691 (defvar font-lock-unfontify-region-function)
2692 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
2693 (declare-function org-agenda-skip "org-agenda" ())
2694 (declare-function org-format-agenda-item "org-agenda"
2695 (extra txt &optional category tags dotime noprefix remove-re))
2696 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
2697 (declare-function org-agenda-change-all-lines "org-agenda"
2698 (newhead hdmarker &optional fixface))
2699 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
2700 (declare-function org-agenda-maybe-redo "org-agenda" ())
2701 (declare-function parse-time-string "parse-time" (string))
2702 (declare-function remember "remember" (&optional initial))
2703 (declare-function remember-buffer-desc "remember" ())
2704 (declare-function remember-finalize "remember" ())
2705 (defvar remember-save-after-remembering)
2706 (defvar remember-data-file)
2707 (defvar remember-register)
2708 (defvar remember-buffer)
2709 (defvar remember-handler-functions)
2710 (defvar remember-annotation-functions)
2711 (defvar texmathp-why)
2712 (declare-function speedbar-line-directory "speedbar" (&optional depth))
2713 (declare-function table--at-cell-p "table" (position &optional object at-column))
2715 (defvar w3m-current-url)
2716 (defvar w3m-current-title)
2718 (defvar org-latex-regexps)
2720 ;;; Autoload and prepare some org modules
2722 ;; Some table stuff that needs to be defined here, because it is used
2723 ;; by the functions setting up org-mode or checking for table context.
2725 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
2726 "Detects an org-type or table-type table.")
2727 (defconst org-table-line-regexp "^[ \t]*|"
2728 "Detects an org-type table line.")
2729 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
2730 "Detects an org-type table line.")
2731 (defconst org-table-hline-regexp "^[ \t]*|-"
2732 "Detects an org-type table hline.")
2733 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
2734 "Detects a table-type table hline.")
2735 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
2736 "Searching from within a table (any type) this finds the first line
2737 outside the table.")
2739 ;; Autoload the functions in org-table.el that are needed by functions here.
2741 (eval-and-compile
2742 (org-autoload "org-table"
2743 '(org-table-align org-table-begin org-table-blank-field
2744 org-table-convert org-table-convert-region org-table-copy-down
2745 org-table-copy-region org-table-create
2746 org-table-create-or-convert-from-region
2747 org-table-create-with-table.el org-table-current-dline
2748 org-table-cut-region org-table-delete-column org-table-edit-field
2749 org-table-edit-formulas org-table-end org-table-eval-formula
2750 org-table-export org-table-field-info
2751 org-table-get-stored-formulas org-table-goto-column
2752 org-table-hline-and-move org-table-import org-table-insert-column
2753 org-table-insert-hline org-table-insert-row org-table-iterate
2754 org-table-justify-field-maybe org-table-kill-row
2755 org-table-maybe-eval-formula org-table-maybe-recalculate-line
2756 org-table-move-column org-table-move-column-left
2757 org-table-move-column-right org-table-move-row
2758 org-table-move-row-down org-table-move-row-up
2759 org-table-next-field org-table-next-row org-table-paste-rectangle
2760 org-table-previous-field org-table-recalculate
2761 org-table-rotate-recalc-marks org-table-sort-lines org-table-sum
2762 org-table-toggle-coordinate-overlays
2763 org-table-toggle-formula-debugger org-table-wrap-region
2764 orgtbl-mode turn-on-orgtbl)))
2766 (defun org-at-table-p (&optional table-type)
2767 "Return t if the cursor is inside an org-type table.
2768 If TABLE-TYPE is non-nil, also check for table.el-type tables."
2769 (if org-enable-table-editor
2770 (save-excursion
2771 (beginning-of-line 1)
2772 (looking-at (if table-type org-table-any-line-regexp
2773 org-table-line-regexp)))
2774 nil))
2775 (defsubst org-table-p () (org-at-table-p))
2777 (defun org-at-table.el-p ()
2778 "Return t if and only if we are at a table.el table."
2779 (and (org-at-table-p 'any)
2780 (save-excursion
2781 (goto-char (org-table-begin 'any))
2782 (looking-at org-table1-hline-regexp))))
2783 (defun org-table-recognize-table.el ()
2784 "If there is a table.el table nearby, recognize it and move into it."
2785 (if org-table-tab-recognizes-table.el
2786 (if (org-at-table.el-p)
2787 (progn
2788 (beginning-of-line 1)
2789 (if (looking-at org-table-dataline-regexp)
2791 (if (looking-at org-table1-hline-regexp)
2792 (progn
2793 (beginning-of-line 2)
2794 (if (looking-at org-table-any-border-regexp)
2795 (beginning-of-line -1)))))
2796 (if (re-search-forward "|" (org-table-end t) t)
2797 (progn
2798 (require 'table)
2799 (if (table--at-cell-p (point))
2801 (message "recognizing table.el table...")
2802 (table-recognize-table)
2803 (message "recognizing table.el table...done")))
2804 (error "This should not happen..."))
2806 nil)
2807 nil))
2809 (defun org-at-table-hline-p ()
2810 "Return t if the cursor is inside a hline in a table."
2811 (if org-enable-table-editor
2812 (save-excursion
2813 (beginning-of-line 1)
2814 (looking-at org-table-hline-regexp))
2815 nil))
2817 (defvar org-table-clean-did-remove-column nil)
2819 (defun org-table-map-tables (function)
2820 "Apply FUNCTION to the start of all tables in the buffer."
2821 (save-excursion
2822 (save-restriction
2823 (widen)
2824 (goto-char (point-min))
2825 (while (re-search-forward org-table-any-line-regexp nil t)
2826 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
2827 (beginning-of-line 1)
2828 (if (looking-at org-table-line-regexp)
2829 (save-excursion (funcall function)))
2830 (re-search-forward org-table-any-border-regexp nil 1))))
2831 (message "Mapping tables: done"))
2833 ;; Declare and autoload functions from org-exp.el
2835 (declare-function org-default-export-plist "org-exp")
2836 (declare-function org-infile-export-plist "org-exp")
2837 (declare-function org-get-current-options "org-exp")
2838 (eval-and-compile
2839 (org-autoload "org-exp"
2840 '(org-export org-export-as-ascii org-export-visible
2841 org-insert-export-options-template org-export-as-html-and-open
2842 org-export-as-html-batch org-export-as-html-to-buffer
2843 org-replace-region-by-html org-export-region-as-html
2844 org-export-as-html org-export-icalendar-this-file
2845 org-export-icalendar-all-agenda-files
2846 org-export-icalendar-combine-agenda-files org-export-as-xoxo)))
2848 ;; Autoload org-remember
2850 (eval-and-compile
2851 (org-autoload "org-remember"
2852 '(org-remember-insinuate org-remember-annotation
2853 org-remember-apply-template org-remember org-remember-handler)))
2855 ;;; Variables for pre-computed regular expressions, all buffer local
2857 (defvar org-drawer-regexp nil
2858 "Matches first line of a hidden block.")
2859 (make-variable-buffer-local 'org-drawer-regexp)
2860 (defvar org-todo-regexp nil
2861 "Matches any of the TODO state keywords.")
2862 (make-variable-buffer-local 'org-todo-regexp)
2863 (defvar org-not-done-regexp nil
2864 "Matches any of the TODO state keywords except the last one.")
2865 (make-variable-buffer-local 'org-not-done-regexp)
2866 (defvar org-todo-line-regexp nil
2867 "Matches a headline and puts TODO state into group 2 if present.")
2868 (make-variable-buffer-local 'org-todo-line-regexp)
2869 (defvar org-complex-heading-regexp nil
2870 "Matches a headline and puts everything into groups:
2871 group 1: the stars
2872 group 2: The todo keyword, maybe
2873 group 3: Priority cookie
2874 group 4: True headline
2875 group 5: Tags")
2876 (make-variable-buffer-local 'org-complex-heading-regexp)
2877 (defvar org-todo-line-tags-regexp nil
2878 "Matches a headline and puts TODO state into group 2 if present.
2879 Also put tags into group 4 if tags are present.")
2880 (make-variable-buffer-local 'org-todo-line-tags-regexp)
2881 (defvar org-nl-done-regexp nil
2882 "Matches newline followed by a headline with the DONE keyword.")
2883 (make-variable-buffer-local 'org-nl-done-regexp)
2884 (defvar org-looking-at-done-regexp nil
2885 "Matches the DONE keyword a point.")
2886 (make-variable-buffer-local 'org-looking-at-done-regexp)
2887 (defvar org-ds-keyword-length 12
2888 "Maximum length of the Deadline and SCHEDULED keywords.")
2889 (make-variable-buffer-local 'org-ds-keyword-length)
2890 (defvar org-deadline-regexp nil
2891 "Matches the DEADLINE keyword.")
2892 (make-variable-buffer-local 'org-deadline-regexp)
2893 (defvar org-deadline-time-regexp nil
2894 "Matches the DEADLINE keyword together with a time stamp.")
2895 (make-variable-buffer-local 'org-deadline-time-regexp)
2896 (defvar org-deadline-line-regexp nil
2897 "Matches the DEADLINE keyword and the rest of the line.")
2898 (make-variable-buffer-local 'org-deadline-line-regexp)
2899 (defvar org-scheduled-regexp nil
2900 "Matches the SCHEDULED keyword.")
2901 (make-variable-buffer-local 'org-scheduled-regexp)
2902 (defvar org-scheduled-time-regexp nil
2903 "Matches the SCHEDULED keyword together with a time stamp.")
2904 (make-variable-buffer-local 'org-scheduled-time-regexp)
2905 (defvar org-closed-time-regexp nil
2906 "Matches the CLOSED keyword together with a time stamp.")
2907 (make-variable-buffer-local 'org-closed-time-regexp)
2909 (defvar org-keyword-time-regexp nil
2910 "Matches any of the 4 keywords, together with the time stamp.")
2911 (make-variable-buffer-local 'org-keyword-time-regexp)
2912 (defvar org-keyword-time-not-clock-regexp nil
2913 "Matches any of the 3 keywords, together with the time stamp.")
2914 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
2915 (defvar org-maybe-keyword-time-regexp nil
2916 "Matches a timestamp, possibly preceeded by a keyword.")
2917 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
2918 (defvar org-planning-or-clock-line-re nil
2919 "Matches a line with planning or clock info.")
2920 (make-variable-buffer-local 'org-planning-or-clock-line-re)
2922 (defconst org-plain-time-of-day-regexp
2923 (concat
2924 "\\(\\<[012]?[0-9]"
2925 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
2926 "\\(--?"
2927 "\\(\\<[012]?[0-9]"
2928 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
2929 "\\)?")
2930 "Regular expression to match a plain time or time range.
2931 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
2932 groups carry important information:
2933 0 the full match
2934 1 the first time, range or not
2935 8 the second time, if it is a range.")
2937 (defconst org-plain-time-extension-regexp
2938 (concat
2939 "\\(\\<[012]?[0-9]"
2940 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
2941 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
2942 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
2943 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
2944 groups carry important information:
2945 0 the full match
2946 7 hours of duration
2947 9 minutes of duration")
2949 (defconst org-stamp-time-of-day-regexp
2950 (concat
2951 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
2952 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
2953 "\\(--?"
2954 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
2955 "Regular expression to match a timestamp time or time range.
2956 After a match, the following groups carry important information:
2957 0 the full match
2958 1 date plus weekday, for backreferencing to make sure both times on same day
2959 2 the first time, range or not
2960 4 the second time, if it is a range.")
2962 (defconst org-startup-options
2963 '(("fold" org-startup-folded t)
2964 ("overview" org-startup-folded t)
2965 ("nofold" org-startup-folded nil)
2966 ("showall" org-startup-folded nil)
2967 ("content" org-startup-folded content)
2968 ("hidestars" org-hide-leading-stars t)
2969 ("showstars" org-hide-leading-stars nil)
2970 ("odd" org-odd-levels-only t)
2971 ("oddeven" org-odd-levels-only nil)
2972 ("align" org-startup-align-all-tables t)
2973 ("noalign" org-startup-align-all-tables nil)
2974 ("customtime" org-display-custom-times t)
2975 ("logdone" org-log-done time)
2976 ("lognotedone" org-log-done note)
2977 ("nologdone" org-log-done nil)
2978 ("lognoteclock-out" org-log-note-clock-out t)
2979 ("nolognoteclock-out" org-log-note-clock-out nil)
2980 ("logrepeat" org-log-repeat state)
2981 ("lognoterepeat" org-log-repeat note)
2982 ("nologrepeat" org-log-repeat nil)
2983 ("constcgs" constants-unit-system cgs)
2984 ("constSI" constants-unit-system SI))
2985 "Variable associated with STARTUP options for org-mode.
2986 Each element is a list of three items: The startup options as written
2987 in the #+STARTUP line, the corresponding variable, and the value to
2988 set this variable to if the option is found. An optional forth element PUSH
2989 means to push this value onto the list in the variable.")
2991 (defun org-set-regexps-and-options ()
2992 "Precompute regular expressions for current buffer."
2993 (when (org-mode-p)
2994 (org-set-local 'org-todo-kwd-alist nil)
2995 (org-set-local 'org-todo-key-alist nil)
2996 (org-set-local 'org-todo-key-trigger nil)
2997 (org-set-local 'org-todo-keywords-1 nil)
2998 (org-set-local 'org-done-keywords nil)
2999 (org-set-local 'org-todo-heads nil)
3000 (org-set-local 'org-todo-sets nil)
3001 (org-set-local 'org-todo-log-states nil)
3002 (let ((re (org-make-options-regexp
3003 '("CATEGORY" "SEQ_TODO" "TYP_TODO" "TODO" "COLUMNS"
3004 "STARTUP" "ARCHIVE" "TAGS" "LINK" "PRIORITIES"
3005 "CONSTANTS" "PROPERTY" "DRAWERS")))
3006 (splitre "[ \t]+")
3007 kwds kws0 kwsa key log value cat arch tags const links hw dws
3008 tail sep kws1 prio props drawers)
3009 (save-excursion
3010 (save-restriction
3011 (widen)
3012 (goto-char (point-min))
3013 (while (re-search-forward re nil t)
3014 (setq key (match-string 1) value (org-match-string-no-properties 2))
3015 (cond
3016 ((equal key "CATEGORY")
3017 (if (string-match "[ \t]+$" value)
3018 (setq value (replace-match "" t t value)))
3019 (setq cat value))
3020 ((member key '("SEQ_TODO" "TODO"))
3021 (push (cons 'sequence (org-split-string value splitre)) kwds))
3022 ((equal key "TYP_TODO")
3023 (push (cons 'type (org-split-string value splitre)) kwds))
3024 ((equal key "TAGS")
3025 (setq tags (append tags (org-split-string value splitre))))
3026 ((equal key "COLUMNS")
3027 (org-set-local 'org-columns-default-format value))
3028 ((equal key "LINK")
3029 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
3030 (push (cons (match-string 1 value)
3031 (org-trim (match-string 2 value)))
3032 links)))
3033 ((equal key "PRIORITIES")
3034 (setq prio (org-split-string value " +")))
3035 ((equal key "PROPERTY")
3036 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
3037 (push (cons (match-string 1 value) (match-string 2 value))
3038 props)))
3039 ((equal key "DRAWERS")
3040 (setq drawers (org-split-string value splitre)))
3041 ((equal key "CONSTANTS")
3042 (setq const (append const (org-split-string value splitre))))
3043 ((equal key "STARTUP")
3044 (let ((opts (org-split-string value splitre))
3045 l var val)
3046 (while (setq l (pop opts))
3047 (when (setq l (assoc l org-startup-options))
3048 (setq var (nth 1 l) val (nth 2 l))
3049 (if (not (nth 3 l))
3050 (set (make-local-variable var) val)
3051 (if (not (listp (symbol-value var)))
3052 (set (make-local-variable var) nil))
3053 (set (make-local-variable var) (symbol-value var))
3054 (add-to-list var val))))))
3055 ((equal key "ARCHIVE")
3056 (string-match " *$" value)
3057 (setq arch (replace-match "" t t value))
3058 (remove-text-properties 0 (length arch)
3059 '(face t fontified t) arch)))
3061 (when cat
3062 (org-set-local 'org-category (intern cat))
3063 (push (cons "CATEGORY" cat) props))
3064 (when prio
3065 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
3066 (setq prio (mapcar 'string-to-char prio))
3067 (org-set-local 'org-highest-priority (nth 0 prio))
3068 (org-set-local 'org-lowest-priority (nth 1 prio))
3069 (org-set-local 'org-default-priority (nth 2 prio)))
3070 (and props (org-set-local 'org-local-properties (nreverse props)))
3071 (and drawers (org-set-local 'org-drawers drawers))
3072 (and arch (org-set-local 'org-archive-location arch))
3073 (and links (setq org-link-abbrev-alist-local (nreverse links)))
3074 ;; Process the TODO keywords
3075 (unless kwds
3076 ;; Use the global values as if they had been given locally.
3077 (setq kwds (default-value 'org-todo-keywords))
3078 (if (stringp (car kwds))
3079 (setq kwds (list (cons org-todo-interpretation
3080 (default-value 'org-todo-keywords)))))
3081 (setq kwds (reverse kwds)))
3082 (setq kwds (nreverse kwds))
3083 (let (inter kws kw)
3084 (while (setq kws (pop kwds))
3085 (setq inter (pop kws) sep (member "|" kws)
3086 kws0 (delete "|" (copy-sequence kws))
3087 kwsa nil
3088 kws1 (mapcar
3089 (lambda (x)
3090 ;; 1 2
3091 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
3092 (progn
3093 (setq kw (match-string 1 x)
3094 key (and (match-end 2) (match-string 2 x))
3095 log (org-extract-log-state-settings x))
3096 (push (cons kw (and key (string-to-char key))) kwsa)
3097 (and log (push log org-todo-log-states))
3099 (error "Invalid TODO keyword %s" x)))
3100 kws0)
3101 kwsa (if kwsa (append '((:startgroup))
3102 (nreverse kwsa)
3103 '((:endgroup))))
3104 hw (car kws1)
3105 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
3106 tail (list inter hw (car dws) (org-last dws)))
3107 (add-to-list 'org-todo-heads hw 'append)
3108 (push kws1 org-todo-sets)
3109 (setq org-done-keywords (append org-done-keywords dws nil))
3110 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
3111 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
3112 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
3113 (setq org-todo-sets (nreverse org-todo-sets)
3114 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
3115 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
3116 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
3117 ;; Process the constants
3118 (when const
3119 (let (e cst)
3120 (while (setq e (pop const))
3121 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
3122 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
3123 (setq org-table-formula-constants-local cst)))
3125 ;; Process the tags.
3126 (when tags
3127 (let (e tgs)
3128 (while (setq e (pop tags))
3129 (cond
3130 ((equal e "{") (push '(:startgroup) tgs))
3131 ((equal e "}") (push '(:endgroup) tgs))
3132 ((string-match (org-re "^\\([[:alnum:]_@]+\\)(\\(.\\))$") e)
3133 (push (cons (match-string 1 e)
3134 (string-to-char (match-string 2 e)))
3135 tgs))
3136 (t (push (list e) tgs))))
3137 (org-set-local 'org-tag-alist nil)
3138 (while (setq e (pop tgs))
3139 (or (and (stringp (car e))
3140 (assoc (car e) org-tag-alist))
3141 (push e org-tag-alist))))))
3143 ;; Compute the regular expressions and other local variables
3144 (if (not org-done-keywords)
3145 (setq org-done-keywords (list (org-last org-todo-keywords-1))))
3146 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
3147 (length org-scheduled-string)))
3148 org-drawer-regexp
3149 (concat "^[ \t]*:\\("
3150 (mapconcat 'regexp-quote org-drawers "\\|")
3151 "\\):[ \t]*$")
3152 org-not-done-keywords
3153 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
3154 org-todo-regexp
3155 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords-1
3156 "\\|") "\\)\\>")
3157 org-not-done-regexp
3158 (concat "\\<\\("
3159 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
3160 "\\)\\>")
3161 org-todo-line-regexp
3162 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3163 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3164 "\\)\\>\\)?[ \t]*\\(.*\\)")
3165 org-complex-heading-regexp
3166 (concat "^\\(\\*+\\)\\(?:[ \t]+\\("
3167 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3168 "\\)\\>\\)?\\(?:[ \t]*\\(\\[#.\\]\\)\\)?[ \t]*\\(.*?\\)"
3169 "\\(?:[ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
3170 org-nl-done-regexp
3171 (concat "\n\\*+[ \t]+"
3172 "\\(?:" (mapconcat 'regexp-quote org-done-keywords "\\|")
3173 "\\)" "\\>")
3174 org-todo-line-tags-regexp
3175 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3176 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3177 (org-re
3178 "\\)\\>\\)? *\\(.*?\\([ \t]:[[:alnum:]:_@]+:[ \t]*\\)?$\\)"))
3179 org-looking-at-done-regexp
3180 (concat "^" "\\(?:"
3181 (mapconcat 'regexp-quote org-done-keywords "\\|") "\\)"
3182 "\\>")
3183 org-deadline-regexp (concat "\\<" org-deadline-string)
3184 org-deadline-time-regexp
3185 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
3186 org-deadline-line-regexp
3187 (concat "\\<\\(" org-deadline-string "\\).*")
3188 org-scheduled-regexp
3189 (concat "\\<" org-scheduled-string)
3190 org-scheduled-time-regexp
3191 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
3192 org-closed-time-regexp
3193 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
3194 org-keyword-time-regexp
3195 (concat "\\<\\(" org-scheduled-string
3196 "\\|" org-deadline-string
3197 "\\|" org-closed-string
3198 "\\|" org-clock-string "\\)"
3199 " *[[<]\\([^]>]+\\)[]>]")
3200 org-keyword-time-not-clock-regexp
3201 (concat "\\<\\(" org-scheduled-string
3202 "\\|" org-deadline-string
3203 "\\|" org-closed-string
3204 "\\)"
3205 " *[[<]\\([^]>]+\\)[]>]")
3206 org-maybe-keyword-time-regexp
3207 (concat "\\(\\<\\(" org-scheduled-string
3208 "\\|" org-deadline-string
3209 "\\|" org-closed-string
3210 "\\|" org-clock-string "\\)\\)?"
3211 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
3212 org-planning-or-clock-line-re
3213 (concat "\\(?:^[ \t]*\\(" org-scheduled-string
3214 "\\|" org-deadline-string
3215 "\\|" org-closed-string "\\|" org-clock-string
3216 "\\)\\>\\)")
3218 (org-compute-latex-and-specials-regexp)
3219 (org-set-font-lock-defaults)))
3221 (defun org-extract-log-state-settings (x)
3222 "Extract the log state setting from a TODO keyword string.
3223 This will extract info from a string like \"WAIT(w@/!)\"."
3224 (let (kw key log1 log2)
3225 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
3226 (setq kw (match-string 1 x)
3227 key (and (match-end 2) (match-string 2 x))
3228 log1 (and (match-end 3) (match-string 3 x))
3229 log2 (and (match-end 4) (match-string 4 x)))
3230 (and (or log1 log2)
3231 (list kw
3232 (and log1 (if (equal log1 "!") 'time 'note))
3233 (and log2 (if (equal log2 "!") 'time 'note)))))))
3235 (defun org-remove-keyword-keys (list)
3236 "Remove a pair of parenthesis at the end of each string in LIST."
3237 (mapcar (lambda (x)
3238 (if (string-match "(.*)$" x)
3239 (substring x 0 (match-beginning 0))
3241 list))
3243 ;; FIXME: this could be done much better, using second characters etc.
3244 (defun org-assign-fast-keys (alist)
3245 "Assign fast keys to a keyword-key alist.
3246 Respect keys that are already there."
3247 (let (new e k c c1 c2 (char ?a))
3248 (while (setq e (pop alist))
3249 (cond
3250 ((equal e '(:startgroup)) (push e new))
3251 ((equal e '(:endgroup)) (push e new))
3253 (setq k (car e) c2 nil)
3254 (if (cdr e)
3255 (setq c (cdr e))
3256 ;; automatically assign a character.
3257 (setq c1 (string-to-char
3258 (downcase (substring
3259 k (if (= (string-to-char k) ?@) 1 0)))))
3260 (if (or (rassoc c1 new) (rassoc c1 alist))
3261 (while (or (rassoc char new) (rassoc char alist))
3262 (setq char (1+ char)))
3263 (setq c2 c1))
3264 (setq c (or c2 char)))
3265 (push (cons k c) new))))
3266 (nreverse new)))
3268 ;;; Some variables ujsed in various places
3270 (defvar org-window-configuration nil
3271 "Used in various places to store a window configuration.")
3272 (defvar org-finish-function nil
3273 "Function to be called when `C-c C-c' is used.
3274 This is for getting out of special buffers like remember.")
3277 ;; FIXME: Occasionally check by commenting these, to make sure
3278 ;; no other functions uses these, forgetting to let-bind them.
3279 (defvar entry)
3280 (defvar state)
3281 (defvar last-state)
3282 (defvar date)
3283 (defvar description)
3285 ;; Defined somewhere in this file, but used before definition.
3286 (defvar org-html-entities)
3287 (defvar org-struct-menu)
3288 (defvar org-org-menu)
3289 (defvar org-tbl-menu)
3290 (defvar org-agenda-keymap)
3292 ;;;; Define the Org-mode
3294 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
3295 (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."))
3298 ;; We use a before-change function to check if a table might need
3299 ;; an update.
3300 (defvar org-table-may-need-update t
3301 "Indicates that a table might need an update.
3302 This variable is set by `org-before-change-function'.
3303 `org-table-align' sets it back to nil.")
3304 (defun org-before-change-function (beg end)
3305 "Every change indicates that a table might need an update."
3306 (setq org-table-may-need-update t))
3307 (defvar org-mode-map)
3308 (defvar org-mode-hook nil)
3309 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
3310 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
3311 (defvar org-table-buffer-is-an nil)
3312 (defconst org-outline-regexp "\\*+ ")
3314 ;;;###autoload
3315 (define-derived-mode org-mode outline-mode "Org"
3316 "Outline-based notes management and organizer, alias
3317 \"Carsten's outline-mode for keeping track of everything.\"
3319 Org-mode develops organizational tasks around a NOTES file which
3320 contains information about projects as plain text. Org-mode is
3321 implemented on top of outline-mode, which is ideal to keep the content
3322 of large files well structured. It supports ToDo items, deadlines and
3323 time stamps, which magically appear in the diary listing of the Emacs
3324 calendar. Tables are easily created with a built-in table editor.
3325 Plain text URL-like links connect to websites, emails (VM), Usenet
3326 messages (Gnus), BBDB entries, and any files related to the project.
3327 For printing and sharing of notes, an Org-mode file (or a part of it)
3328 can be exported as a structured ASCII or HTML file.
3330 The following commands are available:
3332 \\{org-mode-map}"
3334 ;; Get rid of Outline menus, they are not needed
3335 ;; Need to do this here because define-derived-mode sets up
3336 ;; the keymap so late. Still, it is a waste to call this each time
3337 ;; we switch another buffer into org-mode.
3338 (if (featurep 'xemacs)
3339 (when (boundp 'outline-mode-menu-heading)
3340 ;; Assume this is Greg's port, it used easymenu
3341 (easy-menu-remove outline-mode-menu-heading)
3342 (easy-menu-remove outline-mode-menu-show)
3343 (easy-menu-remove outline-mode-menu-hide))
3344 (define-key org-mode-map [menu-bar headings] 'undefined)
3345 (define-key org-mode-map [menu-bar hide] 'undefined)
3346 (define-key org-mode-map [menu-bar show] 'undefined))
3348 (org-load-modules-maybe)
3349 (easy-menu-add org-org-menu)
3350 (easy-menu-add org-tbl-menu)
3351 (org-install-agenda-files-menu)
3352 (if org-descriptive-links (org-add-to-invisibility-spec '(org-link)))
3353 (org-add-to-invisibility-spec '(org-cwidth))
3354 (when (featurep 'xemacs)
3355 (org-set-local 'line-move-ignore-invisible t))
3356 (org-set-local 'outline-regexp org-outline-regexp)
3357 (org-set-local 'outline-level 'org-outline-level)
3358 (when (and org-ellipsis
3359 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
3360 (fboundp 'make-glyph-code))
3361 (unless org-display-table
3362 (setq org-display-table (make-display-table)))
3363 (set-display-table-slot
3364 org-display-table 4
3365 (vconcat (mapcar
3366 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
3367 org-ellipsis)))
3368 (if (stringp org-ellipsis) org-ellipsis "..."))))
3369 (setq buffer-display-table org-display-table))
3370 (org-set-regexps-and-options)
3371 ;; Calc embedded
3372 (org-set-local 'calc-embedded-open-mode "# ")
3373 (modify-syntax-entry ?# "<")
3374 (modify-syntax-entry ?@ "w")
3375 (if org-startup-truncated (setq truncate-lines t))
3376 (org-set-local 'font-lock-unfontify-region-function
3377 'org-unfontify-region)
3378 ;; Activate before-change-function
3379 (org-set-local 'org-table-may-need-update t)
3380 (org-add-hook 'before-change-functions 'org-before-change-function nil
3381 'local)
3382 ;; Check for running clock before killing a buffer
3383 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
3384 ;; Paragraphs and auto-filling
3385 (org-set-autofill-regexps)
3386 (setq indent-line-function 'org-indent-line-function)
3387 (org-update-radio-target-regexp)
3389 ;; Comment characters
3390 ; (org-set-local 'comment-start "#") ;; FIXME: this breaks wrapping
3391 (org-set-local 'comment-padding " ")
3393 ;; Align options lines
3394 (org-set-local
3395 'align-mode-rules-list
3396 '((org-in-buffer-settings
3397 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
3398 (modes . '(org-mode)))))
3400 ;; Imenu
3401 (org-set-local 'imenu-create-index-function
3402 'org-imenu-get-tree)
3404 ;; Make isearch reveal context
3405 (if (or (featurep 'xemacs)
3406 (not (boundp 'outline-isearch-open-invisible-function)))
3407 ;; Emacs 21 and XEmacs make use of the hook
3408 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
3409 ;; Emacs 22 deals with this through a special variable
3410 (org-set-local 'outline-isearch-open-invisible-function
3411 (lambda (&rest ignore) (org-show-context 'isearch))))
3413 ;; If empty file that did not turn on org-mode automatically, make it to.
3414 (if (and org-insert-mode-line-in-empty-file
3415 (interactive-p)
3416 (= (point-min) (point-max)))
3417 (insert "# -*- mode: org -*-\n\n"))
3419 (unless org-inhibit-startup
3420 (when org-startup-align-all-tables
3421 (let ((bmp (buffer-modified-p)))
3422 (org-table-map-tables 'org-table-align)
3423 (set-buffer-modified-p bmp)))
3424 (org-cycle-hide-drawers 'all)
3425 (cond
3426 ((eq org-startup-folded t)
3427 (org-cycle '(4)))
3428 ((eq org-startup-folded 'content)
3429 (let ((this-command 'org-cycle) (last-command 'org-cycle))
3430 (org-cycle '(4)) (org-cycle '(4)))))))
3432 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
3434 (defun org-current-time ()
3435 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
3436 (if (> (car org-time-stamp-rounding-minutes) 1)
3437 (let ((r (car org-time-stamp-rounding-minutes))
3438 (time (decode-time)))
3439 (apply 'encode-time
3440 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
3441 (nthcdr 2 time))))
3442 (current-time)))
3444 ;;;; Font-Lock stuff, including the activators
3446 (defvar org-mouse-map (make-sparse-keymap))
3447 (org-defkey org-mouse-map
3448 (if (featurep 'xemacs) [button2] [mouse-2]) 'org-open-at-mouse)
3449 (org-defkey org-mouse-map
3450 (if (featurep 'xemacs) [button3] [mouse-3]) 'org-find-file-at-mouse)
3451 (when org-mouse-1-follows-link
3452 (org-defkey org-mouse-map [follow-link] 'mouse-face))
3453 (when org-tab-follows-link
3454 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
3455 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
3456 (when org-return-follows-link
3457 (org-defkey org-mouse-map [(return)] 'org-open-at-point)
3458 (org-defkey org-mouse-map "\C-m" 'org-open-at-point))
3460 (require 'font-lock)
3462 (defconst org-non-link-chars "]\t\n\r<>")
3463 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
3464 "shell" "elisp"))
3465 (defvar org-link-re-with-space nil
3466 "Matches a link with spaces, optional angular brackets around it.")
3467 (defvar org-link-re-with-space2 nil
3468 "Matches a link with spaces, optional angular brackets around it.")
3469 (defvar org-angle-link-re nil
3470 "Matches link with angular brackets, spaces are allowed.")
3471 (defvar org-plain-link-re nil
3472 "Matches plain link, without spaces.")
3473 (defvar org-bracket-link-regexp nil
3474 "Matches a link in double brackets.")
3475 (defvar org-bracket-link-analytic-regexp nil
3476 "Regular expression used to analyze links.
3477 Here is what the match groups contain after a match:
3478 1: http:
3479 2: http
3480 3: path
3481 4: [desc]
3482 5: desc")
3483 (defvar org-any-link-re nil
3484 "Regular expression matching any link.")
3486 (defun org-make-link-regexps ()
3487 "Update the link regular expressions.
3488 This should be called after the variable `org-link-types' has changed."
3489 (setq org-link-re-with-space
3490 (concat
3491 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3492 "\\([^" org-non-link-chars " ]"
3493 "[^" org-non-link-chars "]*"
3494 "[^" org-non-link-chars " ]\\)>?")
3495 org-link-re-with-space2
3496 (concat
3497 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3498 "\\([^" org-non-link-chars " ]"
3499 "[^]\t\n\r]*"
3500 "[^" org-non-link-chars " ]\\)>?")
3501 org-angle-link-re
3502 (concat
3503 "<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3504 "\\([^" org-non-link-chars " ]"
3505 "[^" org-non-link-chars "]*"
3506 "\\)>")
3507 org-plain-link-re
3508 (concat
3509 "\\<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3510 "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
3511 org-bracket-link-regexp
3512 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
3513 org-bracket-link-analytic-regexp
3514 (concat
3515 "\\[\\["
3516 "\\(\\(" (mapconcat 'identity org-link-types "\\|") "\\):\\)?"
3517 "\\([^]]+\\)"
3518 "\\]"
3519 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
3520 "\\]")
3521 org-any-link-re
3522 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
3523 org-angle-link-re "\\)\\|\\("
3524 org-plain-link-re "\\)")))
3526 (org-make-link-regexps)
3528 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)>"
3529 "Regular expression for fast time stamp matching.")
3530 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)[]>]"
3531 "Regular expression for fast time stamp matching.")
3532 (defconst org-ts-regexp0 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
3533 "Regular expression matching time strings for analysis.
3534 This one does not require the space after the date, so it can be used
3535 on a string that terminates immediately after the date.")
3536 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) +\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
3537 "Regular expression matching time strings for analysis.")
3538 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
3539 "Regular expression matching time stamps, with groups.")
3540 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
3541 "Regular expression matching time stamps (also [..]), with groups.")
3542 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
3543 "Regular expression matching a time stamp range.")
3544 (defconst org-tr-regexp-both
3545 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
3546 "Regular expression matching a time stamp range.")
3547 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
3548 org-ts-regexp "\\)?")
3549 "Regular expression matching a time stamp or time stamp range.")
3550 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
3551 org-ts-regexp-both "\\)?")
3552 "Regular expression matching a time stamp or time stamp range.
3553 The time stamps may be either active or inactive.")
3555 (defvar org-emph-face nil)
3557 (defun org-do-emphasis-faces (limit)
3558 "Run through the buffer and add overlays to links."
3559 (let (rtn)
3560 (while (and (not rtn) (re-search-forward org-emph-re limit t))
3561 (if (not (= (char-after (match-beginning 3))
3562 (char-after (match-beginning 4))))
3563 (progn
3564 (setq rtn t)
3565 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
3566 'face
3567 (nth 1 (assoc (match-string 3)
3568 org-emphasis-alist)))
3569 (add-text-properties (match-beginning 2) (match-end 2)
3570 '(font-lock-multiline t))
3571 (when org-hide-emphasis-markers
3572 (add-text-properties (match-end 4) (match-beginning 5)
3573 '(invisible org-link))
3574 (add-text-properties (match-beginning 3) (match-end 3)
3575 '(invisible org-link)))))
3576 (backward-char 1))
3577 rtn))
3579 (defun org-emphasize (&optional char)
3580 "Insert or change an emphasis, i.e. a font like bold or italic.
3581 If there is an active region, change that region to a new emphasis.
3582 If there is no region, just insert the marker characters and position
3583 the cursor between them.
3584 CHAR should be either the marker character, or the first character of the
3585 HTML tag associated with that emphasis. If CHAR is a space, the means
3586 to remove the emphasis of the selected region.
3587 If char is not given (for example in an interactive call) it
3588 will be prompted for."
3589 (interactive)
3590 (let ((eal org-emphasis-alist) e det
3591 (erc org-emphasis-regexp-components)
3592 (prompt "")
3593 (string "") beg end move tag c s)
3594 (if (org-region-active-p)
3595 (setq beg (region-beginning) end (region-end)
3596 string (buffer-substring beg end))
3597 (setq move t))
3599 (while (setq e (pop eal))
3600 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
3601 c (aref tag 0))
3602 (push (cons c (string-to-char (car e))) det)
3603 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
3604 (substring tag 1)))))
3605 (unless char
3606 (message "%s" (concat "Emphasis marker or tag:" prompt))
3607 (setq char (read-char-exclusive)))
3608 (setq char (or (cdr (assoc char det)) char))
3609 (if (equal char ?\ )
3610 (setq s "" move nil)
3611 (unless (assoc (char-to-string char) org-emphasis-alist)
3612 (error "No such emphasis marker: \"%c\"" char))
3613 (setq s (char-to-string char)))
3614 (while (and (> (length string) 1)
3615 (equal (substring string 0 1) (substring string -1))
3616 (assoc (substring string 0 1) org-emphasis-alist))
3617 (setq string (substring string 1 -1)))
3618 (setq string (concat s string s))
3619 (if beg (delete-region beg end))
3620 (unless (or (bolp)
3621 (string-match (concat "[" (nth 0 erc) "\n]")
3622 (char-to-string (char-before (point)))))
3623 (insert " "))
3624 (unless (string-match (concat "[" (nth 1 erc) "\n]")
3625 (char-to-string (char-after (point))))
3626 (insert " ") (backward-char 1))
3627 (insert string)
3628 (and move (backward-char 1))))
3630 (defconst org-nonsticky-props
3631 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
3634 (defun org-activate-plain-links (limit)
3635 "Run through the buffer and add overlays to links."
3636 (catch 'exit
3637 (let (f)
3638 (while (re-search-forward org-plain-link-re limit t)
3639 (setq f (get-text-property (match-beginning 0) 'face))
3640 (if (or (eq f 'org-tag)
3641 (and (listp f) (memq 'org-tag f)))
3643 (add-text-properties (match-beginning 0) (match-end 0)
3644 (list 'mouse-face 'highlight
3645 'rear-nonsticky org-nonsticky-props
3646 'keymap org-mouse-map
3648 (throw 'exit t))))))
3650 (defun org-activate-code (limit)
3651 (if (re-search-forward "^[ \t]*\\(:.*\\)" limit t)
3652 (unless (get-text-property (match-beginning 1) 'face)
3653 (remove-text-properties (match-beginning 0) (match-end 0)
3654 '(display t invisible t intangible t))
3655 t)))
3657 (defun org-activate-angle-links (limit)
3658 "Run through the buffer and add overlays to links."
3659 (if (re-search-forward org-angle-link-re limit t)
3660 (progn
3661 (add-text-properties (match-beginning 0) (match-end 0)
3662 (list 'mouse-face 'highlight
3663 'rear-nonsticky org-nonsticky-props
3664 'keymap org-mouse-map
3666 t)))
3668 (defun org-activate-bracket-links (limit)
3669 "Run through the buffer and add overlays to bracketed links."
3670 (if (re-search-forward org-bracket-link-regexp limit t)
3671 (let* ((help (concat "LINK: "
3672 (org-match-string-no-properties 1)))
3673 ;; FIXME: above we should remove the escapes.
3674 ;; but that requires another match, protecting match data,
3675 ;; a lot of overhead for font-lock.
3676 (ip (org-maybe-intangible
3677 (list 'invisible 'org-link 'rear-nonsticky org-nonsticky-props
3678 'keymap org-mouse-map 'mouse-face 'highlight
3679 'font-lock-multiline t 'help-echo help)))
3680 (vp (list 'rear-nonsticky org-nonsticky-props
3681 'keymap org-mouse-map 'mouse-face 'highlight
3682 ' font-lock-multiline t 'help-echo help)))
3683 ;; We need to remove the invisible property here. Table narrowing
3684 ;; may have made some of this invisible.
3685 (remove-text-properties (match-beginning 0) (match-end 0)
3686 '(invisible nil))
3687 (if (match-end 3)
3688 (progn
3689 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
3690 (add-text-properties (match-beginning 3) (match-end 3) vp)
3691 (add-text-properties (match-end 3) (match-end 0) ip))
3692 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
3693 (add-text-properties (match-beginning 1) (match-end 1) vp)
3694 (add-text-properties (match-end 1) (match-end 0) ip))
3695 t)))
3697 (defun org-activate-dates (limit)
3698 "Run through the buffer and add overlays to dates."
3699 (if (re-search-forward org-tsr-regexp-both limit t)
3700 (progn
3701 (add-text-properties (match-beginning 0) (match-end 0)
3702 (list 'mouse-face 'highlight
3703 'rear-nonsticky org-nonsticky-props
3704 'keymap org-mouse-map))
3705 (when org-display-custom-times
3706 (if (match-end 3)
3707 (org-display-custom-time (match-beginning 3) (match-end 3)))
3708 (org-display-custom-time (match-beginning 1) (match-end 1)))
3709 t)))
3711 (defvar org-target-link-regexp nil
3712 "Regular expression matching radio targets in plain text.")
3713 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
3714 "Regular expression matching a link target.")
3715 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
3716 "Regular expression matching a radio target.")
3717 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
3718 "Regular expression matching any target.")
3720 (defun org-activate-target-links (limit)
3721 "Run through the buffer and add overlays to target matches."
3722 (when org-target-link-regexp
3723 (let ((case-fold-search t))
3724 (if (re-search-forward org-target-link-regexp limit t)
3725 (progn
3726 (add-text-properties (match-beginning 0) (match-end 0)
3727 (list 'mouse-face 'highlight
3728 'rear-nonsticky org-nonsticky-props
3729 'keymap org-mouse-map
3730 'help-echo "Radio target link"
3731 'org-linked-text t))
3732 t)))))
3734 (defun org-update-radio-target-regexp ()
3735 "Find all radio targets in this file and update the regular expression."
3736 (interactive)
3737 (when (memq 'radio org-activate-links)
3738 (setq org-target-link-regexp
3739 (org-make-target-link-regexp (org-all-targets 'radio)))
3740 (org-restart-font-lock)))
3742 (defun org-hide-wide-columns (limit)
3743 (let (s e)
3744 (setq s (text-property-any (point) (or limit (point-max))
3745 'org-cwidth t))
3746 (when s
3747 (setq e (next-single-property-change s 'org-cwidth))
3748 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
3749 (goto-char e)
3750 t)))
3752 (defvar org-latex-and-specials-regexp nil
3753 "Regular expression for highlighting export special stuff.")
3754 (defvar org-match-substring-regexp)
3755 (defvar org-match-substring-with-braces-regexp)
3756 (defvar org-export-html-special-string-regexps)
3758 (defun org-compute-latex-and-specials-regexp ()
3759 "Compute regular expression for stuff treated specially by exporters."
3760 (if (not org-highlight-latex-fragments-and-specials)
3761 (org-set-local 'org-latex-and-specials-regexp nil)
3762 (require 'org-exp)
3763 (let*
3764 ((matchers (plist-get org-format-latex-options :matchers))
3765 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
3766 org-latex-regexps)))
3767 (options (org-combine-plists (org-default-export-plist)
3768 (org-infile-export-plist)))
3769 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
3770 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
3771 (org-export-with-TeX-macros (plist-get options :TeX-macros))
3772 (org-export-html-expand (plist-get options :expand-quoted-html))
3773 (org-export-with-special-strings (plist-get options :special-strings))
3774 (re-sub
3775 (cond
3776 ((equal org-export-with-sub-superscripts '{})
3777 (list org-match-substring-with-braces-regexp))
3778 (org-export-with-sub-superscripts
3779 (list org-match-substring-regexp))
3780 (t nil)))
3781 (re-latex
3782 (if org-export-with-LaTeX-fragments
3783 (mapcar (lambda (x) (nth 1 x)) latexs)))
3784 (re-macros
3785 (if org-export-with-TeX-macros
3786 (list (concat "\\\\"
3787 (regexp-opt
3788 (append (mapcar 'car org-html-entities)
3789 (if (boundp 'org-latex-entities)
3790 org-latex-entities nil))
3791 'words))) ; FIXME
3793 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
3794 (re-special (if org-export-with-special-strings
3795 (mapcar (lambda (x) (car x))
3796 org-export-html-special-string-regexps)))
3797 (re-rest
3798 (delq nil
3799 (list
3800 (if org-export-html-expand "@<[^>\n]+>")
3801 ))))
3802 (org-set-local
3803 'org-latex-and-specials-regexp
3804 (mapconcat 'identity (append re-latex re-sub re-macros re-special
3805 re-rest) "\\|")))))
3807 (defface org-latex-and-export-specials
3808 (let ((font (cond ((assq :inherit custom-face-attributes)
3809 '(:inherit underline))
3810 (t '(:underline t)))))
3811 `((((class grayscale) (background light))
3812 (:foreground "DimGray" ,@font))
3813 (((class grayscale) (background dark))
3814 (:foreground "LightGray" ,@font))
3815 (((class color) (background light))
3816 (:foreground "SaddleBrown"))
3817 (((class color) (background dark))
3818 (:foreground "burlywood"))
3819 (t (,@font))))
3820 "Face used to highlight math latex and other special exporter stuff."
3821 :group 'org-faces)
3823 (defun org-do-latex-and-special-faces (limit)
3824 "Run through the buffer and add overlays to links."
3825 (when org-latex-and-specials-regexp
3826 (let (rtn d)
3827 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
3828 limit t))
3829 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
3830 'face))
3831 '(org-code org-verbatim underline)))
3832 (progn
3833 (setq rtn t
3834 d (cond ((member (char-after (1+ (match-beginning 0)))
3835 '(?_ ?^)) 1)
3836 (t 0)))
3837 (font-lock-prepend-text-property
3838 (+ d (match-beginning 0)) (match-end 0)
3839 'face 'org-latex-and-export-specials)
3840 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
3841 '(font-lock-multiline t)))))
3842 rtn)))
3844 (defun org-restart-font-lock ()
3845 "Restart font-lock-mode, to force refontification."
3846 (when (and (boundp 'font-lock-mode) font-lock-mode)
3847 (font-lock-mode -1)
3848 (font-lock-mode 1)))
3850 (defun org-all-targets (&optional radio)
3851 "Return a list of all targets in this file.
3852 With optional argument RADIO, only find radio targets."
3853 (let ((re (if radio org-radio-target-regexp org-target-regexp))
3854 rtn)
3855 (save-excursion
3856 (goto-char (point-min))
3857 (while (re-search-forward re nil t)
3858 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
3859 rtn)))
3861 (defun org-make-target-link-regexp (targets)
3862 "Make regular expression matching all strings in TARGETS.
3863 The regular expression finds the targets also if there is a line break
3864 between words."
3865 (and targets
3866 (concat
3867 "\\<\\("
3868 (mapconcat
3869 (lambda (x)
3870 (while (string-match " +" x)
3871 (setq x (replace-match "\\s-+" t t x)))
3873 targets
3874 "\\|")
3875 "\\)\\>")))
3877 (defun org-activate-tags (limit)
3878 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \r\n]") limit t)
3879 (progn
3880 (add-text-properties (match-beginning 1) (match-end 1)
3881 (list 'mouse-face 'highlight
3882 'rear-nonsticky org-nonsticky-props
3883 'keymap org-mouse-map))
3884 t)))
3886 (defun org-outline-level ()
3887 (save-excursion
3888 (looking-at outline-regexp)
3889 (if (match-beginning 1)
3890 (+ (org-get-string-indentation (match-string 1)) 1000)
3891 (1- (- (match-end 0) (match-beginning 0))))))
3893 (defvar org-font-lock-keywords nil)
3895 (defconst org-property-re (org-re "^[ \t]*\\(:\\([[:alnum:]_]+\\):\\)[ \t]*\\(\\S-.*\\)")
3896 "Regular expression matching a property line.")
3898 (defun org-set-font-lock-defaults ()
3899 (let* ((em org-fontify-emphasized-text)
3900 (lk org-activate-links)
3901 (org-font-lock-extra-keywords
3902 (list
3903 ;; Headlines
3904 '("^\\(\\**\\)\\(\\* \\)\\(.*\\)" (1 (org-get-level-face 1))
3905 (2 (org-get-level-face 2)) (3 (org-get-level-face 3)))
3906 ;; Table lines
3907 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
3908 (1 'org-table t))
3909 ;; Table internals
3910 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
3911 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
3912 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
3913 ;; Drawers
3914 (list org-drawer-regexp '(0 'org-special-keyword t))
3915 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
3916 ;; Properties
3917 (list org-property-re
3918 '(1 'org-special-keyword t)
3919 '(3 'org-property-value t))
3920 (if org-format-transports-properties-p
3921 '("| *\\(<[0-9]+>\\) *" (1 'org-formula t)))
3922 ;; Links
3923 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
3924 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
3925 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
3926 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
3927 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
3928 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
3929 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
3930 '(org-hide-wide-columns (0 nil append))
3931 ;; TODO lines
3932 (list (concat "^\\*+[ \t]+" org-todo-regexp)
3933 '(1 (org-get-todo-face 1) t))
3934 ;; DONE
3935 (if org-fontify-done-headline
3936 (list (concat "^[*]+ +\\<\\("
3937 (mapconcat 'regexp-quote org-done-keywords "\\|")
3938 "\\)\\(.*\\)")
3939 '(2 'org-headline-done t))
3940 nil)
3941 ;; Priorities
3942 (list (concat "\\[#[A-Z0-9]\\]") '(0 'org-special-keyword t))
3943 ;; Special keywords
3944 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
3945 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
3946 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
3947 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
3948 ;; Emphasis
3949 (if em
3950 (if (featurep 'xemacs)
3951 '(org-do-emphasis-faces (0 nil append))
3952 '(org-do-emphasis-faces)))
3953 ;; Checkboxes
3954 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)"
3955 2 'bold prepend)
3956 (if org-provide-checkbox-statistics
3957 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
3958 (0 (org-get-checkbox-statistics-face) t)))
3959 (list (concat "^\\*+ \\(.*:" org-archive-tag ":.*\\)")
3960 '(1 'org-archived prepend))
3961 ;; Specials
3962 '(org-do-latex-and-special-faces)
3963 ;; Code
3964 '(org-activate-code (1 'org-code t))
3965 ;; COMMENT
3966 (list (concat "^\\*+[ \t]+\\<\\(" org-comment-string
3967 "\\|" org-quote-string "\\)\\>")
3968 '(1 'org-special-keyword t))
3969 '("^#.*" (0 'font-lock-comment-face t))
3971 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
3972 ;; Now set the full font-lock-keywords
3973 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
3974 (org-set-local 'font-lock-defaults
3975 '(org-font-lock-keywords t nil nil backward-paragraph))
3976 (kill-local-variable 'font-lock-keywords) nil))
3978 (defvar org-m nil)
3979 (defvar org-l nil)
3980 (defvar org-f nil)
3981 (defun org-get-level-face (n)
3982 "Get the right face for match N in font-lock matching of healdines."
3983 (setq org-l (- (match-end 2) (match-beginning 1) 1))
3984 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
3985 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
3986 (cond
3987 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
3988 ((eq n 2) org-f)
3989 (t (if org-level-color-stars-only nil org-f))))
3991 (defun org-get-todo-face (kwd)
3992 "Get the right face for a TODO keyword KWD.
3993 If KWD is a number, get the corresponding match group."
3994 (if (numberp kwd) (setq kwd (match-string kwd)))
3995 (or (cdr (assoc kwd org-todo-keyword-faces))
3996 (and (member kwd org-done-keywords) 'org-done)
3997 'org-todo))
3999 (defun org-unfontify-region (beg end &optional maybe_loudly)
4000 "Remove fontification and activation overlays from links."
4001 (font-lock-default-unfontify-region beg end)
4002 (let* ((buffer-undo-list t)
4003 (inhibit-read-only t) (inhibit-point-motion-hooks t)
4004 (inhibit-modification-hooks t)
4005 deactivate-mark buffer-file-name buffer-file-truename)
4006 (remove-text-properties beg end
4007 '(mouse-face t keymap t org-linked-text t
4008 invisible t intangible t))))
4010 ;;;; Visibility cycling, including org-goto and indirect buffer
4012 ;;; Cycling
4014 (defvar org-cycle-global-status nil)
4015 (make-variable-buffer-local 'org-cycle-global-status)
4016 (defvar org-cycle-subtree-status nil)
4017 (make-variable-buffer-local 'org-cycle-subtree-status)
4019 ;;;###autoload
4020 (defun org-cycle (&optional arg)
4021 "Visibility cycling for Org-mode.
4023 - When this function is called with a prefix argument, rotate the entire
4024 buffer through 3 states (global cycling)
4025 1. OVERVIEW: Show only top-level headlines.
4026 2. CONTENTS: Show all headlines of all levels, but no body text.
4027 3. SHOW ALL: Show everything.
4029 - When point is at the beginning of a headline, rotate the subtree started
4030 by this line through 3 different states (local cycling)
4031 1. FOLDED: Only the main headline is shown.
4032 2. CHILDREN: The main headline and the direct children are shown.
4033 From this state, you can move to one of the children
4034 and zoom in further.
4035 3. SUBTREE: Show the entire subtree, including body text.
4037 - When there is a numeric prefix, go up to a heading with level ARG, do
4038 a `show-subtree' and return to the previous cursor position. If ARG
4039 is negative, go up that many levels.
4041 - When point is not at the beginning of a headline, execute
4042 `indent-relative', like TAB normally does. See the option
4043 `org-cycle-emulate-tab' for details.
4045 - Special case: if point is at the beginning of the buffer and there is
4046 no headline in line 1, this function will act as if called with prefix arg.
4047 But only if also the variable `org-cycle-global-at-bob' is t."
4048 (interactive "P")
4049 (org-load-modules-maybe)
4050 (let* ((outline-regexp
4051 (if (and (org-mode-p) org-cycle-include-plain-lists)
4052 "\\(?:\\*+ \\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) \\)"
4053 outline-regexp))
4054 (bob-special (and org-cycle-global-at-bob (bobp)
4055 (not (looking-at outline-regexp))))
4056 (org-cycle-hook
4057 (if bob-special
4058 (delq 'org-optimize-window-after-visibility-change
4059 (copy-sequence org-cycle-hook))
4060 org-cycle-hook))
4061 (pos (point)))
4063 (if (or bob-special (equal arg '(4)))
4064 ;; special case: use global cycling
4065 (setq arg t))
4067 (cond
4069 ((org-at-table-p 'any)
4070 ;; Enter the table or move to the next field in the table
4071 (or (org-table-recognize-table.el)
4072 (progn
4073 (if arg (org-table-edit-field t)
4074 (org-table-justify-field-maybe)
4075 (call-interactively 'org-table-next-field)))))
4077 ((eq arg t) ;; Global cycling
4079 (cond
4080 ((and (eq last-command this-command)
4081 (eq org-cycle-global-status 'overview))
4082 ;; We just created the overview - now do table of contents
4083 ;; This can be slow in very large buffers, so indicate action
4084 (message "CONTENTS...")
4085 (org-content)
4086 (message "CONTENTS...done")
4087 (setq org-cycle-global-status 'contents)
4088 (run-hook-with-args 'org-cycle-hook 'contents))
4090 ((and (eq last-command this-command)
4091 (eq org-cycle-global-status 'contents))
4092 ;; We just showed the table of contents - now show everything
4093 (show-all)
4094 (message "SHOW ALL")
4095 (setq org-cycle-global-status 'all)
4096 (run-hook-with-args 'org-cycle-hook 'all))
4099 ;; Default action: go to overview
4100 (org-overview)
4101 (message "OVERVIEW")
4102 (setq org-cycle-global-status 'overview)
4103 (run-hook-with-args 'org-cycle-hook 'overview))))
4105 ((and org-drawers org-drawer-regexp
4106 (save-excursion
4107 (beginning-of-line 1)
4108 (looking-at org-drawer-regexp)))
4109 ;; Toggle block visibility
4110 (org-flag-drawer
4111 (not (get-char-property (match-end 0) 'invisible))))
4113 ((integerp arg)
4114 ;; Show-subtree, ARG levels up from here.
4115 (save-excursion
4116 (org-back-to-heading)
4117 (outline-up-heading (if (< arg 0) (- arg)
4118 (- (funcall outline-level) arg)))
4119 (org-show-subtree)))
4121 ((and (save-excursion (beginning-of-line 1) (looking-at outline-regexp))
4122 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
4123 ;; At a heading: rotate between three different views
4124 (org-back-to-heading)
4125 (let ((goal-column 0) eoh eol eos)
4126 ;; First, some boundaries
4127 (save-excursion
4128 (org-back-to-heading)
4129 (save-excursion
4130 (beginning-of-line 2)
4131 (while (and (not (eobp)) ;; this is like `next-line'
4132 (get-char-property (1- (point)) 'invisible))
4133 (beginning-of-line 2)) (setq eol (point)))
4134 (outline-end-of-heading) (setq eoh (point))
4135 (org-end-of-subtree t)
4136 (unless (eobp)
4137 (skip-chars-forward " \t\n")
4138 (beginning-of-line 1) ; in case this is an item
4140 (setq eos (1- (point))))
4141 ;; Find out what to do next and set `this-command'
4142 (cond
4143 ((= eos eoh)
4144 ;; Nothing is hidden behind this heading
4145 (message "EMPTY ENTRY")
4146 (setq org-cycle-subtree-status nil)
4147 (save-excursion
4148 (goto-char eos)
4149 (outline-next-heading)
4150 (if (org-invisible-p) (org-flag-heading nil))))
4151 ((or (>= eol eos)
4152 (not (string-match "\\S-" (buffer-substring eol eos))))
4153 ;; Entire subtree is hidden in one line: open it
4154 (org-show-entry)
4155 (show-children)
4156 (message "CHILDREN")
4157 (save-excursion
4158 (goto-char eos)
4159 (outline-next-heading)
4160 (if (org-invisible-p) (org-flag-heading nil)))
4161 (setq org-cycle-subtree-status 'children)
4162 (run-hook-with-args 'org-cycle-hook 'children))
4163 ((and (eq last-command this-command)
4164 (eq org-cycle-subtree-status 'children))
4165 ;; We just showed the children, now show everything.
4166 (org-show-subtree)
4167 (message "SUBTREE")
4168 (setq org-cycle-subtree-status 'subtree)
4169 (run-hook-with-args 'org-cycle-hook 'subtree))
4171 ;; Default action: hide the subtree.
4172 (hide-subtree)
4173 (message "FOLDED")
4174 (setq org-cycle-subtree-status 'folded)
4175 (run-hook-with-args 'org-cycle-hook 'folded)))))
4177 ;; TAB emulation
4178 (buffer-read-only (org-back-to-heading))
4180 ((org-try-cdlatex-tab))
4182 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
4183 (or (not (bolp))
4184 (not (looking-at outline-regexp))))
4185 (call-interactively (global-key-binding "\t")))
4187 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
4188 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
4189 (or (and (eq org-cycle-emulate-tab 'white)
4190 (= (match-end 0) (point-at-eol)))
4191 (and (eq org-cycle-emulate-tab 'whitestart)
4192 (>= (match-end 0) pos))))
4194 (eq org-cycle-emulate-tab t))
4195 ; (if (and (looking-at "[ \n\r\t]")
4196 ; (string-match "^[ \t]*$" (buffer-substring
4197 ; (point-at-bol) (point))))
4198 ; (progn
4199 ; (beginning-of-line 1)
4200 ; (and (looking-at "[ \t]+") (replace-match ""))))
4201 (call-interactively (global-key-binding "\t")))
4203 (t (save-excursion
4204 (org-back-to-heading)
4205 (org-cycle))))))
4207 ;;;###autoload
4208 (defun org-global-cycle (&optional arg)
4209 "Cycle the global visibility. For details see `org-cycle'."
4210 (interactive "P")
4211 (let ((org-cycle-include-plain-lists
4212 (if (org-mode-p) org-cycle-include-plain-lists nil)))
4213 (if (integerp arg)
4214 (progn
4215 (show-all)
4216 (hide-sublevels arg)
4217 (setq org-cycle-global-status 'contents))
4218 (org-cycle '(4)))))
4220 (defun org-overview ()
4221 "Switch to overview mode, shoing only top-level headlines.
4222 Really, this shows all headlines with level equal or greater than the level
4223 of the first headline in the buffer. This is important, because if the
4224 first headline is not level one, then (hide-sublevels 1) gives confusing
4225 results."
4226 (interactive)
4227 (let ((level (save-excursion
4228 (goto-char (point-min))
4229 (if (re-search-forward (concat "^" outline-regexp) nil t)
4230 (progn
4231 (goto-char (match-beginning 0))
4232 (funcall outline-level))))))
4233 (and level (hide-sublevels level))))
4235 (defun org-content (&optional arg)
4236 "Show all headlines in the buffer, like a table of contents.
4237 With numerical argument N, show content up to level N."
4238 (interactive "P")
4239 (save-excursion
4240 ;; Visit all headings and show their offspring
4241 (and (integerp arg) (org-overview))
4242 (goto-char (point-max))
4243 (catch 'exit
4244 (while (and (progn (condition-case nil
4245 (outline-previous-visible-heading 1)
4246 (error (goto-char (point-min))))
4248 (looking-at outline-regexp))
4249 (if (integerp arg)
4250 (show-children (1- arg))
4251 (show-branches))
4252 (if (bobp) (throw 'exit nil))))))
4255 (defun org-optimize-window-after-visibility-change (state)
4256 "Adjust the window after a change in outline visibility.
4257 This function is the default value of the hook `org-cycle-hook'."
4258 (when (get-buffer-window (current-buffer))
4259 (cond
4260 ; ((eq state 'overview) (org-first-headline-recenter 1))
4261 ; ((eq state 'overview) (org-beginning-of-line))
4262 ((eq state 'content) nil)
4263 ((eq state 'all) nil)
4264 ((eq state 'folded) nil)
4265 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
4266 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
4268 (defun org-compact-display-after-subtree-move ()
4269 (let (beg end)
4270 (save-excursion
4271 (if (org-up-heading-safe)
4272 (progn
4273 (hide-subtree)
4274 (show-entry)
4275 (show-children)
4276 (org-cycle-show-empty-lines 'children)
4277 (org-cycle-hide-drawers 'children))
4278 (org-overview)))))
4280 (defun org-cycle-show-empty-lines (state)
4281 "Show empty lines above all visible headlines.
4282 The region to be covered depends on STATE when called through
4283 `org-cycle-hook'. Lisp program can use t for STATE to get the
4284 entire buffer covered. Note that an empty line is only shown if there
4285 are at least `org-cycle-separator-lines' empty lines before the headeline."
4286 (when (> org-cycle-separator-lines 0)
4287 (save-excursion
4288 (let* ((n org-cycle-separator-lines)
4289 (re (cond
4290 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
4291 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
4292 (t (let ((ns (number-to-string (- n 2))))
4293 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
4294 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
4295 beg end)
4296 (cond
4297 ((memq state '(overview contents t))
4298 (setq beg (point-min) end (point-max)))
4299 ((memq state '(children folded))
4300 (setq beg (point) end (progn (org-end-of-subtree t t)
4301 (beginning-of-line 2)
4302 (point)))))
4303 (when beg
4304 (goto-char beg)
4305 (while (re-search-forward re end t)
4306 (if (not (get-char-property (match-end 1) 'invisible))
4307 (outline-flag-region
4308 (match-beginning 1) (match-end 1) nil)))))))
4309 ;; Never hide empty lines at the end of the file.
4310 (save-excursion
4311 (goto-char (point-max))
4312 (outline-previous-heading)
4313 (outline-end-of-heading)
4314 (if (and (looking-at "[ \t\n]+")
4315 (= (match-end 0) (point-max)))
4316 (outline-flag-region (point) (match-end 0) nil))))
4318 (defun org-subtree-end-visible-p ()
4319 "Is the end of the current subtree visible?"
4320 (pos-visible-in-window-p
4321 (save-excursion (org-end-of-subtree t) (point))))
4323 (defun org-first-headline-recenter (&optional N)
4324 "Move cursor to the first headline and recenter the headline.
4325 Optional argument N means, put the headline into the Nth line of the window."
4326 (goto-char (point-min))
4327 (when (re-search-forward (concat "^\\(" outline-regexp "\\)") nil t)
4328 (beginning-of-line)
4329 (recenter (prefix-numeric-value N))))
4331 ;;; Org-goto
4333 (defvar org-goto-window-configuration nil)
4334 (defvar org-goto-marker nil)
4335 (defvar org-goto-map
4336 (let ((map (make-sparse-keymap)))
4337 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
4338 (while (setq cmd (pop cmds))
4339 (substitute-key-definition cmd cmd map global-map)))
4340 (suppress-keymap map)
4341 (org-defkey map "\C-m" 'org-goto-ret)
4342 (org-defkey map [(return)] 'org-goto-ret)
4343 (org-defkey map [(left)] 'org-goto-left)
4344 (org-defkey map [(right)] 'org-goto-right)
4345 (org-defkey map [(control ?g)] 'org-goto-quit)
4346 (org-defkey map "\C-i" 'org-cycle)
4347 (org-defkey map [(tab)] 'org-cycle)
4348 (org-defkey map [(down)] 'outline-next-visible-heading)
4349 (org-defkey map [(up)] 'outline-previous-visible-heading)
4350 (if org-goto-auto-isearch
4351 (if (fboundp 'define-key-after)
4352 (define-key-after map [t] 'org-goto-local-auto-isearch)
4353 nil)
4354 (org-defkey map "q" 'org-goto-quit)
4355 (org-defkey map "n" 'outline-next-visible-heading)
4356 (org-defkey map "p" 'outline-previous-visible-heading)
4357 (org-defkey map "f" 'outline-forward-same-level)
4358 (org-defkey map "b" 'outline-backward-same-level)
4359 (org-defkey map "u" 'outline-up-heading))
4360 (org-defkey map "/" 'org-occur)
4361 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
4362 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
4363 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
4364 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
4365 (org-defkey map "\C-c\C-u" 'outline-up-heading)
4366 map))
4368 (defconst org-goto-help
4369 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
4370 RET=jump to location [Q]uit and return to previous location
4371 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
4373 (defvar org-goto-start-pos) ; dynamically scoped parameter
4375 (defun org-goto (&optional alternative-interface)
4376 "Look up a different location in the current file, keeping current visibility.
4378 When you want look-up or go to a different location in a document, the
4379 fastest way is often to fold the entire buffer and then dive into the tree.
4380 This method has the disadvantage, that the previous location will be folded,
4381 which may not be what you want.
4383 This command works around this by showing a copy of the current buffer
4384 in an indirect buffer, in overview mode. You can dive into the tree in
4385 that copy, use org-occur and incremental search to find a location.
4386 When pressing RET or `Q', the command returns to the original buffer in
4387 which the visibility is still unchanged. After RET is will also jump to
4388 the location selected in the indirect buffer and expose the
4389 the headline hierarchy above."
4390 (interactive "P")
4391 (let* ((org-refile-targets '((nil . (:maxlevel . 10))))
4392 (org-refile-use-outline-path t)
4393 (interface
4394 (if (not alternative-interface)
4395 org-goto-interface
4396 (if (eq org-goto-interface 'outline)
4397 'outline-path-completion
4398 'outline)))
4399 (org-goto-start-pos (point))
4400 (selected-point
4401 (if (eq interface 'outline)
4402 (car (org-get-location (current-buffer) org-goto-help))
4403 (nth 3 (org-refile-get-location "Goto: ")))))
4404 (if selected-point
4405 (progn
4406 (org-mark-ring-push org-goto-start-pos)
4407 (goto-char selected-point)
4408 (if (or (org-invisible-p) (org-invisible-p2))
4409 (org-show-context 'org-goto)))
4410 (message "Quit"))))
4412 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
4413 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
4414 (defvar org-goto-local-auto-isearch-map) ; defined below
4416 (defun org-get-location (buf help)
4417 "Let the user select a location in the Org-mode buffer BUF.
4418 This function uses a recursive edit. It returns the selected position
4419 or nil."
4420 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
4421 (isearch-hide-immediately nil)
4422 (isearch-search-fun-function
4423 (lambda () 'org-goto-local-search-forward-headings))
4424 (org-goto-selected-point org-goto-exit-command))
4425 (save-excursion
4426 (save-window-excursion
4427 (delete-other-windows)
4428 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
4429 (switch-to-buffer
4430 (condition-case nil
4431 (make-indirect-buffer (current-buffer) "*org-goto*")
4432 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
4433 (with-output-to-temp-buffer "*Help*"
4434 (princ help))
4435 (shrink-window-if-larger-than-buffer (get-buffer-window "*Help*"))
4436 (setq buffer-read-only nil)
4437 (let ((org-startup-truncated t)
4438 (org-startup-folded nil)
4439 (org-startup-align-all-tables nil))
4440 (org-mode)
4441 (org-overview))
4442 (setq buffer-read-only t)
4443 (if (and (boundp 'org-goto-start-pos)
4444 (integer-or-marker-p org-goto-start-pos))
4445 (let ((org-show-hierarchy-above t)
4446 (org-show-siblings t)
4447 (org-show-following-heading t))
4448 (goto-char org-goto-start-pos)
4449 (and (org-invisible-p) (org-show-context)))
4450 (goto-char (point-min)))
4451 (org-beginning-of-line)
4452 (message "Select location and press RET")
4453 (use-local-map org-goto-map)
4454 (recursive-edit)
4456 (kill-buffer "*org-goto*")
4457 (cons org-goto-selected-point org-goto-exit-command)))
4459 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
4460 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
4461 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
4462 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
4464 (defun org-goto-local-search-forward-headings (string bound noerror)
4465 "Search and make sure that anu matches are in headlines."
4466 (catch 'return
4467 (while (search-forward string bound noerror)
4468 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
4469 (and (member :headline context)
4470 (not (member :tags context))))
4471 (throw 'return (point))))))
4473 (defun org-goto-local-auto-isearch ()
4474 "Start isearch."
4475 (interactive)
4476 (goto-char (point-min))
4477 (let ((keys (this-command-keys)))
4478 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
4479 (isearch-mode t)
4480 (isearch-process-search-char (string-to-char keys)))))
4482 (defun org-goto-ret (&optional arg)
4483 "Finish `org-goto' by going to the new location."
4484 (interactive "P")
4485 (setq org-goto-selected-point (point)
4486 org-goto-exit-command 'return)
4487 (throw 'exit nil))
4489 (defun org-goto-left ()
4490 "Finish `org-goto' by going to the new location."
4491 (interactive)
4492 (if (org-on-heading-p)
4493 (progn
4494 (beginning-of-line 1)
4495 (setq org-goto-selected-point (point)
4496 org-goto-exit-command 'left)
4497 (throw 'exit nil))
4498 (error "Not on a heading")))
4500 (defun org-goto-right ()
4501 "Finish `org-goto' by going to the new location."
4502 (interactive)
4503 (if (org-on-heading-p)
4504 (progn
4505 (setq org-goto-selected-point (point)
4506 org-goto-exit-command 'right)
4507 (throw 'exit nil))
4508 (error "Not on a heading")))
4510 (defun org-goto-quit ()
4511 "Finish `org-goto' without cursor motion."
4512 (interactive)
4513 (setq org-goto-selected-point nil)
4514 (setq org-goto-exit-command 'quit)
4515 (throw 'exit nil))
4517 ;;; Indirect buffer display of subtrees
4519 (defvar org-indirect-dedicated-frame nil
4520 "This is the frame being used for indirect tree display.")
4521 (defvar org-last-indirect-buffer nil)
4523 (defun org-tree-to-indirect-buffer (&optional arg)
4524 "Create indirect buffer and narrow it to current subtree.
4525 With numerical prefix ARG, go up to this level and then take that tree.
4526 If ARG is negative, go up that many levels.
4527 If `org-indirect-buffer-display' is not `new-frame', the command removes the
4528 indirect buffer previously made with this command, to avoid proliferation of
4529 indirect buffers. However, when you call the command with a `C-u' prefix, or
4530 when `org-indirect-buffer-display' is `new-frame', the last buffer
4531 is kept so that you can work with several indirect buffers at the same time.
4532 If `org-indirect-buffer-display' is `dedicated-frame', the C-u prefix also
4533 requests that a new frame be made for the new buffer, so that the dedicated
4534 frame is not changed."
4535 (interactive "P")
4536 (let ((cbuf (current-buffer))
4537 (cwin (selected-window))
4538 (pos (point))
4539 beg end level heading ibuf)
4540 (save-excursion
4541 (org-back-to-heading t)
4542 (when (numberp arg)
4543 (setq level (org-outline-level))
4544 (if (< arg 0) (setq arg (+ level arg)))
4545 (while (> (setq level (org-outline-level)) arg)
4546 (outline-up-heading 1 t)))
4547 (setq beg (point)
4548 heading (org-get-heading))
4549 (org-end-of-subtree t) (setq end (point)))
4550 (if (and (buffer-live-p org-last-indirect-buffer)
4551 (not (eq org-indirect-buffer-display 'new-frame))
4552 (not arg))
4553 (kill-buffer org-last-indirect-buffer))
4554 (setq ibuf (org-get-indirect-buffer cbuf)
4555 org-last-indirect-buffer ibuf)
4556 (cond
4557 ((or (eq org-indirect-buffer-display 'new-frame)
4558 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
4559 (select-frame (make-frame))
4560 (delete-other-windows)
4561 (switch-to-buffer ibuf)
4562 (org-set-frame-title heading))
4563 ((eq org-indirect-buffer-display 'dedicated-frame)
4564 (raise-frame
4565 (select-frame (or (and org-indirect-dedicated-frame
4566 (frame-live-p org-indirect-dedicated-frame)
4567 org-indirect-dedicated-frame)
4568 (setq org-indirect-dedicated-frame (make-frame)))))
4569 (delete-other-windows)
4570 (switch-to-buffer ibuf)
4571 (org-set-frame-title (concat "Indirect: " heading)))
4572 ((eq org-indirect-buffer-display 'current-window)
4573 (switch-to-buffer ibuf))
4574 ((eq org-indirect-buffer-display 'other-window)
4575 (pop-to-buffer ibuf))
4576 (t (error "Invalid value.")))
4577 (if (featurep 'xemacs)
4578 (save-excursion (org-mode) (turn-on-font-lock)))
4579 (narrow-to-region beg end)
4580 (show-all)
4581 (goto-char pos)
4582 (and (window-live-p cwin) (select-window cwin))))
4584 (defun org-get-indirect-buffer (&optional buffer)
4585 (setq buffer (or buffer (current-buffer)))
4586 (let ((n 1) (base (buffer-name buffer)) bname)
4587 (while (buffer-live-p
4588 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
4589 (setq n (1+ n)))
4590 (condition-case nil
4591 (make-indirect-buffer buffer bname 'clone)
4592 (error (make-indirect-buffer buffer bname)))))
4594 (defun org-set-frame-title (title)
4595 "Set the title of the current frame to the string TITLE."
4596 ;; FIXME: how to name a single frame in XEmacs???
4597 (unless (featurep 'xemacs)
4598 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
4600 ;;;; Structure editing
4602 ;;; Inserting headlines
4604 (defun org-insert-heading (&optional force-heading)
4605 "Insert a new heading or item with same depth at point.
4606 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
4607 If point is at the beginning of a headline, insert a sibling before the
4608 current headline. If point is not at the beginning, do not split the line,
4609 but create the new hedline after the current line."
4610 (interactive "P")
4611 (if (= (buffer-size) 0)
4612 (insert "\n* ")
4613 (when (or force-heading (not (org-insert-item)))
4614 (let* ((head (save-excursion
4615 (condition-case nil
4616 (progn
4617 (org-back-to-heading)
4618 (match-string 0))
4619 (error "*"))))
4620 (blank (cdr (assq 'heading org-blank-before-new-entry)))
4621 pos)
4622 (cond
4623 ((and (org-on-heading-p) (bolp)
4624 (or (bobp)
4625 (save-excursion (backward-char 1) (not (org-invisible-p)))))
4626 ;; insert before the current line
4627 (open-line (if blank 2 1)))
4628 ((and (bolp)
4629 (or (bobp)
4630 (save-excursion
4631 (backward-char 1) (not (org-invisible-p)))))
4632 ;; insert right here
4633 nil)
4635 ; ;; in the middle of the line
4636 ; (org-show-entry)
4637 ; (if (org-get-alist-option org-M-RET-may-split-line 'headline)
4638 ; (if (and
4639 ; (org-on-heading-p)
4640 ; (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \r\n]"))
4641 ; ;; protect the tags
4642 ;; (let ((tags (match-string 2)) pos)
4643 ; (delete-region (match-beginning 1) (match-end 1))
4644 ; (setq pos (point-at-bol))
4645 ; (newline (if blank 2 1))
4646 ; (save-excursion
4647 ; (goto-char pos)
4648 ; (end-of-line 1)
4649 ; (insert " " tags)
4650 ; (org-set-tags nil 'align)))
4651 ; (newline (if blank 2 1)))
4652 ; (newline (if blank 2 1))))
4655 ;; in the middle of the line
4656 (org-show-entry)
4657 (let ((split
4658 (org-get-alist-option org-M-RET-may-split-line 'headline))
4659 tags pos)
4660 (if (org-on-heading-p)
4661 (progn
4662 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
4663 (setq tags (and (match-end 2) (match-string 2)))
4664 (and (match-end 1)
4665 (delete-region (match-beginning 1) (match-end 1)))
4666 (setq pos (point-at-bol))
4667 (or split (end-of-line 1))
4668 (delete-horizontal-space)
4669 (newline (if blank 2 1))
4670 (when tags
4671 (save-excursion
4672 (goto-char pos)
4673 (end-of-line 1)
4674 (insert " " tags)
4675 (org-set-tags nil 'align))))
4676 (or split (end-of-line 1))
4677 (newline (if blank 2 1))))))
4678 (insert head) (just-one-space)
4679 (setq pos (point))
4680 (end-of-line 1)
4681 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
4682 (run-hooks 'org-insert-heading-hook)))))
4684 (defun org-insert-heading-after-current ()
4685 "Insert a new heading with same level as current, after current subtree."
4686 (interactive)
4687 (org-back-to-heading)
4688 (org-insert-heading)
4689 (org-move-subtree-down)
4690 (end-of-line 1))
4692 (defun org-insert-todo-heading (arg)
4693 "Insert a new heading with the same level and TODO state as current heading.
4694 If the heading has no TODO state, or if the state is DONE, use the first
4695 state (TODO by default). Also with prefix arg, force first state."
4696 (interactive "P")
4697 (when (not (org-insert-item 'checkbox))
4698 (org-insert-heading)
4699 (save-excursion
4700 (org-back-to-heading)
4701 (outline-previous-heading)
4702 (looking-at org-todo-line-regexp))
4703 (if (or arg
4704 (not (match-beginning 2))
4705 (member (match-string 2) org-done-keywords))
4706 (insert (car org-todo-keywords-1) " ")
4707 (insert (match-string 2) " "))))
4709 (defun org-insert-subheading (arg)
4710 "Insert a new subheading and demote it.
4711 Works for outline headings and for plain lists alike."
4712 (interactive "P")
4713 (org-insert-heading arg)
4714 (cond
4715 ((org-on-heading-p) (org-do-demote))
4716 ((org-at-item-p) (org-indent-item 1))))
4718 (defun org-insert-todo-subheading (arg)
4719 "Insert a new subheading with TODO keyword or checkbox and demote it.
4720 Works for outline headings and for plain lists alike."
4721 (interactive "P")
4722 (org-insert-todo-heading arg)
4723 (cond
4724 ((org-on-heading-p) (org-do-demote))
4725 ((org-at-item-p) (org-indent-item 1))))
4727 ;;; Promotion and Demotion
4729 (defun org-promote-subtree ()
4730 "Promote the entire subtree.
4731 See also `org-promote'."
4732 (interactive)
4733 (save-excursion
4734 (org-map-tree 'org-promote))
4735 (org-fix-position-after-promote))
4737 (defun org-demote-subtree ()
4738 "Demote the entire subtree. See `org-demote'.
4739 See also `org-promote'."
4740 (interactive)
4741 (save-excursion
4742 (org-map-tree 'org-demote))
4743 (org-fix-position-after-promote))
4746 (defun org-do-promote ()
4747 "Promote the current heading higher up the tree.
4748 If the region is active in `transient-mark-mode', promote all headings
4749 in the region."
4750 (interactive)
4751 (save-excursion
4752 (if (org-region-active-p)
4753 (org-map-region 'org-promote (region-beginning) (region-end))
4754 (org-promote)))
4755 (org-fix-position-after-promote))
4757 (defun org-do-demote ()
4758 "Demote the current heading lower down the tree.
4759 If the region is active in `transient-mark-mode', demote all headings
4760 in the region."
4761 (interactive)
4762 (save-excursion
4763 (if (org-region-active-p)
4764 (org-map-region 'org-demote (region-beginning) (region-end))
4765 (org-demote)))
4766 (org-fix-position-after-promote))
4768 (defun org-fix-position-after-promote ()
4769 "Make sure that after pro/demotion cursor position is right."
4770 (let ((pos (point)))
4771 (when (save-excursion
4772 (beginning-of-line 1)
4773 (looking-at org-todo-line-regexp)
4774 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
4775 (cond ((eobp) (insert " "))
4776 ((eolp) (insert " "))
4777 ((equal (char-after) ?\ ) (forward-char 1))))))
4779 (defun org-reduced-level (l)
4780 (if org-odd-levels-only (1+ (floor (/ l 2))) l))
4782 (defun org-get-valid-level (level &optional change)
4783 "Rectify a level change under the influence of `org-odd-levels-only'
4784 LEVEL is a current level, CHANGE is by how much the level should be
4785 modified. Even if CHANGE is nil, LEVEL may be returned modified because
4786 even level numbers will become the next higher odd number."
4787 (if org-odd-levels-only
4788 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
4789 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
4790 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
4791 (max 1 (+ level change))))
4793 (if (featurep 'xemacs)
4794 (define-obsolete-function-alias 'org-get-legal-level
4795 'org-get-valid-level)
4796 (define-obsolete-function-alias 'org-get-legal-level
4797 'org-get-valid-level "23.1"))
4799 (defun org-promote ()
4800 "Promote the current heading higher up the tree.
4801 If the region is active in `transient-mark-mode', promote all headings
4802 in the region."
4803 (org-back-to-heading t)
4804 (let* ((level (save-match-data (funcall outline-level)))
4805 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
4806 (diff (abs (- level (length up-head) -1))))
4807 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
4808 (replace-match up-head nil t)
4809 ;; Fixup tag positioning
4810 (and org-auto-align-tags (org-set-tags nil t))
4811 (if org-adapt-indentation (org-fixup-indentation (- diff)))))
4813 (defun org-demote ()
4814 "Demote the current heading lower down the tree.
4815 If the region is active in `transient-mark-mode', demote all headings
4816 in the region."
4817 (org-back-to-heading t)
4818 (let* ((level (save-match-data (funcall outline-level)))
4819 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
4820 (diff (abs (- level (length down-head) -1))))
4821 (replace-match down-head nil t)
4822 ;; Fixup tag positioning
4823 (and org-auto-align-tags (org-set-tags nil t))
4824 (if org-adapt-indentation (org-fixup-indentation diff))))
4826 (defun org-map-tree (fun)
4827 "Call FUN for every heading underneath the current one."
4828 (org-back-to-heading)
4829 (let ((level (funcall outline-level)))
4830 (save-excursion
4831 (funcall fun)
4832 (while (and (progn
4833 (outline-next-heading)
4834 (> (funcall outline-level) level))
4835 (not (eobp)))
4836 (funcall fun)))))
4838 (defun org-map-region (fun beg end)
4839 "Call FUN for every heading between BEG and END."
4840 (let ((org-ignore-region t))
4841 (save-excursion
4842 (setq end (copy-marker end))
4843 (goto-char beg)
4844 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
4845 (< (point) end))
4846 (funcall fun))
4847 (while (and (progn
4848 (outline-next-heading)
4849 (< (point) end))
4850 (not (eobp)))
4851 (funcall fun)))))
4853 (defun org-fixup-indentation (diff)
4854 "Change the indentation in the current entry by DIFF
4855 However, if any line in the current entry has no indentation, or if it
4856 would end up with no indentation after the change, nothing at all is done."
4857 (save-excursion
4858 (let ((end (save-excursion (outline-next-heading)
4859 (point-marker)))
4860 (prohibit (if (> diff 0)
4861 "^\\S-"
4862 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
4863 col)
4864 (unless (save-excursion (end-of-line 1)
4865 (re-search-forward prohibit end t))
4866 (while (and (< (point) end)
4867 (re-search-forward "^[ \t]+" end t))
4868 (goto-char (match-end 0))
4869 (setq col (current-column))
4870 (if (< diff 0) (replace-match ""))
4871 (indent-to (+ diff col))))
4872 (move-marker end nil))))
4874 (defun org-convert-to-odd-levels ()
4875 "Convert an org-mode file with all levels allowed to one with odd levels.
4876 This will leave level 1 alone, convert level 2 to level 3, level 3 to
4877 level 5 etc."
4878 (interactive)
4879 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
4880 (let ((org-odd-levels-only nil) n)
4881 (save-excursion
4882 (goto-char (point-min))
4883 (while (re-search-forward "^\\*\\*+ " nil t)
4884 (setq n (- (length (match-string 0)) 2))
4885 (while (>= (setq n (1- n)) 0)
4886 (org-demote))
4887 (end-of-line 1))))))
4890 (defun org-convert-to-oddeven-levels ()
4891 "Convert an org-mode file with only odd levels to one with odd and even levels.
4892 This promotes level 3 to level 2, level 5 to level 3 etc. If the file contains a
4893 section with an even level, conversion would destroy the structure of the file. An error
4894 is signaled in this case."
4895 (interactive)
4896 (goto-char (point-min))
4897 ;; First check if there are no even levels
4898 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
4899 (org-show-context t)
4900 (error "Not all levels are odd in this file. Conversion not possible."))
4901 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
4902 (let ((org-odd-levels-only nil) n)
4903 (save-excursion
4904 (goto-char (point-min))
4905 (while (re-search-forward "^\\*\\*+ " nil t)
4906 (setq n (/ (1- (length (match-string 0))) 2))
4907 (while (>= (setq n (1- n)) 0)
4908 (org-promote))
4909 (end-of-line 1))))))
4911 (defun org-tr-level (n)
4912 "Make N odd if required."
4913 (if org-odd-levels-only (1+ (/ n 2)) n))
4915 ;;; Vertical tree motion, cutting and pasting of subtrees
4917 (defun org-move-subtree-up (&optional arg)
4918 "Move the current subtree up past ARG headlines of the same level."
4919 (interactive "p")
4920 (org-move-subtree-down (- (prefix-numeric-value arg))))
4922 (defun org-move-subtree-down (&optional arg)
4923 "Move the current subtree down past ARG headlines of the same level."
4924 (interactive "p")
4925 (setq arg (prefix-numeric-value arg))
4926 (let ((movfunc (if (> arg 0) 'outline-get-next-sibling
4927 'outline-get-last-sibling))
4928 (ins-point (make-marker))
4929 (cnt (abs arg))
4930 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
4931 ;; Select the tree
4932 (org-back-to-heading)
4933 (setq beg0 (point))
4934 (save-excursion
4935 (setq ne-beg (org-back-over-empty-lines))
4936 (setq beg (point)))
4937 (save-match-data
4938 (save-excursion (outline-end-of-heading)
4939 (setq folded (org-invisible-p)))
4940 (outline-end-of-subtree))
4941 (outline-next-heading)
4942 (setq ne-end (org-back-over-empty-lines))
4943 (setq end (point))
4944 (goto-char beg0)
4945 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
4946 ;; include less whitespace
4947 (save-excursion
4948 (goto-char beg)
4949 (forward-line (- ne-beg ne-end))
4950 (setq beg (point))))
4951 ;; Find insertion point, with error handling
4952 (while (> cnt 0)
4953 (or (and (funcall movfunc) (looking-at outline-regexp))
4954 (progn (goto-char beg0)
4955 (error "Cannot move past superior level or buffer limit")))
4956 (setq cnt (1- cnt)))
4957 (if (> arg 0)
4958 ;; Moving forward - still need to move over subtree
4959 (progn (org-end-of-subtree t t)
4960 (save-excursion
4961 (org-back-over-empty-lines)
4962 (or (bolp) (newline)))))
4963 (setq ne-ins (org-back-over-empty-lines))
4964 (move-marker ins-point (point))
4965 (setq txt (buffer-substring beg end))
4966 (delete-region beg end)
4967 (outline-flag-region (1- beg) beg nil)
4968 (outline-flag-region (1- (point)) (point) nil)
4969 (insert txt)
4970 (or (bolp) (insert "\n"))
4971 (setq ins-end (point))
4972 (goto-char ins-point)
4973 (org-skip-whitespace)
4974 (when (and (< arg 0)
4975 (org-first-sibling-p)
4976 (> ne-ins ne-beg))
4977 ;; Move whitespace back to beginning
4978 (save-excursion
4979 (goto-char ins-end)
4980 (let ((kill-whole-line t))
4981 (kill-line (- ne-ins ne-beg)) (point)))
4982 (insert (make-string (- ne-ins ne-beg) ?\n)))
4983 (move-marker ins-point nil)
4984 (org-compact-display-after-subtree-move)
4985 (unless folded
4986 (org-show-entry)
4987 (show-children)
4988 (org-cycle-hide-drawers 'children))))
4990 (defvar org-subtree-clip ""
4991 "Clipboard for cut and paste of subtrees.
4992 This is actually only a copy of the kill, because we use the normal kill
4993 ring. We need it to check if the kill was created by `org-copy-subtree'.")
4995 (defvar org-subtree-clip-folded nil
4996 "Was the last copied subtree folded?
4997 This is used to fold the tree back after pasting.")
4999 (defun org-cut-subtree (&optional n)
5000 "Cut the current subtree into the clipboard.
5001 With prefix arg N, cut this many sequential subtrees.
5002 This is a short-hand for marking the subtree and then cutting it."
5003 (interactive "p")
5004 (org-copy-subtree n 'cut))
5006 (defun org-copy-subtree (&optional n cut)
5007 "Cut the current subtree into the clipboard.
5008 With prefix arg N, cut this many sequential subtrees.
5009 This is a short-hand for marking the subtree and then copying it.
5010 If CUT is non-nil, actually cut the subtree."
5011 (interactive "p")
5012 (let (beg end folded (beg0 (point)))
5013 (if (interactive-p)
5014 (org-back-to-heading nil) ; take what looks like a subtree
5015 (org-back-to-heading t)) ; take what is really there
5016 (org-back-over-empty-lines)
5017 (setq beg (point))
5018 (skip-chars-forward " \t\r\n")
5019 (save-match-data
5020 (save-excursion (outline-end-of-heading)
5021 (setq folded (org-invisible-p)))
5022 (condition-case nil
5023 (outline-forward-same-level (1- n))
5024 (error nil))
5025 (org-end-of-subtree t t))
5026 (org-back-over-empty-lines)
5027 (setq end (point))
5028 (goto-char beg0)
5029 (when (> end beg)
5030 (setq org-subtree-clip-folded folded)
5031 (if cut (kill-region beg end) (copy-region-as-kill beg end))
5032 (setq org-subtree-clip (current-kill 0))
5033 (message "%s: Subtree(s) with %d characters"
5034 (if cut "Cut" "Copied")
5035 (length org-subtree-clip)))))
5037 (defun org-paste-subtree (&optional level tree)
5038 "Paste the clipboard as a subtree, with modification of headline level.
5039 The entire subtree is promoted or demoted in order to match a new headline
5040 level. By default, the new level is derived from the visible headings
5041 before and after the insertion point, and taken to be the inferior headline
5042 level of the two. So if the previous visible heading is level 3 and the
5043 next is level 4 (or vice versa), level 4 will be used for insertion.
5044 This makes sure that the subtree remains an independent subtree and does
5045 not swallow low level entries.
5047 You can also force a different level, either by using a numeric prefix
5048 argument, or by inserting the heading marker by hand. For example, if the
5049 cursor is after \"*****\", then the tree will be shifted to level 5.
5051 If you want to insert the tree as is, just use \\[yank].
5053 If optional TREE is given, use this text instead of the kill ring."
5054 (interactive "P")
5055 (unless (org-kill-is-subtree-p tree)
5056 (error "%s"
5057 (substitute-command-keys
5058 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
5059 (let* ((txt (or tree (and kill-ring (current-kill 0))))
5060 (^re (concat "^\\(" outline-regexp "\\)"))
5061 (re (concat "\\(" outline-regexp "\\)"))
5062 (^re_ (concat "\\(\\*+\\)[ \t]*"))
5064 (old-level (if (string-match ^re txt)
5065 (- (match-end 0) (match-beginning 0) 1)
5066 -1))
5067 (force-level (cond (level (prefix-numeric-value level))
5068 ((string-match
5069 ^re_ (buffer-substring (point-at-bol) (point)))
5070 (- (match-end 1) (match-beginning 1)))
5071 (t nil)))
5072 (previous-level (save-excursion
5073 (condition-case nil
5074 (progn
5075 (outline-previous-visible-heading 1)
5076 (if (looking-at re)
5077 (- (match-end 0) (match-beginning 0) 1)
5079 (error 1))))
5080 (next-level (save-excursion
5081 (condition-case nil
5082 (progn
5083 (or (looking-at outline-regexp)
5084 (outline-next-visible-heading 1))
5085 (if (looking-at re)
5086 (- (match-end 0) (match-beginning 0) 1)
5088 (error 1))))
5089 (new-level (or force-level (max previous-level next-level)))
5090 (shift (if (or (= old-level -1)
5091 (= new-level -1)
5092 (= old-level new-level))
5094 (- new-level old-level)))
5095 (delta (if (> shift 0) -1 1))
5096 (func (if (> shift 0) 'org-demote 'org-promote))
5097 (org-odd-levels-only nil)
5098 beg end)
5099 ;; Remove the forced level indicator
5100 (if force-level
5101 (delete-region (point-at-bol) (point)))
5102 ;; Paste
5103 (beginning-of-line 1)
5104 (org-back-over-empty-lines) ;; FIXME: correct fix????
5105 (setq beg (point))
5106 (insert-before-markers txt) ;; FIXME: correct fix????
5107 (unless (string-match "\n\\'" txt) (insert "\n"))
5108 (setq end (point))
5109 (goto-char beg)
5110 (skip-chars-forward " \t\n\r")
5111 (setq beg (point))
5112 ;; Shift if necessary
5113 (unless (= shift 0)
5114 (save-restriction
5115 (narrow-to-region beg end)
5116 (while (not (= shift 0))
5117 (org-map-region func (point-min) (point-max))
5118 (setq shift (+ delta shift)))
5119 (goto-char (point-min))))
5120 (when (interactive-p)
5121 (message "Clipboard pasted as level %d subtree" new-level))
5122 (if (and kill-ring
5123 (eq org-subtree-clip (current-kill 0))
5124 org-subtree-clip-folded)
5125 ;; The tree was folded before it was killed/copied
5126 (hide-subtree))))
5128 (defun org-kill-is-subtree-p (&optional txt)
5129 "Check if the current kill is an outline subtree, or a set of trees.
5130 Returns nil if kill does not start with a headline, or if the first
5131 headline level is not the largest headline level in the tree.
5132 So this will actually accept several entries of equal levels as well,
5133 which is OK for `org-paste-subtree'.
5134 If optional TXT is given, check this string instead of the current kill."
5135 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
5136 (start-level (and kill
5137 (string-match (concat "\\`\\([ \t\n\r]*?\n\\)?\\("
5138 org-outline-regexp "\\)")
5139 kill)
5140 (- (match-end 2) (match-beginning 2) 1)))
5141 (re (concat "^" org-outline-regexp))
5142 (start (1+ (match-beginning 2))))
5143 (if (not start-level)
5144 (progn
5145 nil) ;; does not even start with a heading
5146 (catch 'exit
5147 (while (setq start (string-match re kill (1+ start)))
5148 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
5149 (throw 'exit nil)))
5150 t))))
5152 (defun org-narrow-to-subtree ()
5153 "Narrow buffer to the current subtree."
5154 (interactive)
5155 (save-excursion
5156 (save-match-data
5157 (narrow-to-region
5158 (progn (org-back-to-heading) (point))
5159 (progn (org-end-of-subtree t t) (point))))))
5162 ;;; Outline Sorting
5164 (defun org-sort (with-case)
5165 "Call `org-sort-entries-or-items' or `org-table-sort-lines'.
5166 Optional argument WITH-CASE means sort case-sensitively."
5167 (interactive "P")
5168 (if (org-at-table-p)
5169 (org-call-with-arg 'org-table-sort-lines with-case)
5170 (org-call-with-arg 'org-sort-entries-or-items with-case)))
5172 (defun org-sort-remove-invisible (s)
5173 (remove-text-properties 0 (length s) org-rm-props s)
5174 (while (string-match org-bracket-link-regexp s)
5175 (setq s (replace-match (if (match-end 2)
5176 (match-string 3 s)
5177 (match-string 1 s)) t t s)))
5180 (defvar org-priority-regexp) ; defined later in the file
5182 (defun org-sort-entries-or-items (&optional with-case sorting-type getkey-func property)
5183 "Sort entries on a certain level of an outline tree.
5184 If there is an active region, the entries in the region are sorted.
5185 Else, if the cursor is before the first entry, sort the top-level items.
5186 Else, the children of the entry at point are sorted.
5188 Sorting can be alphabetically, numerically, and by date/time as given by
5189 the first time stamp in the entry. The command prompts for the sorting
5190 type unless it has been given to the function through the SORTING-TYPE
5191 argument, which needs to a character, any of (?n ?N ?a ?A ?t ?T ?p ?P ?f ?F).
5192 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
5193 called with point at the beginning of the record. It must return either
5194 a string or a number that should serve as the sorting key for that record.
5196 Comparing entries ignores case by default. However, with an optional argument
5197 WITH-CASE, the sorting considers case as well."
5198 (interactive "P")
5199 (let ((case-func (if with-case 'identity 'downcase))
5200 start beg end stars re re2
5201 txt what tmp plain-list-p)
5202 ;; Find beginning and end of region to sort
5203 (cond
5204 ((org-region-active-p)
5205 ;; we will sort the region
5206 (setq end (region-end)
5207 what "region")
5208 (goto-char (region-beginning))
5209 (if (not (org-on-heading-p)) (outline-next-heading))
5210 (setq start (point)))
5211 ((org-at-item-p)
5212 ;; we will sort this plain list
5213 (org-beginning-of-item-list) (setq start (point))
5214 (org-end-of-item-list) (setq end (point))
5215 (goto-char start)
5216 (setq plain-list-p t
5217 what "plain list"))
5218 ((or (org-on-heading-p)
5219 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
5220 ;; we will sort the children of the current headline
5221 (org-back-to-heading)
5222 (setq start (point)
5223 end (progn (org-end-of-subtree t t)
5224 (org-back-over-empty-lines)
5225 (point))
5226 what "children")
5227 (goto-char start)
5228 (show-subtree)
5229 (outline-next-heading))
5231 ;; we will sort the top-level entries in this file
5232 (goto-char (point-min))
5233 (or (org-on-heading-p) (outline-next-heading))
5234 (setq start (point) end (point-max) what "top-level")
5235 (goto-char start)
5236 (show-all)))
5238 (setq beg (point))
5239 (if (>= beg end) (error "Nothing to sort"))
5241 (unless plain-list-p
5242 (looking-at "\\(\\*+\\)")
5243 (setq stars (match-string 1)
5244 re (concat "^" (regexp-quote stars) " +")
5245 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[^*]")
5246 txt (buffer-substring beg end))
5247 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
5248 (if (and (not (equal stars "*")) (string-match re2 txt))
5249 (error "Region to sort contains a level above the first entry")))
5251 (unless sorting-type
5252 (message
5253 (if plain-list-p
5254 "Sort %s: [a]lpha [n]umeric [t]ime [f]unc A/N/T/F means reversed:"
5255 "Sort %s: [a]lpha [n]umeric [t]ime [p]riority p[r]operty [f]unc A/N/T/P/F means reversed:")
5256 what)
5257 (setq sorting-type (read-char-exclusive))
5259 (and (= (downcase sorting-type) ?f)
5260 (setq getkey-func
5261 (completing-read "Sort using function: "
5262 obarray 'fboundp t nil nil))
5263 (setq getkey-func (intern getkey-func)))
5265 (and (= (downcase sorting-type) ?r)
5266 (setq property
5267 (completing-read "Property: "
5268 (mapcar 'list (org-buffer-property-keys t))
5269 nil t))))
5271 (message "Sorting entries...")
5273 (save-restriction
5274 (narrow-to-region start end)
5276 (let ((dcst (downcase sorting-type))
5277 (now (current-time)))
5278 (sort-subr
5279 (/= dcst sorting-type)
5280 ;; This function moves to the beginning character of the "record" to
5281 ;; be sorted.
5282 (if plain-list-p
5283 (lambda nil
5284 (if (org-at-item-p) t (goto-char (point-max))))
5285 (lambda nil
5286 (if (re-search-forward re nil t)
5287 (goto-char (match-beginning 0))
5288 (goto-char (point-max)))))
5289 ;; This function moves to the last character of the "record" being
5290 ;; sorted.
5291 (if plain-list-p
5292 'org-end-of-item
5293 (lambda nil
5294 (save-match-data
5295 (condition-case nil
5296 (outline-forward-same-level 1)
5297 (error
5298 (goto-char (point-max)))))))
5300 ;; This function returns the value that gets sorted against.
5301 (if plain-list-p
5302 (lambda nil
5303 (when (looking-at "[ \t]*[-+*0-9.)]+[ \t]+")
5304 (cond
5305 ((= dcst ?n)
5306 (string-to-number (buffer-substring (match-end 0)
5307 (point-at-eol))))
5308 ((= dcst ?a)
5309 (buffer-substring (match-end 0) (point-at-eol)))
5310 ((= dcst ?t)
5311 (if (re-search-forward org-ts-regexp
5312 (point-at-eol) t)
5313 (org-time-string-to-time (match-string 0))
5314 now))
5315 ((= dcst ?f)
5316 (if getkey-func
5317 (progn
5318 (setq tmp (funcall getkey-func))
5319 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
5320 tmp)
5321 (error "Invalid key function `%s'" getkey-func)))
5322 (t (error "Invalid sorting type `%c'" sorting-type)))))
5323 (lambda nil
5324 (cond
5325 ((= dcst ?n)
5326 (if (looking-at outline-regexp)
5327 (string-to-number (buffer-substring (match-end 0)
5328 (point-at-eol)))
5329 nil))
5330 ((= dcst ?a)
5331 (funcall case-func (buffer-substring (point-at-bol)
5332 (point-at-eol))))
5333 ((= dcst ?t)
5334 (if (re-search-forward org-ts-regexp
5335 (save-excursion
5336 (forward-line 2)
5337 (point)) t)
5338 (org-time-string-to-time (match-string 0))
5339 now))
5340 ((= dcst ?p)
5341 (if (re-search-forward org-priority-regexp (point-at-eol) t)
5342 (string-to-char (match-string 2))
5343 org-default-priority))
5344 ((= dcst ?r)
5345 (or (org-entry-get nil property) ""))
5346 ((= dcst ?f)
5347 (if getkey-func
5348 (progn
5349 (setq tmp (funcall getkey-func))
5350 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
5351 tmp)
5352 (error "Invalid key function `%s'" getkey-func)))
5353 (t (error "Invalid sorting type `%c'" sorting-type)))))
5355 (cond
5356 ((= dcst ?a) 'string<)
5357 ((= dcst ?t) 'time-less-p)
5358 (t nil)))))
5359 (message "Sorting entries...done")))
5361 (defun org-do-sort (table what &optional with-case sorting-type)
5362 "Sort TABLE of WHAT according to SORTING-TYPE.
5363 The user will be prompted for the SORTING-TYPE if the call to this
5364 function does not specify it. WHAT is only for the prompt, to indicate
5365 what is being sorted. The sorting key will be extracted from
5366 the car of the elements of the table.
5367 If WITH-CASE is non-nil, the sorting will be case-sensitive."
5368 (unless sorting-type
5369 (message
5370 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
5371 what)
5372 (setq sorting-type (read-char-exclusive)))
5373 (let ((dcst (downcase sorting-type))
5374 extractfun comparefun)
5375 ;; Define the appropriate functions
5376 (cond
5377 ((= dcst ?n)
5378 (setq extractfun 'string-to-number
5379 comparefun (if (= dcst sorting-type) '< '>)))
5380 ((= dcst ?a)
5381 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
5382 (lambda(x) (downcase (org-sort-remove-invisible x))))
5383 comparefun (if (= dcst sorting-type)
5384 'string<
5385 (lambda (a b) (and (not (string< a b))
5386 (not (string= a b)))))))
5387 ((= dcst ?t)
5388 (setq extractfun
5389 (lambda (x)
5390 (if (string-match org-ts-regexp x)
5391 (time-to-seconds
5392 (org-time-string-to-time (match-string 0 x)))
5394 comparefun (if (= dcst sorting-type) '< '>)))
5395 (t (error "Invalid sorting type `%c'" sorting-type)))
5397 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
5398 table)
5399 (lambda (a b) (funcall comparefun (car a) (car b))))))
5401 ;;;; Plain list items, including checkboxes
5403 ;;; Plain list items
5405 (defun org-at-item-p ()
5406 "Is point in a line starting a hand-formatted item?"
5407 (let ((llt org-plain-list-ordered-item-terminator))
5408 (save-excursion
5409 (goto-char (point-at-bol))
5410 (looking-at
5411 (cond
5412 ((eq llt t) "\\([ \t]*\\([-+]\\|\\([0-9]+[.)]\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
5413 ((= llt ?.) "\\([ \t]*\\([-+]\\|\\([0-9]+\\.\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
5414 ((= llt ?\)) "\\([ \t]*\\([-+]\\|\\([0-9]+))\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
5415 (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))))))
5417 (defun org-in-item-p ()
5418 "It the cursor inside a plain list item.
5419 Does not have to be the first line."
5420 (save-excursion
5421 (condition-case nil
5422 (progn
5423 (org-beginning-of-item)
5424 (org-at-item-p)
5426 (error nil))))
5428 (defun org-insert-item (&optional checkbox)
5429 "Insert a new item at the current level.
5430 Return t when things worked, nil when we are not in an item."
5431 (when (save-excursion
5432 (condition-case nil
5433 (progn
5434 (org-beginning-of-item)
5435 (org-at-item-p)
5436 (if (org-invisible-p) (error "Invisible item"))
5438 (error nil)))
5439 (let* ((bul (match-string 0))
5440 (eow (save-excursion (beginning-of-line 1) (looking-at "[ \t]*")
5441 (match-end 0)))
5442 (blank (cdr (assq 'plain-list-item org-blank-before-new-entry)))
5443 pos)
5444 (cond
5445 ((and (org-at-item-p) (<= (point) eow))
5446 ;; before the bullet
5447 (beginning-of-line 1)
5448 (open-line (if blank 2 1)))
5449 ((<= (point) eow)
5450 (beginning-of-line 1))
5452 (unless (org-get-alist-option org-M-RET-may-split-line 'item)
5453 (end-of-line 1)
5454 (delete-horizontal-space))
5455 (newline (if blank 2 1))))
5456 (insert bul (if checkbox "[ ]" ""))
5457 (just-one-space)
5458 (setq pos (point))
5459 (end-of-line 1)
5460 (unless (= (point) pos) (just-one-space) (backward-delete-char 1)))
5461 (org-maybe-renumber-ordered-list)
5462 (and checkbox (org-update-checkbox-count-maybe))
5465 ;;; Checkboxes
5467 (defun org-at-item-checkbox-p ()
5468 "Is point at a line starting a plain-list item with a checklet?"
5469 (and (org-at-item-p)
5470 (save-excursion
5471 (goto-char (match-end 0))
5472 (skip-chars-forward " \t")
5473 (looking-at "\\[[- X]\\]"))))
5475 (defun org-toggle-checkbox (&optional arg)
5476 "Toggle the checkbox in the current line."
5477 (interactive "P")
5478 (catch 'exit
5479 (let (beg end status (firstnew 'unknown))
5480 (cond
5481 ((org-region-active-p)
5482 (setq beg (region-beginning) end (region-end)))
5483 ((org-on-heading-p)
5484 (setq beg (point) end (save-excursion (outline-next-heading) (point))))
5485 ((org-at-item-checkbox-p)
5486 (let ((pos (point)))
5487 (replace-match
5488 (cond (arg "[-]")
5489 ((member (match-string 0) '("[ ]" "[-]")) "[X]")
5490 (t "[ ]"))
5491 t t)
5492 (goto-char pos))
5493 (throw 'exit t))
5494 (t (error "Not at a checkbox or heading, and no active region")))
5495 (save-excursion
5496 (goto-char beg)
5497 (while (< (point) end)
5498 (when (org-at-item-checkbox-p)
5499 (setq status (equal (match-string 0) "[X]"))
5500 (when (eq firstnew 'unknown)
5501 (setq firstnew (not status)))
5502 (replace-match
5503 (if (if arg (not status) firstnew) "[X]" "[ ]") t t))
5504 (beginning-of-line 2)))))
5505 (org-update-checkbox-count-maybe))
5507 (defun org-update-checkbox-count-maybe ()
5508 "Update checkbox statistics unless turned off by user."
5509 (when org-provide-checkbox-statistics
5510 (org-update-checkbox-count)))
5512 (defun org-update-checkbox-count (&optional all)
5513 "Update the checkbox statistics in the current section.
5514 This will find all statistic cookies like [57%] and [6/12] and update them
5515 with the current numbers. With optional prefix argument ALL, do this for
5516 the whole buffer."
5517 (interactive "P")
5518 (save-excursion
5519 (let* ((buffer-invisibility-spec (org-inhibit-invisibility)) ; Emacs 21
5520 (beg (condition-case nil
5521 (progn (outline-back-to-heading) (point))
5522 (error (point-min))))
5523 (end (move-marker (make-marker)
5524 (progn (outline-next-heading) (point))))
5525 (re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
5526 (re-box "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)")
5527 (re-find (concat re "\\|" re-box))
5528 beg-cookie end-cookie is-percent c-on c-off lim
5529 eline curr-ind next-ind continue-from startsearch
5530 (cstat 0)
5532 (when all
5533 (goto-char (point-min))
5534 (outline-next-heading)
5535 (setq beg (point) end (point-max)))
5536 (goto-char end)
5537 ;; find each statistic cookie
5538 (while (re-search-backward re-find beg t)
5539 (setq beg-cookie (match-beginning 1)
5540 end-cookie (match-end 1)
5541 cstat (+ cstat (if end-cookie 1 0))
5542 startsearch (point-at-eol)
5543 continue-from (point-at-bol)
5544 is-percent (match-beginning 2)
5545 lim (cond
5546 ((org-on-heading-p) (outline-next-heading) (point))
5547 ((org-at-item-p) (org-end-of-item) (point))
5548 (t nil))
5549 c-on 0
5550 c-off 0)
5551 (when lim
5552 ;; find first checkbox for this cookie and gather
5553 ;; statistics from all that are at this indentation level
5554 (goto-char startsearch)
5555 (if (re-search-forward re-box lim t)
5556 (progn
5557 (org-beginning-of-item)
5558 (setq curr-ind (org-get-indentation))
5559 (setq next-ind curr-ind)
5560 (while (and (org-at-item-p) (= curr-ind next-ind))
5561 (save-excursion (end-of-line) (setq eline (point)))
5562 (if (re-search-forward re-box eline t)
5563 (if (member (match-string 2) '("[ ]" "[-]"))
5564 (setq c-off (1+ c-off))
5565 (setq c-on (1+ c-on))
5568 (org-end-of-item)
5569 (setq next-ind (org-get-indentation))
5571 (goto-char continue-from)
5572 ;; update cookie
5573 (when end-cookie
5574 (delete-region beg-cookie end-cookie)
5575 (goto-char beg-cookie)
5576 (insert
5577 (if is-percent
5578 (format "[%d%%]" (/ (* 100 c-on) (max 1 (+ c-on c-off))))
5579 (format "[%d/%d]" c-on (+ c-on c-off)))))
5580 ;; update items checkbox if it has one
5581 (when (org-at-item-p)
5582 (org-beginning-of-item)
5583 (when (and (> (+ c-on c-off) 0)
5584 (re-search-forward re-box (point-at-eol) t))
5585 (setq beg-cookie (match-beginning 2)
5586 end-cookie (match-end 2))
5587 (delete-region beg-cookie end-cookie)
5588 (goto-char beg-cookie)
5589 (cond ((= c-off 0) (insert "[X]"))
5590 ((= c-on 0) (insert "[ ]"))
5591 (t (insert "[-]")))
5593 (goto-char continue-from))
5594 (when (interactive-p)
5595 (message "Checkbox satistics updated %s (%d places)"
5596 (if all "in entire file" "in current outline entry") cstat)))))
5598 (defun org-get-checkbox-statistics-face ()
5599 "Select the face for checkbox statistics.
5600 The face will be `org-done' when all relevant boxes are checked. Otherwise
5601 it will be `org-todo'."
5602 (if (match-end 1)
5603 (if (equal (match-string 1) "100%") 'org-done 'org-todo)
5604 (if (and (> (match-end 2) (match-beginning 2))
5605 (equal (match-string 2) (match-string 3)))
5606 'org-done
5607 'org-todo)))
5609 (defun org-get-indentation (&optional line)
5610 "Get the indentation of the current line, interpreting tabs.
5611 When LINE is given, assume it represents a line and compute its indentation."
5612 (if line
5613 (if (string-match "^ *" (org-remove-tabs line))
5614 (match-end 0))
5615 (save-excursion
5616 (beginning-of-line 1)
5617 (skip-chars-forward " \t")
5618 (current-column))))
5620 (defun org-remove-tabs (s &optional width)
5621 "Replace tabulators in S with spaces.
5622 Assumes that s is a single line, starting in column 0."
5623 (setq width (or width tab-width))
5624 (while (string-match "\t" s)
5625 (setq s (replace-match
5626 (make-string
5627 (- (* width (/ (+ (match-beginning 0) width) width))
5628 (match-beginning 0)) ?\ )
5629 t t s)))
5632 (defun org-fix-indentation (line ind)
5633 "Fix indentation in LINE.
5634 IND is a cons cell with target and minimum indentation.
5635 If the current indenation in LINE is smaller than the minimum,
5636 leave it alone. If it is larger than ind, set it to the target."
5637 (let* ((l (org-remove-tabs line))
5638 (i (org-get-indentation l))
5639 (i1 (car ind)) (i2 (cdr ind)))
5640 (if (>= i i2) (setq l (substring line i2)))
5641 (if (> i1 0)
5642 (concat (make-string i1 ?\ ) l)
5643 l)))
5645 (defcustom org-empty-line-terminates-plain-lists nil
5646 "Non-nil means, an empty line ends all plain list levels.
5647 When nil, empty lines are part of the preceeding item."
5648 :group 'org-plain-lists
5649 :type 'boolean)
5651 (defun org-beginning-of-item ()
5652 "Go to the beginning of the current hand-formatted item.
5653 If the cursor is not in an item, throw an error."
5654 (interactive)
5655 (let ((pos (point))
5656 (limit (save-excursion
5657 (condition-case nil
5658 (progn
5659 (org-back-to-heading)
5660 (beginning-of-line 2) (point))
5661 (error (point-min)))))
5662 (ind-empty (if org-empty-line-terminates-plain-lists 0 10000))
5663 ind ind1)
5664 (if (org-at-item-p)
5665 (beginning-of-line 1)
5666 (beginning-of-line 1)
5667 (skip-chars-forward " \t")
5668 (setq ind (current-column))
5669 (if (catch 'exit
5670 (while t
5671 (beginning-of-line 0)
5672 (if (or (bobp) (< (point) limit)) (throw 'exit nil))
5674 (if (looking-at "[ \t]*$")
5675 (setq ind1 ind-empty)
5676 (skip-chars-forward " \t")
5677 (setq ind1 (current-column)))
5678 (if (< ind1 ind)
5679 (progn (beginning-of-line 1) (throw 'exit (org-at-item-p))))))
5681 (goto-char pos)
5682 (error "Not in an item")))))
5684 (defun org-end-of-item ()
5685 "Go to the end of the current hand-formatted item.
5686 If the cursor is not in an item, throw an error."
5687 (interactive)
5688 (let* ((pos (point))
5689 ind1
5690 (ind-empty (if org-empty-line-terminates-plain-lists 0 10000))
5691 (limit (save-excursion (outline-next-heading) (point)))
5692 (ind (save-excursion
5693 (org-beginning-of-item)
5694 (skip-chars-forward " \t")
5695 (current-column)))
5696 (end (catch 'exit
5697 (while t
5698 (beginning-of-line 2)
5699 (if (eobp) (throw 'exit (point)))
5700 (if (>= (point) limit) (throw 'exit (point-at-bol)))
5701 (if (looking-at "[ \t]*$")
5702 (setq ind1 ind-empty)
5703 (skip-chars-forward " \t")
5704 (setq ind1 (current-column)))
5705 (if (<= ind1 ind)
5706 (throw 'exit (point-at-bol)))))))
5707 (if end
5708 (goto-char end)
5709 (goto-char pos)
5710 (error "Not in an item"))))
5712 (defun org-next-item ()
5713 "Move to the beginning of the next item in the current plain list.
5714 Error if not at a plain list, or if this is the last item in the list."
5715 (interactive)
5716 (let (ind ind1 (pos (point)))
5717 (org-beginning-of-item)
5718 (setq ind (org-get-indentation))
5719 (org-end-of-item)
5720 (setq ind1 (org-get-indentation))
5721 (unless (and (org-at-item-p) (= ind ind1))
5722 (goto-char pos)
5723 (error "On last item"))))
5725 (defun org-previous-item ()
5726 "Move to the beginning of the previous item in the current plain list.
5727 Error if not at a plain list, or if this is the first item in the list."
5728 (interactive)
5729 (let (beg ind ind1 (pos (point)))
5730 (org-beginning-of-item)
5731 (setq beg (point))
5732 (setq ind (org-get-indentation))
5733 (goto-char beg)
5734 (catch 'exit
5735 (while t
5736 (beginning-of-line 0)
5737 (if (looking-at "[ \t]*$")
5739 (if (<= (setq ind1 (org-get-indentation)) ind)
5740 (throw 'exit t)))))
5741 (condition-case nil
5742 (if (or (not (org-at-item-p))
5743 (< ind1 (1- ind)))
5744 (error "")
5745 (org-beginning-of-item))
5746 (error (goto-char pos)
5747 (error "On first item")))))
5749 (defun org-first-list-item-p ()
5750 "Is this heading the item in a plain list?"
5751 (unless (org-at-item-p)
5752 (error "Not at a plain list item"))
5753 (org-beginning-of-item)
5754 (= (point) (save-excursion (org-beginning-of-item-list))))
5756 (defun org-move-item-down ()
5757 "Move the plain list item at point down, i.e. swap with following item.
5758 Subitems (items with larger indentation) are considered part of the item,
5759 so this really moves item trees."
5760 (interactive)
5761 (let (beg beg0 end end0 ind ind1 (pos (point)) txt ne-end ne-beg)
5762 (org-beginning-of-item)
5763 (setq beg0 (point))
5764 (save-excursion
5765 (setq ne-beg (org-back-over-empty-lines))
5766 (setq beg (point)))
5767 (goto-char beg0)
5768 (setq ind (org-get-indentation))
5769 (org-end-of-item)
5770 (setq end0 (point))
5771 (setq ind1 (org-get-indentation))
5772 (setq ne-end (org-back-over-empty-lines))
5773 (setq end (point))
5774 (goto-char beg0)
5775 (when (and (org-first-list-item-p) (< ne-end ne-beg))
5776 ;; include less whitespace
5777 (save-excursion
5778 (goto-char beg)
5779 (forward-line (- ne-beg ne-end))
5780 (setq beg (point))))
5781 (goto-char end0)
5782 (if (and (org-at-item-p) (= ind ind1))
5783 (progn
5784 (org-end-of-item)
5785 (org-back-over-empty-lines)
5786 (setq txt (buffer-substring beg end))
5787 (save-excursion
5788 (delete-region beg end))
5789 (setq pos (point))
5790 (insert txt)
5791 (goto-char pos) (org-skip-whitespace)
5792 (org-maybe-renumber-ordered-list))
5793 (goto-char pos)
5794 (error "Cannot move this item further down"))))
5796 (defun org-move-item-up (arg)
5797 "Move the plain list item at point up, i.e. swap with previous item.
5798 Subitems (items with larger indentation) are considered part of the item,
5799 so this really moves item trees."
5800 (interactive "p")
5801 (let (beg beg0 end ind ind1 (pos (point)) txt
5802 ne-beg ne-ins ins-end)
5803 (org-beginning-of-item)
5804 (setq beg0 (point))
5805 (setq ind (org-get-indentation))
5806 (save-excursion
5807 (setq ne-beg (org-back-over-empty-lines))
5808 (setq beg (point)))
5809 (goto-char beg0)
5810 (org-end-of-item)
5811 (setq end (point))
5812 (goto-char beg0)
5813 (catch 'exit
5814 (while t
5815 (beginning-of-line 0)
5816 (if (looking-at "[ \t]*$")
5817 (if org-empty-line-terminates-plain-lists
5818 (progn
5819 (goto-char pos)
5820 (error "Cannot move this item further up"))
5821 nil)
5822 (if (<= (setq ind1 (org-get-indentation)) ind)
5823 (throw 'exit t)))))
5824 (condition-case nil
5825 (org-beginning-of-item)
5826 (error (goto-char beg)
5827 (error "Cannot move this item further up")))
5828 (setq ind1 (org-get-indentation))
5829 (if (and (org-at-item-p) (= ind ind1))
5830 (progn
5831 (setq ne-ins (org-back-over-empty-lines))
5832 (setq txt (buffer-substring beg end))
5833 (save-excursion
5834 (delete-region beg end))
5835 (setq pos (point))
5836 (insert txt)
5837 (setq ins-end (point))
5838 (goto-char pos) (org-skip-whitespace)
5840 (when (and (org-first-list-item-p) (> ne-ins ne-beg))
5841 ;; Move whitespace back to beginning
5842 (save-excursion
5843 (goto-char ins-end)
5844 (let ((kill-whole-line t))
5845 (kill-line (- ne-ins ne-beg)) (point)))
5846 (insert (make-string (- ne-ins ne-beg) ?\n)))
5848 (org-maybe-renumber-ordered-list))
5849 (goto-char pos)
5850 (error "Cannot move this item further up"))))
5852 (defun org-maybe-renumber-ordered-list ()
5853 "Renumber the ordered list at point if setup allows it.
5854 This tests the user option `org-auto-renumber-ordered-lists' before
5855 doing the renumbering."
5856 (interactive)
5857 (when (and org-auto-renumber-ordered-lists
5858 (org-at-item-p))
5859 (if (match-beginning 3)
5860 (org-renumber-ordered-list 1)
5861 (org-fix-bullet-type))))
5863 (defun org-maybe-renumber-ordered-list-safe ()
5864 (condition-case nil
5865 (save-excursion
5866 (org-maybe-renumber-ordered-list))
5867 (error nil)))
5869 (defun org-cycle-list-bullet (&optional which)
5870 "Cycle through the different itemize/enumerate bullets.
5871 This cycle the entire list level through the sequence:
5873 `-' -> `+' -> `*' -> `1.' -> `1)'
5875 If WHICH is a string, use that as the new bullet. If WHICH is an integer,
5876 0 meand `-', 1 means `+' etc."
5877 (interactive "P")
5878 (org-preserve-lc
5879 (org-beginning-of-item-list)
5880 (org-at-item-p)
5881 (beginning-of-line 1)
5882 (let ((current (match-string 0))
5883 (prevp (eq which 'previous))
5884 new)
5885 (setq new (cond
5886 ((and (numberp which)
5887 (nth (1- which) '("-" "+" "*" "1." "1)"))))
5888 ((string-match "-" current) (if prevp "1)" "+"))
5889 ((string-match "\\+" current)
5890 (if prevp "-" (if (looking-at "\\S-") "1." "*")))
5891 ((string-match "\\*" current) (if prevp "+" "1."))
5892 ((string-match "\\." current) (if prevp "*" "1)"))
5893 ((string-match ")" current) (if prevp "1." "-"))
5894 (t (error "This should not happen"))))
5895 (and (looking-at "\\([ \t]*\\)\\S-+") (replace-match (concat "\\1" new)))
5896 (org-fix-bullet-type)
5897 (org-maybe-renumber-ordered-list))))
5899 (defun org-get-string-indentation (s)
5900 "What indentation has S due to SPACE and TAB at the beginning of the string?"
5901 (let ((n -1) (i 0) (w tab-width) c)
5902 (catch 'exit
5903 (while (< (setq n (1+ n)) (length s))
5904 (setq c (aref s n))
5905 (cond ((= c ?\ ) (setq i (1+ i)))
5906 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
5907 (t (throw 'exit t)))))
5910 (defun org-renumber-ordered-list (arg)
5911 "Renumber an ordered plain list.
5912 Cursor needs to be in the first line of an item, the line that starts
5913 with something like \"1.\" or \"2)\"."
5914 (interactive "p")
5915 (unless (and (org-at-item-p)
5916 (match-beginning 3))
5917 (error "This is not an ordered list"))
5918 (let ((line (org-current-line))
5919 (col (current-column))
5920 (ind (org-get-string-indentation
5921 (buffer-substring (point-at-bol) (match-beginning 3))))
5922 ;; (term (substring (match-string 3) -1))
5923 ind1 (n (1- arg))
5924 fmt)
5925 ;; find where this list begins
5926 (org-beginning-of-item-list)
5927 (looking-at "[ \t]*[0-9]+\\([.)]\\)")
5928 (setq fmt (concat "%d" (match-string 1)))
5929 (beginning-of-line 0)
5930 ;; walk forward and replace these numbers
5931 (catch 'exit
5932 (while t
5933 (catch 'next
5934 (beginning-of-line 2)
5935 (if (eobp) (throw 'exit nil))
5936 (if (looking-at "[ \t]*$") (throw 'next nil))
5937 (skip-chars-forward " \t") (setq ind1 (current-column))
5938 (if (> ind1 ind) (throw 'next t))
5939 (if (< ind1 ind) (throw 'exit t))
5940 (if (not (org-at-item-p)) (throw 'exit nil))
5941 (delete-region (match-beginning 2) (match-end 2))
5942 (goto-char (match-beginning 2))
5943 (insert (format fmt (setq n (1+ n)))))))
5944 (goto-line line)
5945 (move-to-column col)))
5947 (defun org-fix-bullet-type ()
5948 "Make sure all items in this list have the same bullet as the firsst item."
5949 (interactive)
5950 (unless (org-at-item-p) (error "This is not a list"))
5951 (let ((line (org-current-line))
5952 (col (current-column))
5953 (ind (current-indentation))
5954 ind1 bullet)
5955 ;; find where this list begins
5956 (org-beginning-of-item-list)
5957 (beginning-of-line 1)
5958 ;; find out what the bullet type is
5959 (looking-at "[ \t]*\\(\\S-+\\)")
5960 (setq bullet (match-string 1))
5961 ;; walk forward and replace these numbers
5962 (beginning-of-line 0)
5963 (catch 'exit
5964 (while t
5965 (catch 'next
5966 (beginning-of-line 2)
5967 (if (eobp) (throw 'exit nil))
5968 (if (looking-at "[ \t]*$") (throw 'next nil))
5969 (skip-chars-forward " \t") (setq ind1 (current-column))
5970 (if (> ind1 ind) (throw 'next t))
5971 (if (< ind1 ind) (throw 'exit t))
5972 (if (not (org-at-item-p)) (throw 'exit nil))
5973 (skip-chars-forward " \t")
5974 (looking-at "\\S-+")
5975 (replace-match bullet))))
5976 (goto-line line)
5977 (move-to-column col)
5978 (if (string-match "[0-9]" bullet)
5979 (org-renumber-ordered-list 1))))
5981 (defun org-beginning-of-item-list ()
5982 "Go to the beginning of the current item list.
5983 I.e. to the first item in this list."
5984 (interactive)
5985 (org-beginning-of-item)
5986 (let ((pos (point-at-bol))
5987 (ind (org-get-indentation))
5988 ind1)
5989 ;; find where this list begins
5990 (catch 'exit
5991 (while t
5992 (catch 'next
5993 (beginning-of-line 0)
5994 (if (looking-at "[ \t]*$")
5995 (throw (if (bobp) 'exit 'next) t))
5996 (skip-chars-forward " \t") (setq ind1 (current-column))
5997 (if (or (< ind1 ind)
5998 (and (= ind1 ind)
5999 (not (org-at-item-p)))
6000 (bobp))
6001 (throw 'exit t)
6002 (when (org-at-item-p) (setq pos (point-at-bol)))))))
6003 (goto-char pos)))
6006 (defun org-end-of-item-list ()
6007 "Go to the end of the current item list.
6008 I.e. to the text after the last item."
6009 (interactive)
6010 (org-beginning-of-item)
6011 (let ((pos (point-at-bol))
6012 (ind (org-get-indentation))
6013 ind1)
6014 ;; find where this list begins
6015 (catch 'exit
6016 (while t
6017 (catch 'next
6018 (beginning-of-line 2)
6019 (if (looking-at "[ \t]*$")
6020 (throw (if (eobp) 'exit 'next) t))
6021 (skip-chars-forward " \t") (setq ind1 (current-column))
6022 (if (or (< ind1 ind)
6023 (and (= ind1 ind)
6024 (not (org-at-item-p)))
6025 (eobp))
6026 (progn
6027 (setq pos (point-at-bol))
6028 (throw 'exit t))))))
6029 (goto-char pos)))
6032 (defvar org-last-indent-begin-marker (make-marker))
6033 (defvar org-last-indent-end-marker (make-marker))
6035 (defun org-outdent-item (arg)
6036 "Outdent a local list item."
6037 (interactive "p")
6038 (org-indent-item (- arg)))
6040 (defun org-indent-item (arg)
6041 "Indent a local list item."
6042 (interactive "p")
6043 (unless (org-at-item-p)
6044 (error "Not on an item"))
6045 (save-excursion
6046 (let (beg end ind ind1 tmp delta ind-down ind-up)
6047 (if (memq last-command '(org-shiftmetaright org-shiftmetaleft))
6048 (setq beg org-last-indent-begin-marker
6049 end org-last-indent-end-marker)
6050 (org-beginning-of-item)
6051 (setq beg (move-marker org-last-indent-begin-marker (point)))
6052 (org-end-of-item)
6053 (setq end (move-marker org-last-indent-end-marker (point))))
6054 (goto-char beg)
6055 (setq tmp (org-item-indent-positions)
6056 ind (car tmp)
6057 ind-down (nth 2 tmp)
6058 ind-up (nth 1 tmp)
6059 delta (if (> arg 0)
6060 (if ind-down (- ind-down ind) 2)
6061 (if ind-up (- ind-up ind) -2)))
6062 (if (< (+ delta ind) 0) (error "Cannot outdent beyond margin"))
6063 (while (< (point) end)
6064 (beginning-of-line 1)
6065 (skip-chars-forward " \t") (setq ind1 (current-column))
6066 (delete-region (point-at-bol) (point))
6067 (or (eolp) (indent-to-column (+ ind1 delta)))
6068 (beginning-of-line 2))))
6069 (org-fix-bullet-type)
6070 (org-maybe-renumber-ordered-list-safe)
6071 (save-excursion
6072 (beginning-of-line 0)
6073 (condition-case nil (org-beginning-of-item) (error nil))
6074 (org-maybe-renumber-ordered-list-safe)))
6076 (defun org-item-indent-positions ()
6077 "Return indentation for plain list items.
6078 This returns a list with three values: The current indentation, the
6079 parent indentation and the indentation a child should habe.
6080 Assumes cursor in item line."
6081 (let* ((bolpos (point-at-bol))
6082 (ind (org-get-indentation))
6083 ind-down ind-up pos)
6084 (save-excursion
6085 (org-beginning-of-item-list)
6086 (skip-chars-backward "\n\r \t")
6087 (when (org-in-item-p)
6088 (org-beginning-of-item)
6089 (setq ind-up (org-get-indentation))))
6090 (setq pos (point))
6091 (save-excursion
6092 (cond
6093 ((and (condition-case nil (progn (org-previous-item) t)
6094 (error nil))
6095 (or (forward-char 1) t)
6096 (re-search-forward "^\\([ \t]*\\([-+]\\|\\([0-9]+[.)]\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)" bolpos t))
6097 (setq ind-down (org-get-indentation)))
6098 ((and (goto-char pos)
6099 (org-at-item-p))
6100 (goto-char (match-end 0))
6101 (skip-chars-forward " \t")
6102 (setq ind-down (current-column)))))
6103 (list ind ind-up ind-down)))
6105 ;;; The orgstruct minor mode
6107 ;; Define a minor mode which can be used in other modes in order to
6108 ;; integrate the org-mode structure editing commands.
6110 ;; This is really a hack, because the org-mode structure commands use
6111 ;; keys which normally belong to the major mode. Here is how it
6112 ;; works: The minor mode defines all the keys necessary to operate the
6113 ;; structure commands, but wraps the commands into a function which
6114 ;; tests if the cursor is currently at a headline or a plain list
6115 ;; item. If that is the case, the structure command is used,
6116 ;; temporarily setting many Org-mode variables like regular
6117 ;; expressions for filling etc. However, when any of those keys is
6118 ;; used at a different location, function uses `key-binding' to look
6119 ;; up if the key has an associated command in another currently active
6120 ;; keymap (minor modes, major mode, global), and executes that
6121 ;; command. There might be problems if any of the keys is otherwise
6122 ;; used as a prefix key.
6124 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
6125 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
6126 ;; addresses this by checking explicitly for both bindings.
6128 (defvar orgstruct-mode-map (make-sparse-keymap)
6129 "Keymap for the minor `orgstruct-mode'.")
6131 (defvar org-local-vars nil
6132 "List of local variables, for use by `orgstruct-mode'")
6134 ;;;###autoload
6135 (define-minor-mode orgstruct-mode
6136 "Toggle the minor more `orgstruct-mode'.
6137 This mode is for using Org-mode structure commands in other modes.
6138 The following key behave as if Org-mode was active, if the cursor
6139 is on a headline, or on a plain list item (both in the definition
6140 of Org-mode).
6142 M-up Move entry/item up
6143 M-down Move entry/item down
6144 M-left Promote
6145 M-right Demote
6146 M-S-up Move entry/item up
6147 M-S-down Move entry/item down
6148 M-S-left Promote subtree
6149 M-S-right Demote subtree
6150 M-q Fill paragraph and items like in Org-mode
6151 C-c ^ Sort entries
6152 C-c - Cycle list bullet
6153 TAB Cycle item visibility
6154 M-RET Insert new heading/item
6155 S-M-RET Insert new TODO heading / Chekbox item
6156 C-c C-c Set tags / toggle checkbox"
6157 nil " OrgStruct" nil
6158 (org-load-modules-maybe)
6159 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
6161 ;;;###autoload
6162 (defun turn-on-orgstruct ()
6163 "Unconditionally turn on `orgstruct-mode'."
6164 (orgstruct-mode 1))
6166 ;;;###autoload
6167 (defun turn-on-orgstruct++ ()
6168 "Unconditionally turn on `orgstruct-mode', and force org-mode indentations.
6169 In addition to setting orgstruct-mode, this also exports all indentation and
6170 autofilling variables from org-mode into the buffer. Note that turning
6171 off orgstruct-mode will *not* remove these additional settings."
6172 (orgstruct-mode 1)
6173 (let (var val)
6174 (mapc
6175 (lambda (x)
6176 (when (string-match
6177 "^\\(paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
6178 (symbol-name (car x)))
6179 (setq var (car x) val (nth 1 x))
6180 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
6181 org-local-vars)))
6183 (defun orgstruct-error ()
6184 "Error when there is no default binding for a structure key."
6185 (interactive)
6186 (error "This key has no function outside structure elements"))
6188 (defun orgstruct-setup ()
6189 "Setup orgstruct keymaps."
6190 (let ((nfunc 0)
6191 (bindings
6192 (list
6193 '([(meta up)] org-metaup)
6194 '([(meta down)] org-metadown)
6195 '([(meta left)] org-metaleft)
6196 '([(meta right)] org-metaright)
6197 '([(meta shift up)] org-shiftmetaup)
6198 '([(meta shift down)] org-shiftmetadown)
6199 '([(meta shift left)] org-shiftmetaleft)
6200 '([(meta shift right)] org-shiftmetaright)
6201 '([(shift up)] org-shiftup)
6202 '([(shift down)] org-shiftdown)
6203 '("\C-c\C-c" org-ctrl-c-ctrl-c)
6204 '("\M-q" fill-paragraph)
6205 '("\C-c^" org-sort)
6206 '("\C-c-" org-cycle-list-bullet)))
6207 elt key fun cmd)
6208 (while (setq elt (pop bindings))
6209 (setq nfunc (1+ nfunc))
6210 (setq key (org-key (car elt))
6211 fun (nth 1 elt)
6212 cmd (orgstruct-make-binding fun nfunc key))
6213 (org-defkey orgstruct-mode-map key cmd))
6215 ;; Special treatment needed for TAB and RET
6216 (org-defkey orgstruct-mode-map [(tab)]
6217 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
6218 (org-defkey orgstruct-mode-map "\C-i"
6219 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
6221 (org-defkey orgstruct-mode-map "\M-\C-m"
6222 (orgstruct-make-binding 'org-insert-heading 105
6223 "\M-\C-m" [(meta return)]))
6224 (org-defkey orgstruct-mode-map [(meta return)]
6225 (orgstruct-make-binding 'org-insert-heading 106
6226 [(meta return)] "\M-\C-m"))
6228 (org-defkey orgstruct-mode-map [(shift meta return)]
6229 (orgstruct-make-binding 'org-insert-todo-heading 107
6230 [(meta return)] "\M-\C-m"))
6232 (unless org-local-vars
6233 (setq org-local-vars (org-get-local-variables)))
6237 (defun orgstruct-make-binding (fun n &rest keys)
6238 "Create a function for binding in the structure minor mode.
6239 FUN is the command to call inside a table. N is used to create a unique
6240 command name. KEYS are keys that should be checked in for a command
6241 to execute outside of tables."
6242 (eval
6243 (list 'defun
6244 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
6245 '(arg)
6246 (concat "In Structure, run `" (symbol-name fun) "'.\n"
6247 "Outside of structure, run the binding of `"
6248 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
6249 "'.")
6250 '(interactive "p")
6251 (list 'if
6252 '(org-context-p 'headline 'item)
6253 (list 'org-run-like-in-org-mode (list 'quote fun))
6254 (list 'let '(orgstruct-mode)
6255 (list 'call-interactively
6256 (append '(or)
6257 (mapcar (lambda (k)
6258 (list 'key-binding k))
6259 keys)
6260 '('orgstruct-error))))))))
6262 (defun org-context-p (&rest contexts)
6263 "Check if local context is and of CONTEXTS.
6264 Possible values in the list of contexts are `table', `headline', and `item'."
6265 (let ((pos (point)))
6266 (goto-char (point-at-bol))
6267 (prog1 (or (and (memq 'table contexts)
6268 (looking-at "[ \t]*|"))
6269 (and (memq 'headline contexts)
6270 (looking-at "\\*+"))
6271 (and (memq 'item contexts)
6272 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)")))
6273 (goto-char pos))))
6275 (defun org-get-local-variables ()
6276 "Return a list of all local variables in an org-mode buffer."
6277 (let (varlist)
6278 (with-current-buffer (get-buffer-create "*Org tmp*")
6279 (erase-buffer)
6280 (org-mode)
6281 (setq varlist (buffer-local-variables)))
6282 (kill-buffer "*Org tmp*")
6283 (delq nil
6284 (mapcar
6285 (lambda (x)
6286 (setq x
6287 (if (symbolp x)
6288 (list x)
6289 (list (car x) (list 'quote (cdr x)))))
6290 (if (string-match
6291 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
6292 (symbol-name (car x)))
6293 x nil))
6294 varlist))))
6296 ;;;###autoload
6297 (defun org-run-like-in-org-mode (cmd)
6298 (org-load-modules-maybe)
6299 (unless org-local-vars
6300 (setq org-local-vars (org-get-local-variables)))
6301 (eval (list 'let org-local-vars
6302 (list 'call-interactively (list 'quote cmd)))))
6304 ;;;; Archiving
6306 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
6308 (defun org-archive-subtree (&optional find-done)
6309 "Move the current subtree to the archive.
6310 The archive can be a certain top-level heading in the current file, or in
6311 a different file. The tree will be moved to that location, the subtree
6312 heading be marked DONE, and the current time will be added.
6314 When called with prefix argument FIND-DONE, find whole trees without any
6315 open TODO items and archive them (after getting confirmation from the user).
6316 If the cursor is not at a headline when this comand is called, try all level
6317 1 trees. If the cursor is on a headline, only try the direct children of
6318 this heading."
6319 (interactive "P")
6320 (if find-done
6321 (org-archive-all-done)
6322 ;; Save all relevant TODO keyword-relatex variables
6324 (let ((tr-org-todo-line-regexp org-todo-line-regexp) ; keep despite compiler
6325 (tr-org-todo-keywords-1 org-todo-keywords-1)
6326 (tr-org-todo-kwd-alist org-todo-kwd-alist)
6327 (tr-org-done-keywords org-done-keywords)
6328 (tr-org-todo-regexp org-todo-regexp)
6329 (tr-org-todo-line-regexp org-todo-line-regexp)
6330 (tr-org-odd-levels-only org-odd-levels-only)
6331 (this-buffer (current-buffer))
6332 (org-archive-location org-archive-location)
6333 (re "^#\\+ARCHIVE:[ \t]+\\(\\S-.*\\S-\\)[ \t]*$")
6334 ;; start of variables that will be used for saving context
6335 ;; The compiler complains about them - keep them anyway!
6336 (file (abbreviate-file-name (buffer-file-name)))
6337 (olpath (mapconcat 'identity (org-get-outline-path) "/"))
6338 (time (format-time-string
6339 (substring (cdr org-time-stamp-formats) 1 -1)
6340 (current-time)))
6341 afile heading buffer level newfile-p
6342 category todo priority
6343 ;; start of variables that will be used for savind context
6344 ltags itags prop)
6346 ;; Try to find a local archive location
6347 (save-excursion
6348 (save-restriction
6349 (widen)
6350 (setq prop (org-entry-get nil "ARCHIVE" 'inherit))
6351 (if (and prop (string-match "\\S-" prop))
6352 (setq org-archive-location prop)
6353 (if (or (re-search-backward re nil t)
6354 (re-search-forward re nil t))
6355 (setq org-archive-location (match-string 1))))))
6357 (if (string-match "\\(.*\\)::\\(.*\\)" org-archive-location)
6358 (progn
6359 (setq afile (format (match-string 1 org-archive-location)
6360 (file-name-nondirectory buffer-file-name))
6361 heading (match-string 2 org-archive-location)))
6362 (error "Invalid `org-archive-location'"))
6363 (if (> (length afile) 0)
6364 (setq newfile-p (not (file-exists-p afile))
6365 buffer (find-file-noselect afile))
6366 (setq buffer (current-buffer)))
6367 (unless buffer
6368 (error "Cannot access file \"%s\"" afile))
6369 (if (and (> (length heading) 0)
6370 (string-match "^\\*+" heading))
6371 (setq level (match-end 0))
6372 (setq heading nil level 0))
6373 (save-excursion
6374 (org-back-to-heading t)
6375 ;; Get context information that will be lost by moving the tree
6376 (org-refresh-category-properties)
6377 (setq category (org-get-category)
6378 todo (and (looking-at org-todo-line-regexp)
6379 (match-string 2))
6380 priority (org-get-priority (if (match-end 3) (match-string 3) ""))
6381 ltags (org-get-tags)
6382 itags (org-delete-all ltags (org-get-tags-at)))
6383 (setq ltags (mapconcat 'identity ltags " ")
6384 itags (mapconcat 'identity itags " "))
6385 ;; We first only copy, in case something goes wrong
6386 ;; we need to protect this-command, to avoid kill-region sets it,
6387 ;; which would lead to duplication of subtrees
6388 (let (this-command) (org-copy-subtree))
6389 (set-buffer buffer)
6390 ;; Enforce org-mode for the archive buffer
6391 (if (not (org-mode-p))
6392 ;; Force the mode for future visits.
6393 (let ((org-insert-mode-line-in-empty-file t)
6394 (org-inhibit-startup t))
6395 (call-interactively 'org-mode)))
6396 (when newfile-p
6397 (goto-char (point-max))
6398 (insert (format "\nArchived entries from file %s\n\n"
6399 (buffer-file-name this-buffer))))
6400 ;; Force the TODO keywords of the original buffer
6401 (let ((org-todo-line-regexp tr-org-todo-line-regexp)
6402 (org-todo-keywords-1 tr-org-todo-keywords-1)
6403 (org-todo-kwd-alist tr-org-todo-kwd-alist)
6404 (org-done-keywords tr-org-done-keywords)
6405 (org-todo-regexp tr-org-todo-regexp)
6406 (org-todo-line-regexp tr-org-todo-line-regexp)
6407 (org-odd-levels-only
6408 (if (local-variable-p 'org-odd-levels-only (current-buffer))
6409 org-odd-levels-only
6410 tr-org-odd-levels-only)))
6411 (goto-char (point-min))
6412 (show-all)
6413 (if heading
6414 (progn
6415 (if (re-search-forward
6416 (concat "^" (regexp-quote heading)
6417 (org-re "[ \t]*\\(:[[:alnum:]_@:]+:\\)?[ \t]*\\($\\|\r\\)"))
6418 nil t)
6419 (goto-char (match-end 0))
6420 ;; Heading not found, just insert it at the end
6421 (goto-char (point-max))
6422 (or (bolp) (insert "\n"))
6423 (insert "\n" heading "\n")
6424 (end-of-line 0))
6425 ;; Make the subtree visible
6426 (show-subtree)
6427 (org-end-of-subtree t)
6428 (skip-chars-backward " \t\r\n")
6429 (and (looking-at "[ \t\r\n]*")
6430 (replace-match "\n\n")))
6431 ;; No specific heading, just go to end of file.
6432 (goto-char (point-max)) (insert "\n"))
6433 ;; Paste
6434 (org-paste-subtree (org-get-valid-level level 1))
6436 ;; Mark the entry as done
6437 (when (and org-archive-mark-done
6438 (looking-at org-todo-line-regexp)
6439 (or (not (match-end 2))
6440 (not (member (match-string 2) org-done-keywords))))
6441 (let (org-log-done org-todo-log-states)
6442 (org-todo
6443 (car (or (member org-archive-mark-done org-done-keywords)
6444 org-done-keywords)))))
6446 ;; Add the context info
6447 (when org-archive-save-context-info
6448 (let ((l org-archive-save-context-info) e n v)
6449 (while (setq e (pop l))
6450 (when (and (setq v (symbol-value e))
6451 (stringp v) (string-match "\\S-" v))
6452 (setq n (concat "ARCHIVE_" (upcase (symbol-name e))))
6453 (org-entry-put (point) n v)))))
6455 ;; Save and kill the buffer, if it is not the same buffer.
6456 (if (not (eq this-buffer buffer))
6457 (progn (save-buffer) (kill-buffer buffer)))))
6458 ;; Here we are back in the original buffer. Everything seems to have
6459 ;; worked. So now cut the tree and finish up.
6460 (let (this-command) (org-cut-subtree))
6461 (if (and (not (eobp)) (looking-at "[ \t]*$")) (kill-line))
6462 (message "Subtree archived %s"
6463 (if (eq this-buffer buffer)
6464 (concat "under heading: " heading)
6465 (concat "in file: " (abbreviate-file-name afile)))))))
6467 (defun org-refresh-category-properties ()
6468 "Refresh category text properties in teh buffer."
6469 (let ((def-cat (cond
6470 ((null org-category)
6471 (if buffer-file-name
6472 (file-name-sans-extension
6473 (file-name-nondirectory buffer-file-name))
6474 "???"))
6475 ((symbolp org-category) (symbol-name org-category))
6476 (t org-category)))
6477 beg end cat pos optionp)
6478 (org-unmodified
6479 (save-excursion
6480 (save-restriction
6481 (widen)
6482 (goto-char (point-min))
6483 (put-text-property (point) (point-max) 'org-category def-cat)
6484 (while (re-search-forward
6485 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
6486 (setq pos (match-end 0)
6487 optionp (equal (char-after (match-beginning 0)) ?#)
6488 cat (org-trim (match-string 2)))
6489 (if optionp
6490 (setq beg (point-at-bol) end (point-max))
6491 (org-back-to-heading t)
6492 (setq beg (point) end (org-end-of-subtree t t)))
6493 (put-text-property beg end 'org-category cat)
6494 (goto-char pos)))))))
6496 (defun org-archive-all-done (&optional tag)
6497 "Archive sublevels of the current tree without open TODO items.
6498 If the cursor is not on a headline, try all level 1 trees. If
6499 it is on a headline, try all direct children.
6500 When TAG is non-nil, don't move trees, but mark them with the ARCHIVE tag."
6501 (let ((re (concat "^\\*+ +" org-not-done-regexp)) re1
6502 (rea (concat ".*:" org-archive-tag ":"))
6503 (begm (make-marker))
6504 (endm (make-marker))
6505 (question (if tag "Set ARCHIVE tag (no open TODO items)? "
6506 "Move subtree to archive (no open TODO items)? "))
6507 beg end (cntarch 0))
6508 (if (org-on-heading-p)
6509 (progn
6510 (setq re1 (concat "^" (regexp-quote
6511 (make-string
6512 (1+ (- (match-end 0) (match-beginning 0) 1))
6513 ?*))
6514 " "))
6515 (move-marker begm (point))
6516 (move-marker endm (org-end-of-subtree t)))
6517 (setq re1 "^* ")
6518 (move-marker begm (point-min))
6519 (move-marker endm (point-max)))
6520 (save-excursion
6521 (goto-char begm)
6522 (while (re-search-forward re1 endm t)
6523 (setq beg (match-beginning 0)
6524 end (save-excursion (org-end-of-subtree t) (point)))
6525 (goto-char beg)
6526 (if (re-search-forward re end t)
6527 (goto-char end)
6528 (goto-char beg)
6529 (if (and (or (not tag) (not (looking-at rea)))
6530 (y-or-n-p question))
6531 (progn
6532 (if tag
6533 (org-toggle-tag org-archive-tag 'on)
6534 (org-archive-subtree))
6535 (setq cntarch (1+ cntarch)))
6536 (goto-char end)))))
6537 (message "%d trees archived" cntarch)))
6539 (defun org-cycle-hide-drawers (state)
6540 "Re-hide all drawers after a visibility state change."
6541 (when (and (org-mode-p)
6542 (not (memq state '(overview folded))))
6543 (save-excursion
6544 (let* ((globalp (memq state '(contents all)))
6545 (beg (if globalp (point-min) (point)))
6546 (end (if globalp (point-max) (org-end-of-subtree t))))
6547 (goto-char beg)
6548 (while (re-search-forward org-drawer-regexp end t)
6549 (org-flag-drawer t))))))
6551 (defun org-flag-drawer (flag)
6552 (save-excursion
6553 (beginning-of-line 1)
6554 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
6555 (let ((b (match-end 0))
6556 (outline-regexp org-outline-regexp))
6557 (if (re-search-forward
6558 "^[ \t]*:END:"
6559 (save-excursion (outline-next-heading) (point)) t)
6560 (outline-flag-region b (point-at-eol) flag)
6561 (error ":END: line missing"))))))
6563 (defun org-cycle-hide-archived-subtrees (state)
6564 "Re-hide all archived subtrees after a visibility state change."
6565 (when (and (not org-cycle-open-archived-trees)
6566 (not (memq state '(overview folded))))
6567 (save-excursion
6568 (let* ((globalp (memq state '(contents all)))
6569 (beg (if globalp (point-min) (point)))
6570 (end (if globalp (point-max) (org-end-of-subtree t))))
6571 (org-hide-archived-subtrees beg end)
6572 (goto-char beg)
6573 (if (looking-at (concat ".*:" org-archive-tag ":"))
6574 (message "%s" (substitute-command-keys
6575 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
6577 (defun org-force-cycle-archived ()
6578 "Cycle subtree even if it is archived."
6579 (interactive)
6580 (setq this-command 'org-cycle)
6581 (let ((org-cycle-open-archived-trees t))
6582 (call-interactively 'org-cycle)))
6584 (defun org-hide-archived-subtrees (beg end)
6585 "Re-hide all archived subtrees after a visibility state change."
6586 (save-excursion
6587 (let* ((re (concat ":" org-archive-tag ":")))
6588 (goto-char beg)
6589 (while (re-search-forward re end t)
6590 (and (org-on-heading-p) (hide-subtree))
6591 (org-end-of-subtree t)))))
6593 (defun org-toggle-tag (tag &optional onoff)
6594 "Toggle the tag TAG for the current line.
6595 If ONOFF is `on' or `off', don't toggle but set to this state."
6596 (unless (org-on-heading-p t) (error "Not on headling"))
6597 (let (res current)
6598 (save-excursion
6599 (beginning-of-line)
6600 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t]*$")
6601 (point-at-eol) t)
6602 (progn
6603 (setq current (match-string 1))
6604 (replace-match ""))
6605 (setq current ""))
6606 (setq current (nreverse (org-split-string current ":")))
6607 (cond
6608 ((eq onoff 'on)
6609 (setq res t)
6610 (or (member tag current) (push tag current)))
6611 ((eq onoff 'off)
6612 (or (not (member tag current)) (setq current (delete tag current))))
6613 (t (if (member tag current)
6614 (setq current (delete tag current))
6615 (setq res t)
6616 (push tag current))))
6617 (end-of-line 1)
6618 (if current
6619 (progn
6620 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
6621 (org-set-tags nil t))
6622 (delete-horizontal-space))
6623 (run-hooks 'org-after-tags-change-hook))
6624 res))
6626 (defun org-toggle-archive-tag (&optional arg)
6627 "Toggle the archive tag for the current headline.
6628 With prefix ARG, check all children of current headline and offer tagging
6629 the children that do not contain any open TODO items."
6630 (interactive "P")
6631 (if arg
6632 (org-archive-all-done 'tag)
6633 (let (set)
6634 (save-excursion
6635 (org-back-to-heading t)
6636 (setq set (org-toggle-tag org-archive-tag))
6637 (when set (hide-subtree)))
6638 (and set (beginning-of-line 1))
6639 (message "Subtree %s" (if set "archived" "unarchived")))))
6641 ;;;; Link Stuff
6643 ;;; Link abbreviations
6645 (defun org-link-expand-abbrev (link)
6646 "Apply replacements as defined in `org-link-abbrev-alist."
6647 (if (string-match "^\\([a-zA-Z][-_a-zA-Z0-9]*\\)\\(::?\\(.*\\)\\)?$" link)
6648 (let* ((key (match-string 1 link))
6649 (as (or (assoc key org-link-abbrev-alist-local)
6650 (assoc key org-link-abbrev-alist)))
6651 (tag (and (match-end 2) (match-string 3 link)))
6652 rpl)
6653 (if (not as)
6654 link
6655 (setq rpl (cdr as))
6656 (cond
6657 ((symbolp rpl) (funcall rpl tag))
6658 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
6659 (t (concat rpl tag)))))
6660 link))
6662 ;;; Storing and inserting links
6664 (defvar org-insert-link-history nil
6665 "Minibuffer history for links inserted with `org-insert-link'.")
6667 (defvar org-stored-links nil
6668 "Contains the links stored with `org-store-link'.")
6670 (defvar org-store-link-plist nil
6671 "Plist with info about the most recently link created with `org-store-link'.")
6673 (defvar org-link-protocols nil
6674 "Link protocols added to Org-mode using `org-add-link-type'.")
6676 (defvar org-store-link-functions nil
6677 "List of functions that are called to create and store a link.
6678 Each function will be called in turn until one returns a non-nil
6679 value. Each function should check if it is responsible for creating
6680 this link (for example by looking at the major mode).
6681 If not, it must exit and return nil.
6682 If yes, it should return a non-nil value after a calling
6683 `org-store-link-props' with a list of properties and values.
6684 Special properties are:
6686 :type The link prefix. like \"http\". This must be given.
6687 :link The link, like \"http://www.astro.uva.nl/~dominik\".
6688 This is obligatory as well.
6689 :description Optional default description for the second pair
6690 of brackets in an Org-mode link. The user can still change
6691 this when inserting this link into an Org-mode buffer.
6693 In addition to these, any additional properties can be specified
6694 and then used in remember templates.")
6696 (defun org-add-link-type (type &optional follow export)
6697 "Add TYPE to the list of `org-link-types'.
6698 Re-compute all regular expressions depending on `org-link-types'
6700 FOLLOW and EXPORT are two functions.
6702 FOLLOW should take the link path as the single argument and do whatever
6703 is necessary to follow the link, for example find a file or display
6704 a mail message.
6706 EXPORT should format the link path for export to one of the export formats.
6707 It should be a function accepting three arguments:
6709 path the path of the link, the text after the prefix (like \"http:\")
6710 desc the description of the link, if any, nil if there was no descripton
6711 format the export format, a symbol like `html' or `latex'.
6713 The function may use the FORMAT information to return different values
6714 depending on the format. The return value will be put literally into
6715 the exported file.
6716 Org-mode has a built-in default for exporting links. If you are happy with
6717 this default, there is no need to define an export function for the link
6718 type. For a simple example of an export function, see `org-bbdb.el'."
6719 (add-to-list 'org-link-types type t)
6720 (org-make-link-regexps)
6721 (if (assoc type org-link-protocols)
6722 (setcdr (assoc type org-link-protocols) (list follow export))
6723 (push (list type follow export) org-link-protocols)))
6726 ;;;###autoload
6727 (defun org-store-link (arg)
6728 "\\<org-mode-map>Store an org-link to the current location.
6729 This link is added to `org-stored-links' and can later be inserted
6730 into an org-buffer with \\[org-insert-link].
6732 For some link types, a prefix arg is interpreted:
6733 For links to usenet articles, arg negates `org-usenet-links-prefer-google'.
6734 For file links, arg negates `org-context-in-file-links'."
6735 (interactive "P")
6736 (org-load-modules-maybe)
6737 (setq org-store-link-plist nil) ; reset
6738 (let (link cpltxt desc description search txt)
6739 (cond
6741 ((run-hook-with-args-until-success 'org-store-link-functions)
6742 (setq link (plist-get org-store-link-plist :link)
6743 desc (or (plist-get org-store-link-plist :description) link)))
6745 ((eq major-mode 'calendar-mode)
6746 (let ((cd (calendar-cursor-to-date)))
6747 (setq link
6748 (format-time-string
6749 (car org-time-stamp-formats)
6750 (apply 'encode-time
6751 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
6752 nil nil nil))))
6753 (org-store-link-props :type "calendar" :date cd)))
6755 ((eq major-mode 'w3-mode)
6756 (setq cpltxt (url-view-url t)
6757 link (org-make-link cpltxt))
6758 (org-store-link-props :type "w3" :url (url-view-url t)))
6760 ((eq major-mode 'w3m-mode)
6761 (setq cpltxt (or w3m-current-title w3m-current-url)
6762 link (org-make-link w3m-current-url))
6763 (org-store-link-props :type "w3m" :url (url-view-url t)))
6765 ((setq search (run-hook-with-args-until-success
6766 'org-create-file-search-functions))
6767 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
6768 "::" search))
6769 (setq cpltxt (or description link)))
6771 ((eq major-mode 'image-mode)
6772 (setq cpltxt (concat "file:"
6773 (abbreviate-file-name buffer-file-name))
6774 link (org-make-link cpltxt))
6775 (org-store-link-props :type "image" :file buffer-file-name))
6777 ((eq major-mode 'dired-mode)
6778 ;; link to the file in the current line
6779 (setq cpltxt (concat "file:"
6780 (abbreviate-file-name
6781 (expand-file-name
6782 (dired-get-filename nil t))))
6783 link (org-make-link cpltxt)))
6785 ((and buffer-file-name (org-mode-p))
6786 ;; Just link to current headline
6787 (setq cpltxt (concat "file:"
6788 (abbreviate-file-name buffer-file-name)))
6789 ;; Add a context search string
6790 (when (org-xor org-context-in-file-links arg)
6791 ;; Check if we are on a target
6792 (if (org-in-regexp "<<\\(.*?\\)>>")
6793 (setq cpltxt (concat cpltxt "::" (match-string 1)))
6794 (setq txt (cond
6795 ((org-on-heading-p) nil)
6796 ((org-region-active-p)
6797 (buffer-substring (region-beginning) (region-end)))
6798 (t (buffer-substring (point-at-bol) (point-at-eol)))))
6799 (when (or (null txt) (string-match "\\S-" txt))
6800 (setq cpltxt
6801 (concat cpltxt "::" (org-make-org-heading-search-string txt))
6802 desc "NONE"))))
6803 (if (string-match "::\\'" cpltxt)
6804 (setq cpltxt (substring cpltxt 0 -2)))
6805 (setq link (org-make-link cpltxt)))
6807 ((buffer-file-name (buffer-base-buffer))
6808 ;; Just link to this file here.
6809 (setq cpltxt (concat "file:"
6810 (abbreviate-file-name
6811 (buffer-file-name (buffer-base-buffer)))))
6812 ;; Add a context string
6813 (when (org-xor org-context-in-file-links arg)
6814 (setq txt (if (org-region-active-p)
6815 (buffer-substring (region-beginning) (region-end))
6816 (buffer-substring (point-at-bol) (point-at-eol))))
6817 ;; Only use search option if there is some text.
6818 (when (string-match "\\S-" txt)
6819 (setq cpltxt
6820 (concat cpltxt "::" (org-make-org-heading-search-string txt))
6821 desc "NONE")))
6822 (setq link (org-make-link cpltxt)))
6824 ((interactive-p)
6825 (error "Cannot link to a buffer which is not visiting a file"))
6827 (t (setq link nil)))
6829 (if (consp link) (setq cpltxt (car link) link (cdr link)))
6830 (setq link (or link cpltxt)
6831 desc (or desc cpltxt))
6832 (if (equal desc "NONE") (setq desc nil))
6834 (if (and (interactive-p) link)
6835 (progn
6836 (setq org-stored-links
6837 (cons (list link desc) org-stored-links))
6838 (message "Stored: %s" (or desc link)))
6839 (and link (org-make-link-string link desc)))))
6841 (defun org-store-link-props (&rest plist)
6842 "Store link properties, extract names and addresses."
6843 (let (x adr)
6844 (when (setq x (plist-get plist :from))
6845 (setq adr (mail-extract-address-components x))
6846 (plist-put plist :fromname (car adr))
6847 (plist-put plist :fromaddress (nth 1 adr)))
6848 (when (setq x (plist-get plist :to))
6849 (setq adr (mail-extract-address-components x))
6850 (plist-put plist :toname (car adr))
6851 (plist-put plist :toaddress (nth 1 adr))))
6852 (let ((from (plist-get plist :from))
6853 (to (plist-get plist :to)))
6854 (when (and from to org-from-is-user-regexp)
6855 (plist-put plist :fromto
6856 (if (string-match org-from-is-user-regexp from)
6857 (concat "to %t")
6858 (concat "from %f")))))
6859 (setq org-store-link-plist plist))
6861 (defun org-add-link-props (&rest plist)
6862 "Add these properties to the link property list."
6863 (let (key value)
6864 (while plist
6865 (setq key (pop plist) value (pop plist))
6866 (setq org-store-link-plist
6867 (plist-put org-store-link-plist key value)))))
6869 (defun org-email-link-description (&optional fmt)
6870 "Return the description part of an email link.
6871 This takes information from `org-store-link-plist' and formats it
6872 according to FMT (default from `org-email-link-description-format')."
6873 (setq fmt (or fmt org-email-link-description-format))
6874 (let* ((p org-store-link-plist)
6875 (to (plist-get p :toaddress))
6876 (from (plist-get p :fromaddress))
6877 (table
6878 (list
6879 (cons "%c" (plist-get p :fromto))
6880 (cons "%F" (plist-get p :from))
6881 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
6882 (cons "%T" (plist-get p :to))
6883 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
6884 (cons "%s" (plist-get p :subject))
6885 (cons "%m" (plist-get p :message-id)))))
6886 (when (string-match "%c" fmt)
6887 ;; Check if the user wrote this message
6888 (if (and org-from-is-user-regexp from to
6889 (save-match-data (string-match org-from-is-user-regexp from)))
6890 (setq fmt (replace-match "to %t" t t fmt))
6891 (setq fmt (replace-match "from %f" t t fmt))))
6892 (org-replace-escapes fmt table)))
6894 (defun org-make-org-heading-search-string (&optional string heading)
6895 "Make search string for STRING or current headline."
6896 (interactive)
6897 (let ((s (or string (org-get-heading))))
6898 (unless (and string (not heading))
6899 ;; We are using a headline, clean up garbage in there.
6900 (if (string-match org-todo-regexp s)
6901 (setq s (replace-match "" t t s)))
6902 (if (string-match (org-re ":[[:alnum:]_@:]+:[ \t]*$") s)
6903 (setq s (replace-match "" t t s)))
6904 (setq s (org-trim s))
6905 (if (string-match (concat "^\\(" org-quote-string "\\|"
6906 org-comment-string "\\)") s)
6907 (setq s (replace-match "" t t s)))
6908 (while (string-match org-ts-regexp s)
6909 (setq s (replace-match "" t t s))))
6910 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
6911 (setq s (replace-match " " t t s)))
6912 (or string (setq s (concat "*" s))) ; Add * for headlines
6913 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
6915 (defun org-make-link (&rest strings)
6916 "Concatenate STRINGS."
6917 (apply 'concat strings))
6919 (defun org-make-link-string (link &optional description)
6920 "Make a link with brackets, consisting of LINK and DESCRIPTION."
6921 (unless (string-match "\\S-" link)
6922 (error "Empty link"))
6923 (when (stringp description)
6924 ;; Remove brackets from the description, they are fatal.
6925 (while (string-match "\\[" description)
6926 (setq description (replace-match "{" t t description)))
6927 (while (string-match "\\]" description)
6928 (setq description (replace-match "}" t t description))))
6929 (when (equal (org-link-escape link) description)
6930 ;; No description needed, it is identical
6931 (setq description nil))
6932 (when (and (not description)
6933 (not (equal link (org-link-escape link))))
6934 (setq description link))
6935 (concat "[[" (org-link-escape link) "]"
6936 (if description (concat "[" description "]") "")
6937 "]"))
6939 (defconst org-link-escape-chars
6940 '((?\ . "%20")
6941 (?\[ . "%5B")
6942 (?\] . "%5D")
6943 (?\340 . "%E0") ; `a
6944 (?\342 . "%E2") ; ^a
6945 (?\347 . "%E7") ; ,c
6946 (?\350 . "%E8") ; `e
6947 (?\351 . "%E9") ; 'e
6948 (?\352 . "%EA") ; ^e
6949 (?\356 . "%EE") ; ^i
6950 (?\364 . "%F4") ; ^o
6951 (?\371 . "%F9") ; `u
6952 (?\373 . "%FB") ; ^u
6953 (?\; . "%3B")
6954 (?? . "%3F")
6955 (?= . "%3D")
6956 (?+ . "%2B")
6958 "Association list of escapes for some characters problematic in links.
6959 This is the list that is used for internal purposes.")
6961 (defconst org-link-escape-chars-browser
6962 '((?\ . "%20")) ; 32 for the SPC char
6963 "Association list of escapes for some characters problematic in links.
6964 This is the list that is used before handing over to the browser.")
6966 (defun org-link-escape (text &optional table)
6967 "Escape charaters in TEXT that are problematic for links."
6968 (setq table (or table org-link-escape-chars))
6969 (when text
6970 (let ((re (mapconcat (lambda (x) (regexp-quote
6971 (char-to-string (car x))))
6972 table "\\|")))
6973 (while (string-match re text)
6974 (setq text
6975 (replace-match
6976 (cdr (assoc (string-to-char (match-string 0 text))
6977 table))
6978 t t text)))
6979 text)))
6981 (defun org-link-unescape (text &optional table)
6982 "Reverse the action of `org-link-escape'."
6983 (setq table (or table org-link-escape-chars))
6984 (when text
6985 (let ((re (mapconcat (lambda (x) (regexp-quote (cdr x)))
6986 table "\\|")))
6987 (while (string-match re text)
6988 (setq text
6989 (replace-match
6990 (char-to-string (car (rassoc (match-string 0 text) table)))
6991 t t text)))
6992 text)))
6994 (defun org-xor (a b)
6995 "Exclusive or."
6996 (if a (not b) b))
6998 (defun org-get-header (header)
6999 "Find a header field in the current buffer."
7000 (save-excursion
7001 (goto-char (point-min))
7002 (let ((case-fold-search t) s)
7003 (cond
7004 ((eq header 'from)
7005 (if (re-search-forward "^From:\\s-+\\(.*\\)" nil t)
7006 (setq s (match-string 1)))
7007 (while (string-match "\"" s)
7008 (setq s (replace-match "" t t s)))
7009 (if (string-match "[<(].*" s)
7010 (setq s (replace-match "" t t s))))
7011 ((eq header 'message-id)
7012 (if (re-search-forward "^message-id:\\s-+\\(.*\\)" nil t)
7013 (setq s (match-string 1))))
7014 ((eq header 'subject)
7015 (if (re-search-forward "^subject:\\s-+\\(.*\\)" nil t)
7016 (setq s (match-string 1)))))
7017 (if (string-match "\\`[ \t\]+" s) (setq s (replace-match "" t t s)))
7018 (if (string-match "[ \t\]+\\'" s) (setq s (replace-match "" t t s)))
7019 s)))
7022 (defun org-fixup-message-id-for-http (s)
7023 "Replace special characters in a message id, so it can be used in an http query."
7024 (while (string-match "<" s)
7025 (setq s (replace-match "%3C" t t s)))
7026 (while (string-match ">" s)
7027 (setq s (replace-match "%3E" t t s)))
7028 (while (string-match "@" s)
7029 (setq s (replace-match "%40" t t s)))
7032 ;;;###autoload
7033 (defun org-insert-link-global ()
7034 "Insert a link like Org-mode does.
7035 This command can be called in any mode to insert a link in Org-mode syntax."
7036 (interactive)
7037 (org-load-modules-maybe)
7038 (org-run-like-in-org-mode 'org-insert-link))
7040 (defun org-insert-link (&optional complete-file)
7041 "Insert a link. At the prompt, enter the link.
7043 Completion can be used to select a link previously stored with
7044 `org-store-link'. When the empty string is entered (i.e. if you just
7045 press RET at the prompt), the link defaults to the most recently
7046 stored link. As SPC triggers completion in the minibuffer, you need to
7047 use M-SPC or C-q SPC to force the insertion of a space character.
7049 You will also be prompted for a description, and if one is given, it will
7050 be displayed in the buffer instead of the link.
7052 If there is already a link at point, this command will allow you to edit link
7053 and description parts.
7055 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can be
7056 selected using completion. The path to the file will be relative to
7057 the current directory if the file is in the current directory or a
7058 subdirectory. Otherwise, the link will be the absolute path as
7059 completed in the minibuffer (i.e. normally ~/path/to/file).
7061 With two \\[universal-argument] prefixes, enforce an absolute path even if the file
7062 is in the current directory or below.
7063 With three \\[universal-argument] prefixes, negate the meaning of
7064 `org-keep-stored-link-after-insertion'."
7065 (interactive "P")
7066 (let* ((wcf (current-window-configuration))
7067 (region (if (org-region-active-p)
7068 (buffer-substring (region-beginning) (region-end))))
7069 (remove (and region (list (region-beginning) (region-end))))
7070 (desc region)
7071 tmphist ; byte-compile incorrectly complains about this
7072 link entry file)
7073 (cond
7074 ((org-in-regexp org-bracket-link-regexp 1)
7075 ;; We do have a link at point, and we are going to edit it.
7076 (setq remove (list (match-beginning 0) (match-end 0)))
7077 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
7078 (setq link (read-string "Link: "
7079 (org-link-unescape
7080 (org-match-string-no-properties 1)))))
7081 ((or (org-in-regexp org-angle-link-re)
7082 (org-in-regexp org-plain-link-re))
7083 ;; Convert to bracket link
7084 (setq remove (list (match-beginning 0) (match-end 0))
7085 link (read-string "Link: "
7086 (org-remove-angle-brackets (match-string 0)))))
7087 ((equal complete-file '(4))
7088 ;; Completing read for file names.
7089 (setq file (read-file-name "File: "))
7090 (let ((pwd (file-name-as-directory (expand-file-name ".")))
7091 (pwd1 (file-name-as-directory (abbreviate-file-name
7092 (expand-file-name ".")))))
7093 (cond
7094 ((equal complete-file '(16))
7095 (setq link (org-make-link
7096 "file:"
7097 (abbreviate-file-name (expand-file-name file)))))
7098 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
7099 (setq link (org-make-link "file:" (match-string 1 file))))
7100 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
7101 (expand-file-name file))
7102 (setq link (org-make-link
7103 "file:" (match-string 1 (expand-file-name file)))))
7104 (t (setq link (org-make-link "file:" file))))))
7106 ;; Read link, with completion for stored links.
7107 (with-output-to-temp-buffer "*Org Links*"
7108 (princ "Insert a link. Use TAB to complete valid link prefixes.\n")
7109 (when org-stored-links
7110 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
7111 (princ (mapconcat
7112 (lambda (x)
7113 (if (nth 1 x) (concat (car x) " (" (nth 1 x) ")") (car x)))
7114 (reverse org-stored-links) "\n"))))
7115 (let ((cw (selected-window)))
7116 (select-window (get-buffer-window "*Org Links*"))
7117 (shrink-window-if-larger-than-buffer)
7118 (setq truncate-lines t)
7119 (select-window cw))
7120 ;; Fake a link history, containing the stored links.
7121 (setq tmphist (append (mapcar 'car org-stored-links)
7122 org-insert-link-history))
7123 (unwind-protect
7124 (setq link (org-completing-read
7125 "Link: "
7126 (append
7127 (mapcar (lambda (x) (list (concat (car x) ":")))
7128 (append org-link-abbrev-alist-local org-link-abbrev-alist))
7129 (mapcar (lambda (x) (list (concat x ":")))
7130 org-link-types))
7131 nil nil nil
7132 'tmphist
7133 (or (car (car org-stored-links)))))
7134 (set-window-configuration wcf)
7135 (kill-buffer "*Org Links*"))
7136 (setq entry (assoc link org-stored-links))
7137 (or entry (push link org-insert-link-history))
7138 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
7139 (not org-keep-stored-link-after-insertion))
7140 (setq org-stored-links (delq (assoc link org-stored-links)
7141 org-stored-links)))
7142 (setq desc (or desc (nth 1 entry)))))
7144 (if (string-match org-plain-link-re link)
7145 ;; URL-like link, normalize the use of angular brackets.
7146 (setq link (org-make-link (org-remove-angle-brackets link))))
7148 ;; Check if we are linking to the current file with a search option
7149 ;; If yes, simplify the link by using only the search option.
7150 (when (and buffer-file-name
7151 (string-match "\\<file:\\(.+?\\)::\\([^>]+\\)" link))
7152 (let* ((path (match-string 1 link))
7153 (case-fold-search nil)
7154 (search (match-string 2 link)))
7155 (save-match-data
7156 (if (equal (file-truename buffer-file-name) (file-truename path))
7157 ;; We are linking to this same file, with a search option
7158 (setq link search)))))
7160 ;; Check if we can/should use a relative path. If yes, simplify the link
7161 (when (string-match "\\<file:\\(.*\\)" link)
7162 (let* ((path (match-string 1 link))
7163 (origpath path)
7164 (case-fold-search nil))
7165 (cond
7166 ((eq org-link-file-path-type 'absolute)
7167 (setq path (abbreviate-file-name (expand-file-name path))))
7168 ((eq org-link-file-path-type 'noabbrev)
7169 (setq path (expand-file-name path)))
7170 ((eq org-link-file-path-type 'relative)
7171 (setq path (file-relative-name path)))
7173 (save-match-data
7174 (if (string-match (concat "^" (regexp-quote
7175 (file-name-as-directory
7176 (expand-file-name "."))))
7177 (expand-file-name path))
7178 ;; We are linking a file with relative path name.
7179 (setq path (substring (expand-file-name path)
7180 (match-end 0)))))))
7181 (setq link (concat "file:" path))
7182 (if (equal desc origpath)
7183 (setq desc path))))
7185 (setq desc (read-string "Description: " desc))
7186 (unless (string-match "\\S-" desc) (setq desc nil))
7187 (if remove (apply 'delete-region remove))
7188 (insert (org-make-link-string link desc))))
7190 (defun org-completing-read (&rest args)
7191 (let ((minibuffer-local-completion-map
7192 (copy-keymap minibuffer-local-completion-map)))
7193 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
7194 (apply 'completing-read args)))
7196 ;;; Opening/following a link
7197 (defvar org-link-search-failed nil)
7199 (defun org-next-link ()
7200 "Move forward to the next link.
7201 If the link is in hidden text, expose it."
7202 (interactive)
7203 (when (and org-link-search-failed (eq this-command last-command))
7204 (goto-char (point-min))
7205 (message "Link search wrapped back to beginning of buffer"))
7206 (setq org-link-search-failed nil)
7207 (let* ((pos (point))
7208 (ct (org-context))
7209 (a (assoc :link ct)))
7210 (if a (goto-char (nth 2 a)))
7211 (if (re-search-forward org-any-link-re nil t)
7212 (progn
7213 (goto-char (match-beginning 0))
7214 (if (org-invisible-p) (org-show-context)))
7215 (goto-char pos)
7216 (setq org-link-search-failed t)
7217 (error "No further link found"))))
7219 (defun org-previous-link ()
7220 "Move backward to the previous link.
7221 If the link is in hidden text, expose it."
7222 (interactive)
7223 (when (and org-link-search-failed (eq this-command last-command))
7224 (goto-char (point-max))
7225 (message "Link search wrapped back to end of buffer"))
7226 (setq org-link-search-failed nil)
7227 (let* ((pos (point))
7228 (ct (org-context))
7229 (a (assoc :link ct)))
7230 (if a (goto-char (nth 1 a)))
7231 (if (re-search-backward org-any-link-re nil t)
7232 (progn
7233 (goto-char (match-beginning 0))
7234 (if (org-invisible-p) (org-show-context)))
7235 (goto-char pos)
7236 (setq org-link-search-failed t)
7237 (error "No further link found"))))
7239 (defun org-find-file-at-mouse (ev)
7240 "Open file link or URL at mouse."
7241 (interactive "e")
7242 (mouse-set-point ev)
7243 (org-open-at-point 'in-emacs))
7245 (defun org-open-at-mouse (ev)
7246 "Open file link or URL at mouse."
7247 (interactive "e")
7248 (mouse-set-point ev)
7249 (org-open-at-point))
7251 (defvar org-window-config-before-follow-link nil
7252 "The window configuration before following a link.
7253 This is saved in case the need arises to restore it.")
7255 (defvar org-open-link-marker (make-marker)
7256 "Marker pointing to the location where `org-open-at-point; was called.")
7258 ;;;###autoload
7259 (defun org-open-at-point-global ()
7260 "Follow a link like Org-mode does.
7261 This command can be called in any mode to follow a link that has
7262 Org-mode syntax."
7263 (interactive)
7264 (org-run-like-in-org-mode 'org-open-at-point))
7266 (defun org-open-at-point (&optional in-emacs)
7267 "Open link at or after point.
7268 If there is no link at point, this function will search forward up to
7269 the end of the current subtree.
7270 Normally, files will be opened by an appropriate application. If the
7271 optional argument IN-EMACS is non-nil, Emacs will visit the file."
7272 (interactive "P")
7273 (org-load-modules-maybe)
7274 (move-marker org-open-link-marker (point))
7275 (setq org-window-config-before-follow-link (current-window-configuration))
7276 (org-remove-occur-highlights nil nil t)
7277 (if (org-at-timestamp-p t)
7278 (org-follow-timestamp-link)
7279 (let (type path link line search (pos (point)))
7280 (catch 'match
7281 (save-excursion
7282 (skip-chars-forward "^]\n\r")
7283 (when (org-in-regexp org-bracket-link-regexp)
7284 (setq link (org-link-unescape (org-match-string-no-properties 1)))
7285 (while (string-match " *\n *" link)
7286 (setq link (replace-match " " t t link)))
7287 (setq link (org-link-expand-abbrev link))
7288 (if (string-match org-link-re-with-space2 link)
7289 (setq type (match-string 1 link) path (match-string 2 link))
7290 (setq type "thisfile" path link))
7291 (throw 'match t)))
7293 (when (get-text-property (point) 'org-linked-text)
7294 (setq type "thisfile"
7295 pos (if (get-text-property (1+ (point)) 'org-linked-text)
7296 (1+ (point)) (point))
7297 path (buffer-substring
7298 (previous-single-property-change pos 'org-linked-text)
7299 (next-single-property-change pos 'org-linked-text)))
7300 (throw 'match t))
7302 (save-excursion
7303 (when (or (org-in-regexp org-angle-link-re)
7304 (org-in-regexp org-plain-link-re))
7305 (setq type (match-string 1) path (match-string 2))
7306 (throw 'match t)))
7307 (when (org-in-regexp "\\<\\([^><\n]+\\)\\>")
7308 (setq type "tree-match"
7309 path (match-string 1))
7310 (throw 'match t))
7311 (save-excursion
7312 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@:]+\\):[ \t]*$"))
7313 (setq type "tags"
7314 path (match-string 1))
7315 (while (string-match ":" path)
7316 (setq path (replace-match "+" t t path)))
7317 (throw 'match t))))
7318 (unless path
7319 (error "No link found"))
7320 ;; Remove any trailing spaces in path
7321 (if (string-match " +\\'" path)
7322 (setq path (replace-match "" t t path)))
7324 (cond
7326 ((assoc type org-link-protocols)
7327 (funcall (nth 1 (assoc type org-link-protocols)) path))
7329 ((equal type "mailto")
7330 (let ((cmd (car org-link-mailto-program))
7331 (args (cdr org-link-mailto-program)) args1
7332 (address path) (subject "") a)
7333 (if (string-match "\\(.*\\)::\\(.*\\)" path)
7334 (setq address (match-string 1 path)
7335 subject (org-link-escape (match-string 2 path))))
7336 (while args
7337 (cond
7338 ((not (stringp (car args))) (push (pop args) args1))
7339 (t (setq a (pop args))
7340 (if (string-match "%a" a)
7341 (setq a (replace-match address t t a)))
7342 (if (string-match "%s" a)
7343 (setq a (replace-match subject t t a)))
7344 (push a args1))))
7345 (apply cmd (nreverse args1))))
7347 ((member type '("http" "https" "ftp" "news"))
7348 (browse-url (concat type ":" (org-link-escape
7349 path org-link-escape-chars-browser))))
7351 ((member type '("message"))
7352 (browse-url (concat type ":" path)))
7354 ((string= type "tags")
7355 (org-tags-view in-emacs path))
7356 ((string= type "thisfile")
7357 (if in-emacs
7358 (switch-to-buffer-other-window
7359 (org-get-buffer-for-internal-link (current-buffer)))
7360 (org-mark-ring-push))
7361 (let ((cmd `(org-link-search
7362 ,path
7363 ,(cond ((equal in-emacs '(4)) 'occur)
7364 ((equal in-emacs '(16)) 'org-occur)
7365 (t nil))
7366 ,pos)))
7367 (condition-case nil (eval cmd)
7368 (error (progn (widen) (eval cmd))))))
7370 ((string= type "tree-match")
7371 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
7373 ((string= type "file")
7374 (if (string-match "::\\([0-9]+\\)\\'" path)
7375 (setq line (string-to-number (match-string 1 path))
7376 path (substring path 0 (match-beginning 0)))
7377 (if (string-match "::\\(.+\\)\\'" path)
7378 (setq search (match-string 1 path)
7379 path (substring path 0 (match-beginning 0)))))
7380 (if (string-match "[*?{]" (file-name-nondirectory path))
7381 (dired path)
7382 (org-open-file path in-emacs line search)))
7384 ((string= type "news")
7385 (require 'org-gnus)
7386 (org-gnus-follow-link path))
7388 ((string= type "shell")
7389 (let ((cmd path))
7390 (if (or (not org-confirm-shell-link-function)
7391 (funcall org-confirm-shell-link-function
7392 (format "Execute \"%s\" in shell? "
7393 (org-add-props cmd nil
7394 'face 'org-warning))))
7395 (progn
7396 (message "Executing %s" cmd)
7397 (shell-command cmd))
7398 (error "Abort"))))
7400 ((string= type "elisp")
7401 (let ((cmd path))
7402 (if (or (not org-confirm-elisp-link-function)
7403 (funcall org-confirm-elisp-link-function
7404 (format "Execute \"%s\" as elisp? "
7405 (org-add-props cmd nil
7406 'face 'org-warning))))
7407 (message "%s => %s" cmd (eval (read cmd)))
7408 (error "Abort"))))
7411 (browse-url-at-point)))))
7412 (move-marker org-open-link-marker nil)
7413 (run-hook-with-args 'org-follow-link-hook))
7415 ;;; File search
7417 (defvar org-create-file-search-functions nil
7418 "List of functions to construct the right search string for a file link.
7419 These functions are called in turn with point at the location to
7420 which the link should point.
7422 A function in the hook should first test if it would like to
7423 handle this file type, for example by checking the major-mode or
7424 the file extension. If it decides not to handle this file, it
7425 should just return nil to give other functions a chance. If it
7426 does handle the file, it must return the search string to be used
7427 when following the link. The search string will be part of the
7428 file link, given after a double colon, and `org-open-at-point'
7429 will automatically search for it. If special measures must be
7430 taken to make the search successful, another function should be
7431 added to the companion hook `org-execute-file-search-functions',
7432 which see.
7434 A function in this hook may also use `setq' to set the variable
7435 `description' to provide a suggestion for the descriptive text to
7436 be used for this link when it gets inserted into an Org-mode
7437 buffer with \\[org-insert-link].")
7439 (defvar org-execute-file-search-functions nil
7440 "List of functions to execute a file search triggered by a link.
7442 Functions added to this hook must accept a single argument, the
7443 search string that was part of the file link, the part after the
7444 double colon. The function must first check if it would like to
7445 handle this search, for example by checking the major-mode or the
7446 file extension. If it decides not to handle this search, it
7447 should just return nil to give other functions a chance. If it
7448 does handle the search, it must return a non-nil value to keep
7449 other functions from trying.
7451 Each function can access the current prefix argument through the
7452 variable `current-prefix-argument'. Note that a single prefix is
7453 used to force opening a link in Emacs, so it may be good to only
7454 use a numeric or double prefix to guide the search function.
7456 In case this is needed, a function in this hook can also restore
7457 the window configuration before `org-open-at-point' was called using:
7459 (set-window-configuration org-window-config-before-follow-link)")
7461 (defun org-link-search (s &optional type avoid-pos)
7462 "Search for a link search option.
7463 If S is surrounded by forward slashes, it is interpreted as a
7464 regular expression. In org-mode files, this will create an `org-occur'
7465 sparse tree. In ordinary files, `occur' will be used to list matches.
7466 If the current buffer is in `dired-mode', grep will be used to search
7467 in all files. If AVOID-POS is given, ignore matches near that position."
7468 (let ((case-fold-search t)
7469 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
7470 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
7471 (append '(("") (" ") ("\t") ("\n"))
7472 org-emphasis-alist)
7473 "\\|") "\\)"))
7474 (pos (point))
7475 (pre "") (post "")
7476 words re0 re1 re2 re3 re4 re5 re2a reall)
7477 (cond
7478 ;; First check if there are any special
7479 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
7480 ;; Now try the builtin stuff
7481 ((save-excursion
7482 (goto-char (point-min))
7483 (and
7484 (re-search-forward
7485 (concat "<<" (regexp-quote s0) ">>") nil t)
7486 (setq pos (match-beginning 0))))
7487 ;; There is an exact target for this
7488 (goto-char pos))
7489 ((string-match "^/\\(.*\\)/$" s)
7490 ;; A regular expression
7491 (cond
7492 ((org-mode-p)
7493 (org-occur (match-string 1 s)))
7494 ;;((eq major-mode 'dired-mode)
7495 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
7496 (t (org-do-occur (match-string 1 s)))))
7498 ;; A normal search strings
7499 (when (equal (string-to-char s) ?*)
7500 ;; Anchor on headlines, post may include tags.
7501 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
7502 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@:+]:[ \t]*\\)?$")
7503 s (substring s 1)))
7504 (remove-text-properties
7505 0 (length s)
7506 '(face nil mouse-face nil keymap nil fontified nil) s)
7507 ;; Make a series of regular expressions to find a match
7508 (setq words (org-split-string s "[ \n\r\t]+")
7509 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
7510 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
7511 "\\)" markers)
7512 re2a (concat "[ \t\r\n]\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
7513 re4 (concat "[^a-zA-Z_]\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
7514 re1 (concat pre re2 post)
7515 re3 (concat pre re4 post)
7516 re5 (concat pre ".*" re4)
7517 re2 (concat pre re2)
7518 re2a (concat pre re2a)
7519 re4 (concat pre re4)
7520 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
7521 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
7522 re5 "\\)"
7524 (cond
7525 ((eq type 'org-occur) (org-occur reall))
7526 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
7527 (t (goto-char (point-min))
7528 (if (or (org-search-not-self 1 re0 nil t)
7529 (org-search-not-self 1 re1 nil t)
7530 (org-search-not-self 1 re2 nil t)
7531 (org-search-not-self 1 re2a nil t)
7532 (org-search-not-self 1 re3 nil t)
7533 (org-search-not-self 1 re4 nil t)
7534 (org-search-not-self 1 re5 nil t)
7536 (goto-char (match-beginning 1))
7537 (goto-char pos)
7538 (error "No match")))))
7540 ;; Normal string-search
7541 (goto-char (point-min))
7542 (if (search-forward s nil t)
7543 (goto-char (match-beginning 0))
7544 (error "No match"))))
7545 (and (org-mode-p) (org-show-context 'link-search))))
7547 (defun org-search-not-self (group &rest args)
7548 "Execute `re-search-forward', but only accept matches that do not
7549 enclose the position of `org-open-link-marker'."
7550 (let ((m org-open-link-marker))
7551 (catch 'exit
7552 (while (apply 're-search-forward args)
7553 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
7554 (goto-char (match-end group))
7555 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
7556 (> (match-beginning 0) (marker-position m))
7557 (< (match-end 0) (marker-position m)))
7558 (save-match-data
7559 (or (not (org-in-regexp
7560 org-bracket-link-analytic-regexp 1))
7561 (not (match-end 4)) ; no description
7562 (and (<= (match-beginning 4) (point))
7563 (>= (match-end 4) (point))))))
7564 (throw 'exit (point))))))))
7566 (defun org-get-buffer-for-internal-link (buffer)
7567 "Return a buffer to be used for displaying the link target of internal links."
7568 (cond
7569 ((not org-display-internal-link-with-indirect-buffer)
7570 buffer)
7571 ((string-match "(Clone)$" (buffer-name buffer))
7572 (message "Buffer is already a clone, not making another one")
7573 ;; we also do not modify visibility in this case
7574 buffer)
7575 (t ; make a new indirect buffer for displaying the link
7576 (let* ((bn (buffer-name buffer))
7577 (ibn (concat bn "(Clone)"))
7578 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
7579 (with-current-buffer ib (org-overview))
7580 ib))))
7582 (defun org-do-occur (regexp &optional cleanup)
7583 "Call the Emacs command `occur'.
7584 If CLEANUP is non-nil, remove the printout of the regular expression
7585 in the *Occur* buffer. This is useful if the regex is long and not useful
7586 to read."
7587 (occur regexp)
7588 (when cleanup
7589 (let ((cwin (selected-window)) win beg end)
7590 (when (setq win (get-buffer-window "*Occur*"))
7591 (select-window win))
7592 (goto-char (point-min))
7593 (when (re-search-forward "match[a-z]+" nil t)
7594 (setq beg (match-end 0))
7595 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
7596 (setq end (1- (match-beginning 0)))))
7597 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
7598 (goto-char (point-min))
7599 (select-window cwin))))
7601 ;;; The mark ring for links jumps
7603 (defvar org-mark-ring nil
7604 "Mark ring for positions before jumps in Org-mode.")
7605 (defvar org-mark-ring-last-goto nil
7606 "Last position in the mark ring used to go back.")
7607 ;; Fill and close the ring
7608 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
7609 (loop for i from 1 to org-mark-ring-length do
7610 (push (make-marker) org-mark-ring))
7611 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
7612 org-mark-ring)
7614 (defun org-mark-ring-push (&optional pos buffer)
7615 "Put the current position or POS into the mark ring and rotate it."
7616 (interactive)
7617 (setq pos (or pos (point)))
7618 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
7619 (move-marker (car org-mark-ring)
7620 (or pos (point))
7621 (or buffer (current-buffer)))
7622 (message "%s"
7623 (substitute-command-keys
7624 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
7626 (defun org-mark-ring-goto (&optional n)
7627 "Jump to the previous position in the mark ring.
7628 With prefix arg N, jump back that many stored positions. When
7629 called several times in succession, walk through the entire ring.
7630 Org-mode commands jumping to a different position in the current file,
7631 or to another Org-mode file, automatically push the old position
7632 onto the ring."
7633 (interactive "p")
7634 (let (p m)
7635 (if (eq last-command this-command)
7636 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
7637 (setq p org-mark-ring))
7638 (setq org-mark-ring-last-goto p)
7639 (setq m (car p))
7640 (switch-to-buffer (marker-buffer m))
7641 (goto-char m)
7642 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
7644 (defun org-remove-angle-brackets (s)
7645 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
7646 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
7648 (defun org-add-angle-brackets (s)
7649 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
7650 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
7653 ;;; Following specific links
7655 (defun org-follow-timestamp-link ()
7656 (cond
7657 ((org-at-date-range-p t)
7658 (let ((org-agenda-start-on-weekday)
7659 (t1 (match-string 1))
7660 (t2 (match-string 2)))
7661 (setq t1 (time-to-days (org-time-string-to-time t1))
7662 t2 (time-to-days (org-time-string-to-time t2)))
7663 (org-agenda-list nil t1 (1+ (- t2 t1)))))
7664 ((org-at-timestamp-p t)
7665 (org-agenda-list nil (time-to-days (org-time-string-to-time
7666 (substring (match-string 1) 0 10)))
7668 (t (error "This should not happen"))))
7671 ;;; BibTeX links
7673 ;; Use the custom search meachnism to construct and use search strings for
7674 ;; file links to BibTeX database entries.
7676 (defun org-create-file-search-in-bibtex ()
7677 "Create the search string and description for a BibTeX database entry."
7678 (when (eq major-mode 'bibtex-mode)
7679 ;; yes, we want to construct this search string.
7680 ;; Make a good description for this entry, using names, year and the title
7681 ;; Put it into the `description' variable which is dynamically scoped.
7682 (let ((bibtex-autokey-names 1)
7683 (bibtex-autokey-names-stretch 1)
7684 (bibtex-autokey-name-case-convert-function 'identity)
7685 (bibtex-autokey-name-separator " & ")
7686 (bibtex-autokey-additional-names " et al.")
7687 (bibtex-autokey-year-length 4)
7688 (bibtex-autokey-name-year-separator " ")
7689 (bibtex-autokey-titlewords 3)
7690 (bibtex-autokey-titleword-separator " ")
7691 (bibtex-autokey-titleword-case-convert-function 'identity)
7692 (bibtex-autokey-titleword-length 'infty)
7693 (bibtex-autokey-year-title-separator ": "))
7694 (setq description (bibtex-generate-autokey)))
7695 ;; Now parse the entry, get the key and return it.
7696 (save-excursion
7697 (bibtex-beginning-of-entry)
7698 (cdr (assoc "=key=" (bibtex-parse-entry))))))
7700 (defun org-execute-file-search-in-bibtex (s)
7701 "Find the link search string S as a key for a database entry."
7702 (when (eq major-mode 'bibtex-mode)
7703 ;; Yes, we want to do the search in this file.
7704 ;; We construct a regexp that searches for "@entrytype{" followed by the key
7705 (goto-char (point-min))
7706 (and (re-search-forward (concat "@[a-zA-Z]+[ \t\n]*{[ \t\n]*"
7707 (regexp-quote s) "[ \t\n]*,") nil t)
7708 (goto-char (match-beginning 0)))
7709 (if (and (match-beginning 0) (equal current-prefix-arg '(16)))
7710 ;; Use double prefix to indicate that any web link should be browsed
7711 (let ((b (current-buffer)) (p (point)))
7712 ;; Restore the window configuration because we just use the web link
7713 (set-window-configuration org-window-config-before-follow-link)
7714 (save-excursion (set-buffer b) (goto-char p)
7715 (bibtex-url)))
7716 (recenter 0)) ; Move entry start to beginning of window
7717 ;; return t to indicate that the search is done.
7720 ;; Finally add the functions to the right hooks.
7721 (add-hook 'org-create-file-search-functions 'org-create-file-search-in-bibtex)
7722 (add-hook 'org-execute-file-search-functions 'org-execute-file-search-in-bibtex)
7724 ;; end of Bibtex link setup
7726 ;;; Following file links
7728 (defun org-open-file (path &optional in-emacs line search)
7729 "Open the file at PATH.
7730 First, this expands any special file name abbreviations. Then the
7731 configuration variable `org-file-apps' is checked if it contains an
7732 entry for this file type, and if yes, the corresponding command is launched.
7733 If no application is found, Emacs simply visits the file.
7734 With optional argument IN-EMACS, Emacs will visit the file.
7735 Optional LINE specifies a line to go to, optional SEARCH a string to
7736 search for. If LINE or SEARCH is given, the file will always be
7737 opened in Emacs.
7738 If the file does not exist, an error is thrown."
7739 (setq in-emacs (or in-emacs line search))
7740 (let* ((file (if (equal path "")
7741 buffer-file-name
7742 (substitute-in-file-name (expand-file-name path))))
7743 (apps (append org-file-apps (org-default-apps)))
7744 (remp (and (assq 'remote apps) (org-file-remote-p file)))
7745 (dirp (if remp nil (file-directory-p file)))
7746 (dfile (downcase file))
7747 (old-buffer (current-buffer))
7748 (old-pos (point))
7749 (old-mode major-mode)
7750 ext cmd)
7751 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
7752 (setq ext (match-string 1 dfile))
7753 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
7754 (setq ext (match-string 1 dfile))))
7755 (if in-emacs
7756 (setq cmd 'emacs)
7757 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
7758 (and dirp (cdr (assoc 'directory apps)))
7759 (cdr (assoc ext apps))
7760 (cdr (assoc t apps)))))
7761 (when (eq cmd 'mailcap)
7762 (require 'mailcap)
7763 (mailcap-parse-mailcaps)
7764 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
7765 (command (mailcap-mime-info mime-type)))
7766 (if (stringp command)
7767 (setq cmd command)
7768 (setq cmd 'emacs))))
7769 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
7770 (not (file-exists-p file))
7771 (not org-open-non-existing-files))
7772 (error "No such file: %s" file))
7773 (cond
7774 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
7775 ;; Remove quotes around the file name - we'll use shell-quote-argument.
7776 (while (string-match "['\"]%s['\"]" cmd)
7777 (setq cmd (replace-match "%s" t t cmd)))
7778 (while (string-match "%s" cmd)
7779 (setq cmd (replace-match
7780 (save-match-data (shell-quote-argument file))
7781 t t cmd)))
7782 (save-window-excursion
7783 (start-process-shell-command cmd nil cmd)))
7784 ((or (stringp cmd)
7785 (eq cmd 'emacs))
7786 (funcall (cdr (assq 'file org-link-frame-setup)) file)
7787 (widen)
7788 (if line (goto-line line)
7789 (if search (org-link-search search))))
7790 ((consp cmd)
7791 (eval cmd))
7792 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
7793 (and (org-mode-p) (eq old-mode 'org-mode)
7794 (or (not (equal old-buffer (current-buffer)))
7795 (not (equal old-pos (point))))
7796 (org-mark-ring-push old-pos old-buffer))))
7798 (defun org-default-apps ()
7799 "Return the default applications for this operating system."
7800 (cond
7801 ((eq system-type 'darwin)
7802 org-file-apps-defaults-macosx)
7803 ((eq system-type 'windows-nt)
7804 org-file-apps-defaults-windowsnt)
7805 (t org-file-apps-defaults-gnu)))
7807 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
7808 (defun org-file-remote-p (file)
7809 "Test whether FILE specifies a location on a remote system.
7810 Return non-nil if the location is indeed remote.
7812 For example, the filename \"/user@host:/foo\" specifies a location
7813 on the system \"/user@host:\"."
7814 (cond ((fboundp 'file-remote-p)
7815 (file-remote-p file))
7816 ((fboundp 'tramp-handle-file-remote-p)
7817 (tramp-handle-file-remote-p file))
7818 ((and (boundp 'ange-ftp-name-format)
7819 (string-match (car ange-ftp-name-format) file))
7821 (t nil)))
7824 ;;;; Hooks for remember.el, and refiling
7826 (defun org-get-org-file ()
7827 "Read a filename, with default directory `org-directory'."
7828 (let ((default (or org-default-notes-file remember-data-file)))
7829 (read-file-name (format "File name [%s]: " default)
7830 (file-name-as-directory org-directory)
7831 default)))
7833 (defun org-notes-order-reversed-p ()
7834 "Check if the current file should receive notes in reversed order."
7835 (cond
7836 ((not org-reverse-note-order) nil)
7837 ((eq t org-reverse-note-order) t)
7838 ((not (listp org-reverse-note-order)) nil)
7839 (t (catch 'exit
7840 (let ((all org-reverse-note-order)
7841 entry)
7842 (while (setq entry (pop all))
7843 (if (string-match (car entry) buffer-file-name)
7844 (throw 'exit (cdr entry))))
7845 nil)))))
7847 ;;;; Refiling
7849 (defvar org-refile-target-table nil
7850 "The list of refile targets, created by `org-refile'.")
7852 (defvar org-agenda-new-buffers nil
7853 "Buffers created to visit agenda files.")
7855 (defun org-get-refile-targets (&optional default-buffer)
7856 "Produce a table with refile targets."
7857 (let ((entries (or org-refile-targets '((nil . (:level . 1)))))
7858 targets txt re files f desc descre)
7859 (with-current-buffer (or default-buffer (current-buffer))
7860 (while (setq entry (pop entries))
7861 (setq files (car entry) desc (cdr entry))
7862 (cond
7863 ((null files) (setq files (list (current-buffer))))
7864 ((eq files 'org-agenda-files)
7865 (setq files (org-agenda-files 'unrestricted)))
7866 ((and (symbolp files) (fboundp files))
7867 (setq files (funcall files)))
7868 ((and (symbolp files) (boundp files))
7869 (setq files (symbol-value files))))
7870 (if (stringp files) (setq files (list files)))
7871 (cond
7872 ((eq (car desc) :tag)
7873 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
7874 ((eq (car desc) :todo)
7875 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
7876 ((eq (car desc) :regexp)
7877 (setq descre (cdr desc)))
7878 ((eq (car desc) :level)
7879 (setq descre (concat "^\\*\\{" (number-to-string
7880 (if org-odd-levels-only
7881 (1- (* 2 (cdr desc)))
7882 (cdr desc)))
7883 "\\}[ \t]")))
7884 ((eq (car desc) :maxlevel)
7885 (setq descre (concat "^\\*\\{1," (number-to-string
7886 (if org-odd-levels-only
7887 (1- (* 2 (cdr desc)))
7888 (cdr desc)))
7889 "\\}[ \t]")))
7890 (t (error "Bad refiling target description %s" desc)))
7891 (while (setq f (pop files))
7892 (save-excursion
7893 (set-buffer (if (bufferp f) f (org-get-agenda-file-buffer f)))
7894 (if (bufferp f) (setq f (buffer-file-name (buffer-base-buffer f))))
7895 (save-excursion
7896 (save-restriction
7897 (widen)
7898 (goto-char (point-min))
7899 (while (re-search-forward descre nil t)
7900 (goto-char (point-at-bol))
7901 (when (looking-at org-complex-heading-regexp)
7902 (setq txt (match-string 4)
7903 re (concat "^" (regexp-quote
7904 (buffer-substring (match-beginning 1)
7905 (match-end 4)))))
7906 (if (match-end 5) (setq re (concat re "[ \t]+"
7907 (regexp-quote
7908 (match-string 5)))))
7909 (setq re (concat re "[ \t]*$"))
7910 (when org-refile-use-outline-path
7911 (setq txt (mapconcat 'identity
7912 (append
7913 (if (eq org-refile-use-outline-path 'file)
7914 (list (file-name-nondirectory
7915 (buffer-file-name (buffer-base-buffer))))
7916 (if (eq org-refile-use-outline-path 'full-file-path)
7917 (list (buffer-file-name (buffer-base-buffer)))))
7918 (org-get-outline-path)
7919 (list txt))
7920 "/")))
7921 (push (list txt f re (point)) targets))
7922 (goto-char (point-at-eol))))))))
7923 (nreverse targets))))
7925 (defun org-get-outline-path ()
7926 "Return the outline path to the current entry, as a list."
7927 (let (rtn)
7928 (save-excursion
7929 (while (org-up-heading-safe)
7930 (when (looking-at org-complex-heading-regexp)
7931 (push (org-match-string-no-properties 4) rtn)))
7932 rtn)))
7934 (defvar org-refile-history nil
7935 "History for refiling operations.")
7937 (defun org-refile (&optional goto default-buffer)
7938 "Move the entry at point to another heading.
7939 The list of target headings is compiled using the information in
7940 `org-refile-targets', which see. This list is created upon first use, and
7941 you can update it by calling this command with a double prefix (`C-u C-u').
7942 FIXME: Can we find a better way of updating?
7944 At the target location, the entry is filed as a subitem of the target heading.
7945 Depending on `org-reverse-note-order', the new subitem will either be the
7946 first of the last subitem.
7948 With prefix arg GOTO, the command will only visit the target location,
7949 not actually move anything.
7950 With a double prefix `C-c C-c', go to the location where the last refiling
7951 operation has put the subtree.
7953 With a double prefix argument, the command can be used to jump to any
7954 heading in the current buffer."
7955 (interactive "P")
7956 (let* ((cbuf (current-buffer))
7957 (filename (buffer-file-name (buffer-base-buffer cbuf)))
7958 pos it nbuf file re level reversed)
7959 (if (equal goto '(16))
7960 (org-refile-goto-last-stored)
7961 (when (setq it (org-refile-get-location
7962 (if goto "Goto: " "Refile to: ") default-buffer))
7963 (setq file (nth 1 it)
7964 re (nth 2 it)
7965 pos (nth 3 it))
7966 (setq nbuf (or (find-buffer-visiting file)
7967 (find-file-noselect file)))
7968 (if goto
7969 (progn
7970 (switch-to-buffer nbuf)
7971 (goto-char pos)
7972 (org-show-context 'org-goto))
7973 (org-copy-special)
7974 (save-excursion
7975 (set-buffer (setq nbuf (or (find-buffer-visiting file)
7976 (find-file-noselect file))))
7977 (setq reversed (org-notes-order-reversed-p))
7978 (save-excursion
7979 (save-restriction
7980 (widen)
7981 (goto-char pos)
7982 (looking-at outline-regexp)
7983 (setq level (org-get-valid-level (funcall outline-level) 1))
7984 (goto-char
7985 (if reversed
7986 (outline-next-heading)
7987 (or (save-excursion (outline-get-next-sibling))
7988 (org-end-of-subtree t t)
7989 (point-max))))
7990 (bookmark-set "org-refile-last-stored")
7991 (org-paste-subtree level))))
7992 (org-cut-special)
7993 (message "Entry refiled to \"%s\"" (car it)))))))
7995 (defun org-refile-goto-last-stored ()
7996 "Go to the location where the last refile was stored."
7997 (interactive)
7998 (bookmark-jump "org-refile-last-stored")
7999 (message "This is the location of the last refile"))
8001 (defun org-refile-get-location (&optional prompt default-buffer)
8002 "Prompt the user for a refile location, using PROMPT."
8003 (let ((org-refile-targets org-refile-targets)
8004 (org-refile-use-outline-path org-refile-use-outline-path))
8005 (setq org-refile-target-table (org-get-refile-targets default-buffer)))
8006 (unless org-refile-target-table
8007 (error "No refile targets"))
8008 (let* ((cbuf (current-buffer))
8009 (filename (buffer-file-name (buffer-base-buffer cbuf)))
8010 (fname (and filename (file-truename filename)))
8011 (tbl (mapcar
8012 (lambda (x)
8013 (if (not (equal fname (file-truename (nth 1 x))))
8014 (cons (concat (car x) " (" (file-name-nondirectory
8015 (nth 1 x)) ")")
8016 (cdr x))
8018 org-refile-target-table))
8019 (completion-ignore-case t))
8020 (assoc (completing-read prompt tbl nil t nil 'org-refile-history)
8021 tbl)))
8023 ;;;; Dynamic blocks
8025 (defun org-find-dblock (name)
8026 "Find the first dynamic block with name NAME in the buffer.
8027 If not found, stay at current position and return nil."
8028 (let (pos)
8029 (save-excursion
8030 (goto-char (point-min))
8031 (setq pos (and (re-search-forward (concat "^#\\+BEGIN:[ \t]+" name "\\>")
8032 nil t)
8033 (match-beginning 0))))
8034 (if pos (goto-char pos))
8035 pos))
8037 (defconst org-dblock-start-re
8038 "^#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
8039 "Matches the startline of a dynamic block, with parameters.")
8041 (defconst org-dblock-end-re "^#\\+END\\([: \t\r\n]\\|$\\)"
8042 "Matches the end of a dyhamic block.")
8044 (defun org-create-dblock (plist)
8045 "Create a dynamic block section, with parameters taken from PLIST.
8046 PLIST must containe a :name entry which is used as name of the block."
8047 (unless (bolp) (newline))
8048 (let ((name (plist-get plist :name)))
8049 (insert "#+BEGIN: " name)
8050 (while plist
8051 (if (eq (car plist) :name)
8052 (setq plist (cddr plist))
8053 (insert " " (prin1-to-string (pop plist)))))
8054 (insert "\n\n#+END:\n")
8055 (beginning-of-line -2)))
8057 (defun org-prepare-dblock ()
8058 "Prepare dynamic block for refresh.
8059 This empties the block, puts the cursor at the insert position and returns
8060 the property list including an extra property :name with the block name."
8061 (unless (looking-at org-dblock-start-re)
8062 (error "Not at a dynamic block"))
8063 (let* ((begdel (1+ (match-end 0)))
8064 (name (org-no-properties (match-string 1)))
8065 (params (append (list :name name)
8066 (read (concat "(" (match-string 3) ")")))))
8067 (unless (re-search-forward org-dblock-end-re nil t)
8068 (error "Dynamic block not terminated"))
8069 (setq params
8070 (append params
8071 (list :content (buffer-substring
8072 begdel (match-beginning 0)))))
8073 (delete-region begdel (match-beginning 0))
8074 (goto-char begdel)
8075 (open-line 1)
8076 params))
8078 (defun org-map-dblocks (&optional command)
8079 "Apply COMMAND to all dynamic blocks in the current buffer.
8080 If COMMAND is not given, use `org-update-dblock'."
8081 (let ((cmd (or command 'org-update-dblock))
8082 pos)
8083 (save-excursion
8084 (goto-char (point-min))
8085 (while (re-search-forward org-dblock-start-re nil t)
8086 (goto-char (setq pos (match-beginning 0)))
8087 (condition-case nil
8088 (funcall cmd)
8089 (error (message "Error during update of dynamic block")))
8090 (goto-char pos)
8091 (unless (re-search-forward org-dblock-end-re nil t)
8092 (error "Dynamic block not terminated"))))))
8094 (defun org-dblock-update (&optional arg)
8095 "User command for updating dynamic blocks.
8096 Update the dynamic block at point. With prefix ARG, update all dynamic
8097 blocks in the buffer."
8098 (interactive "P")
8099 (if arg
8100 (org-update-all-dblocks)
8101 (or (looking-at org-dblock-start-re)
8102 (org-beginning-of-dblock))
8103 (org-update-dblock)))
8105 (defun org-update-dblock ()
8106 "Update the dynamic block at point
8107 This means to empty the block, parse for parameters and then call
8108 the correct writing function."
8109 (save-window-excursion
8110 (let* ((pos (point))
8111 (line (org-current-line))
8112 (params (org-prepare-dblock))
8113 (name (plist-get params :name))
8114 (cmd (intern (concat "org-dblock-write:" name))))
8115 (message "Updating dynamic block `%s' at line %d..." name line)
8116 (funcall cmd params)
8117 (message "Updating dynamic block `%s' at line %d...done" name line)
8118 (goto-char pos))))
8120 (defun org-beginning-of-dblock ()
8121 "Find the beginning of the dynamic block at point.
8122 Error if there is no scuh block at point."
8123 (let ((pos (point))
8124 beg)
8125 (end-of-line 1)
8126 (if (and (re-search-backward org-dblock-start-re nil t)
8127 (setq beg (match-beginning 0))
8128 (re-search-forward org-dblock-end-re nil t)
8129 (> (match-end 0) pos))
8130 (goto-char beg)
8131 (goto-char pos)
8132 (error "Not in a dynamic block"))))
8134 (defun org-update-all-dblocks ()
8135 "Update all dynamic blocks in the buffer.
8136 This function can be used in a hook."
8137 (when (org-mode-p)
8138 (org-map-dblocks 'org-update-dblock)))
8141 ;;;; Completion
8143 (defconst org-additional-option-like-keywords
8144 '("BEGIN_HTML" "BEGIN_LaTeX" "END_HTML" "END_LaTeX"
8145 "ORGTBL" "HTML:" "LaTeX:" "BEGIN:" "END:" "TBLFM"
8146 "BEGIN_EXAMPLE" "END_EXAMPLE"))
8148 (defun org-complete (&optional arg)
8149 "Perform completion on word at point.
8150 At the beginning of a headline, this completes TODO keywords as given in
8151 `org-todo-keywords'.
8152 If the current word is preceded by a backslash, completes the TeX symbols
8153 that are supported for HTML support.
8154 If the current word is preceded by \"#+\", completes special words for
8155 setting file options.
8156 In the line after \"#+STARTUP:, complete valid keywords.\"
8157 At all other locations, this simply calls the value of
8158 `org-completion-fallback-command'."
8159 (interactive "P")
8160 (org-without-partial-completion
8161 (catch 'exit
8162 (let* ((end (point))
8163 (beg1 (save-excursion
8164 (skip-chars-backward (org-re "[:alnum:]_@"))
8165 (point)))
8166 (beg (save-excursion
8167 (skip-chars-backward "a-zA-Z0-9_:$")
8168 (point)))
8169 (confirm (lambda (x) (stringp (car x))))
8170 (searchhead (equal (char-before beg) ?*))
8171 (tag (and (equal (char-before beg1) ?:)
8172 (equal (char-after (point-at-bol)) ?*)))
8173 (prop (and (equal (char-before beg1) ?:)
8174 (not (equal (char-after (point-at-bol)) ?*))))
8175 (texp (equal (char-before beg) ?\\))
8176 (link (equal (char-before beg) ?\[))
8177 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
8178 beg)
8179 "#+"))
8180 (startup (string-match "^#\\+STARTUP:.*"
8181 (buffer-substring (point-at-bol) (point))))
8182 (completion-ignore-case opt)
8183 (type nil)
8184 (tbl nil)
8185 (table (cond
8186 (opt
8187 (setq type :opt)
8188 (require 'org-exp)
8189 (append
8190 (mapcar
8191 (lambda (x)
8192 (string-match "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
8193 (cons (match-string 2 x) (match-string 1 x)))
8194 (org-split-string (org-get-current-options) "\n"))
8195 (mapcar 'list org-additional-option-like-keywords)))
8196 (startup
8197 (setq type :startup)
8198 org-startup-options)
8199 (link (append org-link-abbrev-alist-local
8200 org-link-abbrev-alist))
8201 (texp
8202 (setq type :tex)
8203 org-html-entities)
8204 ((string-match "\\`\\*+[ \t]+\\'"
8205 (buffer-substring (point-at-bol) beg))
8206 (setq type :todo)
8207 (mapcar 'list org-todo-keywords-1))
8208 (searchhead
8209 (setq type :searchhead)
8210 (save-excursion
8211 (goto-char (point-min))
8212 (while (re-search-forward org-todo-line-regexp nil t)
8213 (push (list
8214 (org-make-org-heading-search-string
8215 (match-string 3) t))
8216 tbl)))
8217 tbl)
8218 (tag (setq type :tag beg beg1)
8219 (or org-tag-alist (org-get-buffer-tags)))
8220 (prop (setq type :prop beg beg1)
8221 (mapcar 'list (org-buffer-property-keys nil t t)))
8222 (t (progn
8223 (call-interactively org-completion-fallback-command)
8224 (throw 'exit nil)))))
8225 (pattern (buffer-substring-no-properties beg end))
8226 (completion (try-completion pattern table confirm)))
8227 (cond ((eq completion t)
8228 (if (not (assoc (upcase pattern) table))
8229 (message "Already complete")
8230 (if (and (equal type :opt)
8231 (not (member (car (assoc (upcase pattern) table))
8232 org-additional-option-like-keywords)))
8233 (insert (substring (cdr (assoc (upcase pattern) table))
8234 (length pattern)))
8235 (if (memq type '(:tag :prop)) (insert ":")))))
8236 ((null completion)
8237 (message "Can't find completion for \"%s\"" pattern)
8238 (ding))
8239 ((not (string= pattern completion))
8240 (delete-region beg end)
8241 (if (string-match " +$" completion)
8242 (setq completion (replace-match "" t t completion)))
8243 (insert completion)
8244 (if (get-buffer-window "*Completions*")
8245 (delete-window (get-buffer-window "*Completions*")))
8246 (if (assoc completion table)
8247 (if (eq type :todo) (insert " ")
8248 (if (memq type '(:tag :prop)) (insert ":"))))
8249 (if (and (equal type :opt) (assoc completion table))
8250 (message "%s" (substitute-command-keys
8251 "Press \\[org-complete] again to insert example settings"))))
8253 (message "Making completion list...")
8254 (let ((list (sort (all-completions pattern table confirm)
8255 'string<)))
8256 (with-output-to-temp-buffer "*Completions*"
8257 (condition-case nil
8258 ;; Protection needed for XEmacs and emacs 21
8259 (display-completion-list list pattern)
8260 (error (display-completion-list list)))))
8261 (message "Making completion list...%s" "done")))))))
8263 ;;;; TODO, DEADLINE, Comments
8265 (defun org-toggle-comment ()
8266 "Change the COMMENT state of an entry."
8267 (interactive)
8268 (save-excursion
8269 (org-back-to-heading)
8270 (let (case-fold-search)
8271 (if (looking-at (concat outline-regexp
8272 "\\( *\\<" org-comment-string "\\>[ \t]*\\)"))
8273 (replace-match "" t t nil 1)
8274 (if (looking-at outline-regexp)
8275 (progn
8276 (goto-char (match-end 0))
8277 (insert org-comment-string " ")))))))
8279 (defvar org-last-todo-state-is-todo nil
8280 "This is non-nil when the last TODO state change led to a TODO state.
8281 If the last change removed the TODO tag or switched to DONE, then
8282 this is nil.")
8284 (defvar org-setting-tags nil) ; dynamically skiped
8286 ;; FIXME: better place
8287 (defun org-property-or-variable-value (var &optional inherit)
8288 "Check if there is a property fixing the value of VAR.
8289 If yes, return this value. If not, return the current value of the variable."
8290 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
8291 (if (and prop (stringp prop) (string-match "\\S-" prop))
8292 (read prop)
8293 (symbol-value var))))
8295 (defun org-parse-local-options (string var)
8296 "Parse STRING for startup setting relevant for variable VAR."
8297 (let ((rtn (symbol-value var))
8298 e opts)
8299 (save-match-data
8300 (if (or (not string) (not (string-match "\\S-" string)))
8302 (setq opts (delq nil (mapcar (lambda (x)
8303 (setq e (assoc x org-startup-options))
8304 (if (eq (nth 1 e) var) e nil))
8305 (org-split-string string "[ \t]+"))))
8306 (if (not opts)
8308 (setq rtn nil)
8309 (while (setq e (pop opts))
8310 (if (not (nth 3 e))
8311 (setq rtn (nth 2 e))
8312 (if (not (listp rtn)) (setq rtn nil))
8313 (push (nth 2 e) rtn)))
8314 rtn)))))
8316 (defvar org-blocker-hook nil
8317 "Hook for functions that are allowed to block a state change.
8319 Each function gets as its single argument a property list, see
8320 `org-trigger-hook' for more information about this list.
8322 If any of the functions in this hook returns nil, the state change
8323 is blocked.")
8325 (defvar org-trigger-hook nil
8326 "Hook for functions that are triggered by a state change.
8328 Each function gets as its single argument a property list with at least
8329 the following elements:
8331 (:type type-of-change :position pos-at-entry-start
8332 :from old-state :to new-state)
8334 Depending on the type, more properties may be present.
8336 This mechanism is currently implemented for:
8338 TODO state changes
8339 ------------------
8340 :type todo-state-change
8341 :from previous state (keyword as a string), or nil
8342 :to new state (keyword as a string), or nil")
8345 (defun org-todo (&optional arg)
8346 "Change the TODO state of an item.
8347 The state of an item is given by a keyword at the start of the heading,
8348 like
8349 *** TODO Write paper
8350 *** DONE Call mom
8352 The different keywords are specified in the variable `org-todo-keywords'.
8353 By default the available states are \"TODO\" and \"DONE\".
8354 So for this example: when the item starts with TODO, it is changed to DONE.
8355 When it starts with DONE, the DONE is removed. And when neither TODO nor
8356 DONE are present, add TODO at the beginning of the heading.
8358 With C-u prefix arg, use completion to determine the new state.
8359 With numeric prefix arg, switch to that state.
8361 For calling through lisp, arg is also interpreted in the following way:
8362 'none -> empty state
8363 \"\"(empty string) -> switch to empty state
8364 'done -> switch to DONE
8365 'nextset -> switch to the next set of keywords
8366 'previousset -> switch to the previous set of keywords
8367 \"WAITING\" -> switch to the specified keyword, but only if it
8368 really is a member of `org-todo-keywords'."
8369 (interactive "P")
8370 (save-excursion
8371 (catch 'exit
8372 (org-back-to-heading)
8373 (if (looking-at outline-regexp) (goto-char (1- (match-end 0))))
8374 (or (looking-at (concat " +" org-todo-regexp " *"))
8375 (looking-at " *"))
8376 (let* ((match-data (match-data))
8377 (startpos (point-at-bol))
8378 (logging (save-match-data (org-entry-get nil "LOGGING" t)))
8379 (org-log-done org-log-done)
8380 (org-log-repeat org-log-repeat)
8381 (org-todo-log-states org-todo-log-states)
8382 (this (match-string 1))
8383 (hl-pos (match-beginning 0))
8384 (head (org-get-todo-sequence-head this))
8385 (ass (assoc head org-todo-kwd-alist))
8386 (interpret (nth 1 ass))
8387 (done-word (nth 3 ass))
8388 (final-done-word (nth 4 ass))
8389 (last-state (or this ""))
8390 (completion-ignore-case t)
8391 (member (member this org-todo-keywords-1))
8392 (tail (cdr member))
8393 (state (cond
8394 ((and org-todo-key-trigger
8395 (or (and (equal arg '(4)) (eq org-use-fast-todo-selection 'prefix))
8396 (and (not arg) org-use-fast-todo-selection
8397 (not (eq org-use-fast-todo-selection 'prefix)))))
8398 ;; Use fast selection
8399 (org-fast-todo-selection))
8400 ((and (equal arg '(4))
8401 (or (not org-use-fast-todo-selection)
8402 (not org-todo-key-trigger)))
8403 ;; Read a state with completion
8404 (completing-read "State: " (mapcar (lambda(x) (list x))
8405 org-todo-keywords-1)
8406 nil t))
8407 ((eq arg 'right)
8408 (if this
8409 (if tail (car tail) nil)
8410 (car org-todo-keywords-1)))
8411 ((eq arg 'left)
8412 (if (equal member org-todo-keywords-1)
8414 (if this
8415 (nth (- (length org-todo-keywords-1) (length tail) 2)
8416 org-todo-keywords-1)
8417 (org-last org-todo-keywords-1))))
8418 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
8419 (setq arg nil))) ; hack to fall back to cycling
8420 (arg
8421 ;; user or caller requests a specific state
8422 (cond
8423 ((equal arg "") nil)
8424 ((eq arg 'none) nil)
8425 ((eq arg 'done) (or done-word (car org-done-keywords)))
8426 ((eq arg 'nextset)
8427 (or (car (cdr (member head org-todo-heads)))
8428 (car org-todo-heads)))
8429 ((eq arg 'previousset)
8430 (let ((org-todo-heads (reverse org-todo-heads)))
8431 (or (car (cdr (member head org-todo-heads)))
8432 (car org-todo-heads))))
8433 ((car (member arg org-todo-keywords-1)))
8434 ((nth (1- (prefix-numeric-value arg))
8435 org-todo-keywords-1))))
8436 ((null member) (or head (car org-todo-keywords-1)))
8437 ((equal this final-done-word) nil) ;; -> make empty
8438 ((null tail) nil) ;; -> first entry
8439 ((eq interpret 'sequence)
8440 (car tail))
8441 ((memq interpret '(type priority))
8442 (if (eq this-command last-command)
8443 (car tail)
8444 (if (> (length tail) 0)
8445 (or done-word (car org-done-keywords))
8446 nil)))
8447 (t nil)))
8448 (next (if state (concat " " state " ") " "))
8449 (change-plist (list :type 'todo-state-change :from this :to state
8450 :position startpos))
8451 dolog now-done-p)
8452 (when org-blocker-hook
8453 (unless (save-excursion
8454 (save-match-data
8455 (run-hook-with-args-until-failure
8456 'org-blocker-hook change-plist)))
8457 (if (interactive-p)
8458 (error "TODO state change from %s to %s blocked" this state)
8459 ;; fail silently
8460 (message "TODO state change from %s to %s blocked" this state)
8461 (throw 'exit nil))))
8462 (store-match-data match-data)
8463 (replace-match next t t)
8464 (unless (pos-visible-in-window-p hl-pos)
8465 (message "TODO state changed to %s" (org-trim next)))
8466 (unless head
8467 (setq head (org-get-todo-sequence-head state)
8468 ass (assoc head org-todo-kwd-alist)
8469 interpret (nth 1 ass)
8470 done-word (nth 3 ass)
8471 final-done-word (nth 4 ass)))
8472 (when (memq arg '(nextset previousset))
8473 (message "Keyword-Set %d/%d: %s"
8474 (- (length org-todo-sets) -1
8475 (length (memq (assoc state org-todo-sets) org-todo-sets)))
8476 (length org-todo-sets)
8477 (mapconcat 'identity (assoc state org-todo-sets) " ")))
8478 (setq org-last-todo-state-is-todo
8479 (not (member state org-done-keywords)))
8480 (setq now-done-p (and (member state org-done-keywords)
8481 (not (member this org-done-keywords))))
8482 (and logging (org-local-logging logging))
8483 (when (and (or org-todo-log-states org-log-done)
8484 (not (memq arg '(nextset previousset))))
8485 ;; we need to look at recording a time and note
8486 (setq dolog (or (nth 1 (assoc state org-todo-log-states))
8487 (nth 2 (assoc this org-todo-log-states))))
8488 (when (and state
8489 (member state org-not-done-keywords)
8490 (not (member this org-not-done-keywords)))
8491 ;; This is now a todo state and was not one before
8492 ;; If there was a CLOSED time stamp, get rid of it.
8493 (org-add-planning-info nil nil 'closed))
8494 (when (and now-done-p org-log-done)
8495 ;; It is now done, and it was not done before
8496 (org-add-planning-info 'closed (org-current-time))
8497 (if (and (not dolog) (eq 'note org-log-done))
8498 (org-add-log-setup 'done state 'findpos 'note)))
8499 (when (and state dolog)
8500 ;; This is a non-nil state, and we need to log it
8501 (org-add-log-setup 'state state 'findpos dolog)))
8502 ;; Fixup tag positioning
8503 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
8504 (run-hooks 'org-after-todo-state-change-hook)
8505 (if (and arg (not (member state org-done-keywords)))
8506 (setq head (org-get-todo-sequence-head state)))
8507 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
8508 ;; Do we need to trigger a repeat?
8509 (when now-done-p (org-auto-repeat-maybe state))
8510 ;; Fixup cursor location if close to the keyword
8511 (if (and (outline-on-heading-p)
8512 (not (bolp))
8513 (save-excursion (beginning-of-line 1)
8514 (looking-at org-todo-line-regexp))
8515 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
8516 (progn
8517 (goto-char (or (match-end 2) (match-end 1)))
8518 (just-one-space)))
8519 (when org-trigger-hook
8520 (save-excursion
8521 (run-hook-with-args 'org-trigger-hook change-plist)))))))
8523 (defun org-local-logging (value)
8524 "Get logging settings from a property VALUE."
8525 (let* (words w a)
8526 ;; directly set the variables, they are already local.
8527 (setq org-log-done nil
8528 org-log-repeat nil
8529 org-todo-log-states nil)
8530 (setq words (org-split-string value))
8531 (while (setq w (pop words))
8532 (cond
8533 ((setq a (assoc w org-startup-options))
8534 (and (member (nth 1 a) '(org-log-done org-log-repeat))
8535 (set (nth 1 a) (nth 2 a))))
8536 ((setq a (org-extract-log-state-settings w))
8537 (and (member (car a) org-todo-keywords-1)
8538 (push a org-todo-log-states)))))))
8540 (defun org-get-todo-sequence-head (kwd)
8541 "Return the head of the TODO sequence to which KWD belongs.
8542 If KWD is not set, check if there is a text property remembering the
8543 right sequence."
8544 (let (p)
8545 (cond
8546 ((not kwd)
8547 (or (get-text-property (point-at-bol) 'org-todo-head)
8548 (progn
8549 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
8550 nil (point-at-eol)))
8551 (get-text-property p 'org-todo-head))))
8552 ((not (member kwd org-todo-keywords-1))
8553 (car org-todo-keywords-1))
8554 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
8556 (defun org-fast-todo-selection ()
8557 "Fast TODO keyword selection with single keys.
8558 Returns the new TODO keyword, or nil if no state change should occur."
8559 (let* ((fulltable org-todo-key-alist)
8560 (done-keywords org-done-keywords) ;; needed for the faces.
8561 (maxlen (apply 'max (mapcar
8562 (lambda (x)
8563 (if (stringp (car x)) (string-width (car x)) 0))
8564 fulltable)))
8565 (expert nil)
8566 (fwidth (+ maxlen 3 1 3))
8567 (ncol (/ (- (window-width) 4) fwidth))
8568 tg cnt e c tbl
8569 groups ingroup)
8570 (save-window-excursion
8571 (if expert
8572 (set-buffer (get-buffer-create " *Org todo*"))
8573 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
8574 (erase-buffer)
8575 (org-set-local 'org-done-keywords done-keywords)
8576 (setq tbl fulltable cnt 0)
8577 (while (setq e (pop tbl))
8578 (cond
8579 ((equal e '(:startgroup))
8580 (push '() groups) (setq ingroup t)
8581 (when (not (= cnt 0))
8582 (setq cnt 0)
8583 (insert "\n"))
8584 (insert "{ "))
8585 ((equal e '(:endgroup))
8586 (setq ingroup nil cnt 0)
8587 (insert "}\n"))
8589 (setq tg (car e) c (cdr e))
8590 (if ingroup (push tg (car groups)))
8591 (setq tg (org-add-props tg nil 'face
8592 (org-get-todo-face tg)))
8593 (if (and (= cnt 0) (not ingroup)) (insert " "))
8594 (insert "[" c "] " tg (make-string
8595 (- fwidth 4 (length tg)) ?\ ))
8596 (when (= (setq cnt (1+ cnt)) ncol)
8597 (insert "\n")
8598 (if ingroup (insert " "))
8599 (setq cnt 0)))))
8600 (insert "\n")
8601 (goto-char (point-min))
8602 (if (and (not expert) (fboundp 'fit-window-to-buffer))
8603 (fit-window-to-buffer))
8604 (message "[a-z..]:Set [SPC]:clear")
8605 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
8606 (cond
8607 ((or (= c ?\C-g)
8608 (and (= c ?q) (not (rassoc c fulltable))))
8609 (setq quit-flag t))
8610 ((= c ?\ ) nil)
8611 ((setq e (rassoc c fulltable) tg (car e))
8613 (t (setq quit-flag t))))))
8615 (defun org-entry-is-todo-p ()
8616 (member (org-get-todo-state) org-not-done-keywords))
8618 (defun org-entry-is-done-p ()
8619 (member (org-get-todo-state) org-done-keywords))
8621 (defun org-get-todo-state ()
8622 (save-excursion
8623 (org-back-to-heading t)
8624 (and (looking-at org-todo-line-regexp)
8625 (match-end 2)
8626 (match-string 2))))
8628 (defun org-at-date-range-p (&optional inactive-ok)
8629 "Is the cursor inside a date range?"
8630 (interactive)
8631 (save-excursion
8632 (catch 'exit
8633 (let ((pos (point)))
8634 (skip-chars-backward "^[<\r\n")
8635 (skip-chars-backward "<[")
8636 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
8637 (>= (match-end 0) pos)
8638 (throw 'exit t))
8639 (skip-chars-backward "^<[\r\n")
8640 (skip-chars-backward "<[")
8641 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
8642 (>= (match-end 0) pos)
8643 (throw 'exit t)))
8644 nil)))
8646 (defun org-get-repeat ()
8647 "Check if tere is a deadline/schedule with repeater in this entry."
8648 (save-match-data
8649 (save-excursion
8650 (org-back-to-heading t)
8651 (if (re-search-forward
8652 org-repeat-re (save-excursion (outline-next-heading) (point)) t)
8653 (match-string 1)))))
8655 (defvar org-last-changed-timestamp)
8656 (defvar org-log-post-message)
8657 (defvar org-log-note-purpose)
8658 (defun org-auto-repeat-maybe (done-word)
8659 "Check if the current headline contains a repeated deadline/schedule.
8660 If yes, set TODO state back to what it was and change the base date
8661 of repeating deadline/scheduled time stamps to new date.
8662 This function is run automatically after each state change to a DONE state."
8663 ;; last-state is dynamically scoped into this function
8664 (let* ((repeat (org-get-repeat))
8665 (aa (assoc last-state org-todo-kwd-alist))
8666 (interpret (nth 1 aa))
8667 (head (nth 2 aa))
8668 (whata '(("d" . day) ("m" . month) ("y" . year)))
8669 (msg "Entry repeats: ")
8670 (org-log-done nil)
8671 (org-todo-log-states nil)
8672 (nshiftmax 10) (nshift 0)
8673 re type n what ts mb0 time)
8674 (when repeat
8675 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
8676 (org-todo (if (eq interpret 'type) last-state head))
8677 (when (and org-log-repeat
8678 (or (not (memq 'org-add-log-note
8679 (default-value 'post-command-hook)))
8680 (eq org-log-note-purpose 'done)))
8681 ;; Make sure a note is taken;
8682 (org-add-log-setup 'state (or done-word (car org-done-keywords))
8683 'findpos org-log-repeat))
8684 (org-back-to-heading t)
8685 (org-add-planning-info nil nil 'closed)
8686 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
8687 org-deadline-time-regexp "\\)\\|\\("
8688 org-ts-regexp "\\)"))
8689 (while (re-search-forward
8690 re (save-excursion (outline-next-heading) (point)) t)
8691 (setq type (if (match-end 1) org-scheduled-string
8692 (if (match-end 3) org-deadline-string "Plain:"))
8693 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0)))
8694 mb0 (match-beginning 0))
8695 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts)
8696 (setq n (string-to-number (match-string 2 ts))
8697 what (match-string 3 ts))
8698 (if (equal what "w") (setq n (* n 7) what "d"))
8699 ;; Preparation, see if we need to modify the start date for the change
8700 (when (match-end 1)
8701 (setq time (save-match-data (org-time-string-to-time ts)))
8702 (cond
8703 ((equal (match-string 1 ts) ".")
8704 ;; Shift starting date to today
8705 (org-timestamp-change
8706 (- (time-to-days (current-time)) (time-to-days time))
8707 'day))
8708 ((equal (match-string 1 ts) "+")
8709 (while (or (= nshift 0)
8710 (<= (time-to-days time) (time-to-days (current-time))))
8711 (when (= (incf nshift) nshiftmax)
8712 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
8713 (error "Abort")))
8714 (org-timestamp-change n (cdr (assoc what whata)))
8715 (org-at-timestamp-p t)
8716 (setq ts (match-string 1))
8717 (setq time (save-match-data (org-time-string-to-time ts))))
8718 (org-timestamp-change (- n) (cdr (assoc what whata)))
8719 ;; rematch, so that we have everything in place for the real shift
8720 (org-at-timestamp-p t)
8721 (setq ts (match-string 1))
8722 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts))))
8723 (org-timestamp-change n (cdr (assoc what whata)))
8724 (setq msg (concat msg type org-last-changed-timestamp " "))))
8725 (setq org-log-post-message msg)
8726 (message "%s" msg))))
8728 (defun org-show-todo-tree (arg)
8729 "Make a compact tree which shows all headlines marked with TODO.
8730 The tree will show the lines where the regexp matches, and all higher
8731 headlines above the match.
8732 With a \\[universal-argument] prefix, also show the DONE entries.
8733 With a numeric prefix N, construct a sparse tree for the Nth element
8734 of `org-todo-keywords-1'."
8735 (interactive "P")
8736 (let ((case-fold-search nil)
8737 (kwd-re
8738 (cond ((null arg) org-not-done-regexp)
8739 ((equal arg '(4))
8740 (let ((kwd (completing-read "Keyword (or KWD1|KWD2|...): "
8741 (mapcar 'list org-todo-keywords-1))))
8742 (concat "\\("
8743 (mapconcat 'identity (org-split-string kwd "|") "\\|")
8744 "\\)\\>")))
8745 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
8746 (regexp-quote (nth (1- (prefix-numeric-value arg))
8747 org-todo-keywords-1)))
8748 (t (error "Invalid prefix argument: %s" arg)))))
8749 (message "%d TODO entries found"
8750 (org-occur (concat "^" outline-regexp " *" kwd-re )))))
8752 (defun org-deadline (&optional remove)
8753 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
8754 With argument REMOVE, remove any deadline from the item."
8755 (interactive "P")
8756 (if remove
8757 (progn
8758 (org-remove-timestamp-with-keyword org-deadline-string)
8759 (message "Item no longer has a deadline."))
8760 (org-add-planning-info 'deadline nil 'closed)))
8762 (defun org-schedule (&optional remove)
8763 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
8764 With argument REMOVE, remove any scheduling date from the item."
8765 (interactive "P")
8766 (if remove
8767 (progn
8768 (org-remove-timestamp-with-keyword org-scheduled-string)
8769 (message "Item is no longer scheduled."))
8770 (org-add-planning-info 'scheduled nil 'closed)))
8772 (defun org-remove-timestamp-with-keyword (keyword)
8773 "Remove all time stamps with KEYWORD in the current entry."
8774 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
8775 beg)
8776 (save-excursion
8777 (org-back-to-heading t)
8778 (setq beg (point))
8779 (org-end-of-subtree t t)
8780 (while (re-search-backward re beg t)
8781 (replace-match "")
8782 (unless (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
8783 (delete-region (point-at-bol) (min (1+ (point)) (point-max))))))))
8785 (defun org-add-planning-info (what &optional time &rest remove)
8786 "Insert new timestamp with keyword in the line directly after the headline.
8787 WHAT indicates what kind of time stamp to add. TIME indicated the time to use.
8788 If non is given, the user is prompted for a date.
8789 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
8790 be removed."
8791 (interactive)
8792 (let (org-time-was-given org-end-time-was-given ts
8793 end default-time default-input)
8795 (when (and (not time) (memq what '(scheduled deadline)))
8796 ;; Try to get a default date/time from existing timestamp
8797 (save-excursion
8798 (org-back-to-heading t)
8799 (setq end (save-excursion (outline-next-heading) (point)))
8800 (when (re-search-forward (if (eq what 'scheduled)
8801 org-scheduled-time-regexp
8802 org-deadline-time-regexp)
8803 end t)
8804 (setq ts (match-string 1)
8805 default-time
8806 (apply 'encode-time (org-parse-time-string ts))
8807 default-input (and ts (org-get-compact-tod ts))))))
8808 (when what
8809 ;; If necessary, get the time from the user
8810 (setq time (or time (org-read-date nil 'to-time nil nil
8811 default-time default-input))))
8813 (when (and org-insert-labeled-timestamps-at-point
8814 (member what '(scheduled deadline)))
8815 (insert
8816 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
8817 (org-insert-time-stamp time org-time-was-given
8818 nil nil nil (list org-end-time-was-given))
8819 (setq what nil))
8820 (save-excursion
8821 (save-restriction
8822 (let (col list elt ts buffer-invisibility-spec)
8823 (org-back-to-heading t)
8824 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
8825 (goto-char (match-end 1))
8826 (setq col (current-column))
8827 (goto-char (match-end 0))
8828 (if (eobp) (insert "\n") (forward-char 1))
8829 (if (and (not (looking-at outline-regexp))
8830 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
8831 "[^\r\n]*"))
8832 (not (equal (match-string 1) org-clock-string)))
8833 (narrow-to-region (match-beginning 0) (match-end 0))
8834 (insert-before-markers "\n")
8835 (backward-char 1)
8836 (narrow-to-region (point) (point))
8837 (indent-to-column col))
8838 ;; Check if we have to remove something.
8839 (setq list (cons what remove))
8840 (while list
8841 (setq elt (pop list))
8842 (goto-char (point-min))
8843 (when (or (and (eq elt 'scheduled)
8844 (re-search-forward org-scheduled-time-regexp nil t))
8845 (and (eq elt 'deadline)
8846 (re-search-forward org-deadline-time-regexp nil t))
8847 (and (eq elt 'closed)
8848 (re-search-forward org-closed-time-regexp nil t)))
8849 (replace-match "")
8850 (if (looking-at "--+<[^>]+>") (replace-match ""))
8851 (if (looking-at " +") (replace-match ""))))
8852 (goto-char (point-max))
8853 (when what
8854 (insert
8855 (if (not (equal (char-before) ?\ )) " " "")
8856 (cond ((eq what 'scheduled) org-scheduled-string)
8857 ((eq what 'deadline) org-deadline-string)
8858 ((eq what 'closed) org-closed-string))
8859 " ")
8860 (setq ts (org-insert-time-stamp
8861 time
8862 (or org-time-was-given
8863 (and (eq what 'closed) org-log-done-with-time))
8864 (eq what 'closed)
8865 nil nil (list org-end-time-was-given)))
8866 (end-of-line 1))
8867 (goto-char (point-min))
8868 (widen)
8869 (if (looking-at "[ \t]+\r?\n")
8870 (replace-match ""))
8871 ts)))))
8873 (defvar org-log-note-marker (make-marker))
8874 (defvar org-log-note-purpose nil)
8875 (defvar org-log-note-state nil)
8876 (defvar org-log-note-how nil)
8877 (defvar org-log-note-window-configuration nil)
8878 (defvar org-log-note-return-to (make-marker))
8879 (defvar org-log-post-message nil
8880 "Message to be displayed after a log note has been stored.
8881 The auto-repeater uses this.")
8883 (defun org-add-note ()
8884 "Add a note to the current entry.
8885 This is done in the same way as adding a state change note."
8886 (interactive)
8887 (org-add-log-setup 'note nil t nil))
8889 (defun org-add-log-setup (&optional purpose state findpos how)
8890 "Set up the post command hook to take a note.
8891 If this is about to TODO state change, the new state is expected in STATE.
8892 When FINDPOS is non-nil, find the correct position for the note in
8893 the current entry. If not, assume that it can be inserted at point."
8894 (save-excursion
8895 (when findpos
8896 (org-back-to-heading t)
8897 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"
8898 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
8899 "[^\r\n]*\\)?"))
8900 (goto-char (match-end 0))
8901 (unless org-log-states-order-reversed
8902 (and (= (char-after) ?\n) (forward-char 1))
8903 (org-skip-over-state-notes)
8904 (skip-chars-backward " \t\n\r")))
8905 (move-marker org-log-note-marker (point))
8906 (setq org-log-note-purpose purpose
8907 org-log-note-state state
8908 org-log-note-how how)
8909 (add-hook 'post-command-hook 'org-add-log-note 'append)))
8911 (defun org-skip-over-state-notes ()
8912 "Skip past the list of State notes in an entry."
8913 (if (looking-at "\n[ \t]*- State") (forward-char 1))
8914 (while (looking-at "[ \t]*- State")
8915 (condition-case nil
8916 (org-next-item)
8917 (error (org-end-of-item)))))
8919 (defun org-add-log-note (&optional purpose)
8920 "Pop up a window for taking a note, and add this note later at point."
8921 (remove-hook 'post-command-hook 'org-add-log-note)
8922 (setq org-log-note-window-configuration (current-window-configuration))
8923 (delete-other-windows)
8924 (move-marker org-log-note-return-to (point))
8925 (switch-to-buffer (marker-buffer org-log-note-marker))
8926 (goto-char org-log-note-marker)
8927 (org-switch-to-buffer-other-window "*Org Note*")
8928 (erase-buffer)
8929 (if (memq org-log-note-how '(time state)) ; FIXME: time or state????????????
8930 (org-store-log-note)
8931 (let ((org-inhibit-startup t)) (org-mode))
8932 (insert (format "# Insert note for %s.
8933 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
8934 (cond
8935 ((eq org-log-note-purpose 'clock-out) "stopped clock")
8936 ((eq org-log-note-purpose 'done) "closed todo item")
8937 ((eq org-log-note-purpose 'state)
8938 (format "state change to \"%s\"" org-log-note-state))
8939 ((eq org-log-note-purpose 'note)
8940 "this entry")
8941 (t (error "This should not happen")))))
8942 (org-set-local 'org-finish-function 'org-store-log-note)))
8944 (defvar org-note-abort nil) ; dynamically scoped
8945 (defun org-store-log-note ()
8946 "Finish taking a log note, and insert it to where it belongs."
8947 (let ((txt (buffer-string))
8948 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
8949 lines ind)
8950 (kill-buffer (current-buffer))
8951 (while (string-match "\\`#.*\n[ \t\n]*" txt)
8952 (setq txt (replace-match "" t t txt)))
8953 (if (string-match "\\s-+\\'" txt)
8954 (setq txt (replace-match "" t t txt)))
8955 (setq lines (org-split-string txt "\n"))
8956 (when (and note (string-match "\\S-" note))
8957 (setq note
8958 (org-replace-escapes
8959 note
8960 (list (cons "%u" (user-login-name))
8961 (cons "%U" user-full-name)
8962 (cons "%t" (format-time-string
8963 (org-time-stamp-format 'long 'inactive)
8964 (current-time)))
8965 (cons "%s" (if org-log-note-state
8966 (concat "\"" org-log-note-state "\"")
8967 "")))))
8968 (if lines (setq note (concat note " \\\\")))
8969 (push note lines))
8970 (when (or current-prefix-arg org-note-abort) (setq lines nil))
8971 (when lines
8972 (save-excursion
8973 (set-buffer (marker-buffer org-log-note-marker))
8974 (save-excursion
8975 (goto-char org-log-note-marker)
8976 (move-marker org-log-note-marker nil)
8977 (end-of-line 1)
8978 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
8979 (indent-relative nil)
8980 (insert "- " (pop lines))
8981 (org-indent-line-function)
8982 (beginning-of-line 1)
8983 (looking-at "[ \t]*")
8984 (setq ind (concat (match-string 0) " "))
8985 (end-of-line 1)
8986 (while lines (insert "\n" ind (pop lines)))))))
8987 (set-window-configuration org-log-note-window-configuration)
8988 (with-current-buffer (marker-buffer org-log-note-return-to)
8989 (goto-char org-log-note-return-to))
8990 (move-marker org-log-note-return-to nil)
8991 (and org-log-post-message (message "%s" org-log-post-message)))
8993 ;; FIXME: what else would be useful?
8994 ;; - priority
8995 ;; - date
8997 (defun org-sparse-tree (&optional arg)
8998 "Create a sparse tree, prompt for the details.
8999 This command can create sparse trees. You first need to select the type
9000 of match used to create the tree:
9002 t Show entries with a specific TODO keyword.
9003 T Show entries selected by a tags match.
9004 p Enter a property name and its value (both with completion on existing
9005 names/values) and show entries with that property.
9006 r Show entries matching a regular expression
9007 d Show deadlines due within `org-deadline-warning-days'."
9008 (interactive "P")
9009 (let (ans kwd value)
9010 (message "Sparse tree: [/]regexp [t]odo-kwd [T]ag [p]roperty [d]eadlines [b]efore-date")
9011 (setq ans (read-char-exclusive))
9012 (cond
9013 ((equal ans ?d)
9014 (call-interactively 'org-check-deadlines))
9015 ((equal ans ?b)
9016 (call-interactively 'org-check-before-date))
9017 ((equal ans ?t)
9018 (org-show-todo-tree '(4)))
9019 ((equal ans ?T)
9020 (call-interactively 'org-tags-sparse-tree))
9021 ((member ans '(?p ?P))
9022 (setq kwd (completing-read "Property: "
9023 (mapcar 'list (org-buffer-property-keys))))
9024 (setq value (completing-read "Value: "
9025 (mapcar 'list (org-property-values kwd))))
9026 (unless (string-match "\\`{.*}\\'" value)
9027 (setq value (concat "\"" value "\"")))
9028 (org-tags-sparse-tree arg (concat kwd "=" value)))
9029 ((member ans '(?r ?R ?/))
9030 (call-interactively 'org-occur))
9031 (t (error "No such sparse tree command \"%c\"" ans)))))
9033 (defvar org-occur-highlights nil
9034 "List of overlays used for occur matches.")
9035 (make-variable-buffer-local 'org-occur-highlights)
9036 (defvar org-occur-parameters nil
9037 "Parameters of the active org-occur calls.
9038 This is a list, each call to org-occur pushes as cons cell,
9039 containing the regular expression and the callback, onto the list.
9040 The list can contain several entries if `org-occur' has been called
9041 several time with the KEEP-PREVIOUS argument. Otherwise, this list
9042 will only contain one set of parameters. When the highlights are
9043 removed (for example with `C-c C-c', or with the next edit (depending
9044 on `org-remove-highlights-with-change'), this variable is emptied
9045 as well.")
9046 (make-variable-buffer-local 'org-occur-parameters)
9048 (defun org-occur (regexp &optional keep-previous callback)
9049 "Make a compact tree which shows all matches of REGEXP.
9050 The tree will show the lines where the regexp matches, and all higher
9051 headlines above the match. It will also show the heading after the match,
9052 to make sure editing the matching entry is easy.
9053 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
9054 call to `org-occur' will be kept, to allow stacking of calls to this
9055 command.
9056 If CALLBACK is non-nil, it is a function which is called to confirm
9057 that the match should indeed be shown."
9058 (interactive "sRegexp: \nP")
9059 (unless keep-previous
9060 (org-remove-occur-highlights nil nil t))
9061 (push (cons regexp callback) org-occur-parameters)
9062 (let ((cnt 0))
9063 (save-excursion
9064 (goto-char (point-min))
9065 (if (or (not keep-previous) ; do not want to keep
9066 (not org-occur-highlights)) ; no previous matches
9067 ;; hide everything
9068 (org-overview))
9069 (while (re-search-forward regexp nil t)
9070 (when (or (not callback)
9071 (save-match-data (funcall callback)))
9072 (setq cnt (1+ cnt))
9073 (when org-highlight-sparse-tree-matches
9074 (org-highlight-new-match (match-beginning 0) (match-end 0)))
9075 (org-show-context 'occur-tree))))
9076 (when org-remove-highlights-with-change
9077 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
9078 nil 'local))
9079 (unless org-sparse-tree-open-archived-trees
9080 (org-hide-archived-subtrees (point-min) (point-max)))
9081 (run-hooks 'org-occur-hook)
9082 (if (interactive-p)
9083 (message "%d match(es) for regexp %s" cnt regexp))
9084 cnt))
9086 (defun org-show-context (&optional key)
9087 "Make sure point and context and visible.
9088 How much context is shown depends upon the variables
9089 `org-show-hierarchy-above', `org-show-following-heading'. and
9090 `org-show-siblings'."
9091 (let ((heading-p (org-on-heading-p t))
9092 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
9093 (following-p (org-get-alist-option org-show-following-heading key))
9094 (entry-p (org-get-alist-option org-show-entry-below key))
9095 (siblings-p (org-get-alist-option org-show-siblings key)))
9096 (catch 'exit
9097 ;; Show heading or entry text
9098 (if (and heading-p (not entry-p))
9099 (org-flag-heading nil) ; only show the heading
9100 (and (or entry-p (org-invisible-p) (org-invisible-p2))
9101 (org-show-hidden-entry))) ; show entire entry
9102 (when following-p
9103 ;; Show next sibling, or heading below text
9104 (save-excursion
9105 (and (if heading-p (org-goto-sibling) (outline-next-heading))
9106 (org-flag-heading nil))))
9107 (when siblings-p (org-show-siblings))
9108 (when hierarchy-p
9109 ;; show all higher headings, possibly with siblings
9110 (save-excursion
9111 (while (and (condition-case nil
9112 (progn (org-up-heading-all 1) t)
9113 (error nil))
9114 (not (bobp)))
9115 (org-flag-heading nil)
9116 (when siblings-p (org-show-siblings))))))))
9118 (defun org-reveal (&optional siblings)
9119 "Show current entry, hierarchy above it, and the following headline.
9120 This can be used to show a consistent set of context around locations
9121 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
9122 not t for the search context.
9124 With optional argument SIBLINGS, on each level of the hierarchy all
9125 siblings are shown. This repairs the tree structure to what it would
9126 look like when opened with hierarchical calls to `org-cycle'."
9127 (interactive "P")
9128 (let ((org-show-hierarchy-above t)
9129 (org-show-following-heading t)
9130 (org-show-siblings (if siblings t org-show-siblings)))
9131 (org-show-context nil)))
9133 (defun org-highlight-new-match (beg end)
9134 "Highlight from BEG to END and mark the highlight is an occur headline."
9135 (let ((ov (org-make-overlay beg end)))
9136 (org-overlay-put ov 'face 'secondary-selection)
9137 (push ov org-occur-highlights)))
9139 (defun org-remove-occur-highlights (&optional beg end noremove)
9140 "Remove the occur highlights from the buffer.
9141 BEG and END are ignored. If NOREMOVE is nil, remove this function
9142 from the `before-change-functions' in the current buffer."
9143 (interactive)
9144 (unless org-inhibit-highlight-removal
9145 (mapc 'org-delete-overlay org-occur-highlights)
9146 (setq org-occur-highlights nil)
9147 (setq org-occur-parameters nil)
9148 (unless noremove
9149 (remove-hook 'before-change-functions
9150 'org-remove-occur-highlights 'local))))
9152 ;;;; Priorities
9154 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
9155 "Regular expression matching the priority indicator.")
9157 (defvar org-remove-priority-next-time nil)
9159 (defun org-priority-up ()
9160 "Increase the priority of the current item."
9161 (interactive)
9162 (org-priority 'up))
9164 (defun org-priority-down ()
9165 "Decrease the priority of the current item."
9166 (interactive)
9167 (org-priority 'down))
9169 (defun org-priority (&optional action)
9170 "Change the priority of an item by ARG.
9171 ACTION can be `set', `up', `down', or a character."
9172 (interactive)
9173 (setq action (or action 'set))
9174 (let (current new news have remove)
9175 (save-excursion
9176 (org-back-to-heading)
9177 (if (looking-at org-priority-regexp)
9178 (setq current (string-to-char (match-string 2))
9179 have t)
9180 (setq current org-default-priority))
9181 (cond
9182 ((or (eq action 'set) (integerp action))
9183 (if (integerp action)
9184 (setq new action)
9185 (message "Priority %c-%c, SPC to remove: " org-highest-priority org-lowest-priority)
9186 (setq new (read-char-exclusive)))
9187 (if (and (= (upcase org-highest-priority) org-highest-priority)
9188 (= (upcase org-lowest-priority) org-lowest-priority))
9189 (setq new (upcase new)))
9190 (cond ((equal new ?\ ) (setq remove t))
9191 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
9192 (error "Priority must be between `%c' and `%c'"
9193 org-highest-priority org-lowest-priority))))
9194 ((eq action 'up)
9195 (if (and (not have) (eq last-command this-command))
9196 (setq new org-lowest-priority)
9197 (setq new (if (and org-priority-start-cycle-with-default (not have))
9198 org-default-priority (1- current)))))
9199 ((eq action 'down)
9200 (if (and (not have) (eq last-command this-command))
9201 (setq new org-highest-priority)
9202 (setq new (if (and org-priority-start-cycle-with-default (not have))
9203 org-default-priority (1+ current)))))
9204 (t (error "Invalid action")))
9205 (if (or (< (upcase new) org-highest-priority)
9206 (> (upcase new) org-lowest-priority))
9207 (setq remove t))
9208 (setq news (format "%c" new))
9209 (if have
9210 (if remove
9211 (replace-match "" t t nil 1)
9212 (replace-match news t t nil 2))
9213 (if remove
9214 (error "No priority cookie found in line")
9215 (looking-at org-todo-line-regexp)
9216 (if (match-end 2)
9217 (progn
9218 (goto-char (match-end 2))
9219 (insert " [#" news "]"))
9220 (goto-char (match-beginning 3))
9221 (insert "[#" news "] ")))))
9222 (org-preserve-lc (org-set-tags nil 'align))
9223 (if remove
9224 (message "Priority removed")
9225 (message "Priority of current item set to %s" news))))
9228 (defun org-get-priority (s)
9229 "Find priority cookie and return priority."
9230 (save-match-data
9231 (if (not (string-match org-priority-regexp s))
9232 (* 1000 (- org-lowest-priority org-default-priority))
9233 (* 1000 (- org-lowest-priority
9234 (string-to-char (match-string 2 s)))))))
9236 ;;;; Tags
9238 (defun org-scan-tags (action matcher &optional todo-only)
9239 "Scan headline tags with inheritance and produce output ACTION.
9240 ACTION can be `sparse-tree' or `agenda'. MATCHER is a Lisp form to be
9241 evaluated, testing if a given set of tags qualifies a headline for
9242 inclusion. When TODO-ONLY is non-nil, only lines with a TODO keyword
9243 are included in the output."
9244 (let* ((re (concat "[\n\r]" outline-regexp " *\\(\\<\\("
9245 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
9246 (org-re
9247 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*$")))
9248 (props (list 'face nil
9249 'done-face 'org-done
9250 'undone-face nil
9251 'mouse-face 'highlight
9252 'org-not-done-regexp org-not-done-regexp
9253 'org-todo-regexp org-todo-regexp
9254 'keymap org-agenda-keymap
9255 'help-echo
9256 (format "mouse-2 or RET jump to org file %s"
9257 (abbreviate-file-name
9258 (or (buffer-file-name (buffer-base-buffer))
9259 (buffer-name (buffer-base-buffer)))))))
9260 (case-fold-search nil)
9261 lspos
9262 tags tags-list tags-alist (llast 0) rtn level category i txt
9263 todo marker entry priority)
9264 (save-excursion
9265 (goto-char (point-min))
9266 (when (eq action 'sparse-tree)
9267 (org-overview)
9268 (org-remove-occur-highlights))
9269 (while (re-search-forward re nil t)
9270 (catch :skip
9271 (setq todo (if (match-end 1) (match-string 2))
9272 tags (if (match-end 4) (match-string 4)))
9273 (goto-char (setq lspos (1+ (match-beginning 0))))
9274 (setq level (org-reduced-level (funcall outline-level))
9275 category (org-get-category))
9276 (setq i llast llast level)
9277 ;; remove tag lists from same and sublevels
9278 (while (>= i level)
9279 (when (setq entry (assoc i tags-alist))
9280 (setq tags-alist (delete entry tags-alist)))
9281 (setq i (1- i)))
9282 ;; add the next tags
9283 (when tags
9284 (setq tags (mapcar 'downcase (org-split-string tags ":"))
9285 tags-alist
9286 (cons (cons level tags) tags-alist)))
9287 ;; compile tags for current headline
9288 (setq tags-list
9289 (if org-use-tag-inheritance
9290 (apply 'append (mapcar 'cdr tags-alist))
9291 tags))
9292 (when (and tags org-use-tag-inheritance
9293 (not (eq t org-use-tag-inheritance)))
9294 ;; selective inheritance, remove uninherited ones
9295 (setcdr (car tags-alist)
9296 (org-remove-uniherited-tags (cdar tags-alist))))
9297 (when (and (or (not todo-only) (member todo org-not-done-keywords))
9298 (eval matcher)
9299 (or (not org-agenda-skip-archived-trees)
9300 (not (member org-archive-tag tags-list))))
9301 (and (eq action 'agenda) (org-agenda-skip))
9302 ;; list this headline
9304 (if (eq action 'sparse-tree)
9305 (progn
9306 (and org-highlight-sparse-tree-matches
9307 (org-get-heading) (match-end 0)
9308 (org-highlight-new-match
9309 (match-beginning 0) (match-beginning 1)))
9310 (org-show-context 'tags-tree))
9311 (setq txt (org-format-agenda-item
9313 (concat
9314 (if org-tags-match-list-sublevels
9315 (make-string (1- level) ?.) "")
9316 (org-get-heading))
9317 category tags-list)
9318 priority (org-get-priority txt))
9319 (goto-char lspos)
9320 (setq marker (org-agenda-new-marker))
9321 (org-add-props txt props
9322 'org-marker marker 'org-hd-marker marker 'org-category category
9323 'priority priority 'type "tagsmatch")
9324 (push txt rtn))
9325 ;; if we are to skip sublevels, jump to end of subtree
9326 (or org-tags-match-list-sublevels (org-end-of-subtree t))))))
9327 (when (and (eq action 'sparse-tree)
9328 (not org-sparse-tree-open-archived-trees))
9329 (org-hide-archived-subtrees (point-min) (point-max)))
9330 (nreverse rtn)))
9332 (defun org-remove-uniherited-tags (tags)
9333 "Remove all tags that are not inherited from the list TAGS."
9334 (cond
9335 ((eq org-use-tag-inheritance t) tags)
9336 ((not org-use-tag-inheritance) nil)
9337 ((stringp org-use-tag-inheritance)
9338 (delq nil (mapcar
9339 (lambda (x) (if (string-match org-use-tag-inheritance x) x nil))
9340 tags)))
9341 ((listp org-use-tag-inheritance)
9342 (org-delete-all org-use-tag-inheritance tags))))
9344 (defvar todo-only) ;; dynamically scoped
9346 (defun org-tags-sparse-tree (&optional todo-only match)
9347 "Create a sparse tree according to tags string MATCH.
9348 MATCH can contain positive and negative selection of tags, like
9349 \"+WORK+URGENT-WITHBOSS\".
9350 If optional argument TODO_ONLY is non-nil, only select lines that are
9351 also TODO lines."
9352 (interactive "P")
9353 (org-prepare-agenda-buffers (list (current-buffer)))
9354 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
9356 (defvar org-cached-props nil)
9357 (defun org-cached-entry-get (pom property)
9358 (if (or (eq t org-use-property-inheritance)
9359 (and (stringp org-use-property-inheritance)
9360 (string-match org-use-property-inheritance property))
9361 (and (listp org-use-property-inheritance)
9362 (member property org-use-property-inheritance)))
9363 ;; Caching is not possible, check it directly
9364 (org-entry-get pom property 'inherit)
9365 ;; Get all properties, so that we can do complicated checks easily
9366 (cdr (assoc property (or org-cached-props
9367 (setq org-cached-props
9368 (org-entry-properties pom)))))))
9370 (defun org-global-tags-completion-table (&optional files)
9371 "Return the list of all tags in all agenda buffer/files."
9372 (save-excursion
9373 (org-uniquify
9374 (delq nil
9375 (apply 'append
9376 (mapcar
9377 (lambda (file)
9378 (set-buffer (find-file-noselect file))
9379 (append (org-get-buffer-tags)
9380 (mapcar (lambda (x) (if (stringp (car-safe x))
9381 (list (car-safe x)) nil))
9382 org-tag-alist)))
9383 (if (and files (car files))
9384 files
9385 (org-agenda-files))))))))
9387 (defun org-make-tags-matcher (match)
9388 "Create the TAGS//TODO matcher form for the selection string MATCH."
9389 ;; todo-only is scoped dynamically into this function, and the function
9390 ;; may change it it the matcher asksk for it.
9391 (unless match
9392 ;; Get a new match request, with completion
9393 (let ((org-last-tags-completion-table
9394 (org-global-tags-completion-table)))
9395 (setq match (completing-read
9396 "Match: " 'org-tags-completion-function nil nil nil
9397 'org-tags-history))))
9399 ;; Parse the string and create a lisp form
9400 (let ((match0 match)
9401 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL=\\([0-9]+\\)\\|\\([[:alnum:]_]+\\)=\\({[^}]+}\\|\"[^\"]*\"\\)\\|[[:alnum:]_@]+\\)"))
9402 minus tag mm
9403 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
9404 orterms term orlist re-p level-p prop-p pn pv cat-p gv)
9405 (if (string-match "/+" match)
9406 ;; match contains also a todo-matching request
9407 (progn
9408 (setq tagsmatch (substring match 0 (match-beginning 0))
9409 todomatch (substring match (match-end 0)))
9410 (if (string-match "^!" todomatch)
9411 (setq todo-only t todomatch (substring todomatch 1)))
9412 (if (string-match "^\\s-*$" todomatch)
9413 (setq todomatch nil)))
9414 ;; only matching tags
9415 (setq tagsmatch match todomatch nil))
9417 ;; Make the tags matcher
9418 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
9419 (setq tagsmatcher t)
9420 (setq orterms (org-split-string tagsmatch "|") orlist nil)
9421 (while (setq term (pop orterms))
9422 (while (and (equal (substring term -1) "\\") orterms)
9423 (setq term (concat term "|" (pop orterms)))) ; repair bad split
9424 (while (string-match re term)
9425 (setq minus (and (match-end 1)
9426 (equal (match-string 1 term) "-"))
9427 tag (match-string 2 term)
9428 re-p (equal (string-to-char tag) ?{)
9429 level-p (match-end 3)
9430 prop-p (match-end 4)
9431 mm (cond
9432 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
9433 (level-p `(= level ,(string-to-number
9434 (match-string 3 term))))
9435 (prop-p
9436 (setq pn (match-string 4 term)
9437 pv (match-string 5 term)
9438 cat-p (equal pn "CATEGORY")
9439 re-p (equal (string-to-char pv) ?{)
9440 pv (substring pv 1 -1))
9441 (if (equal pn "CATEGORY")
9442 (setq gv '(get-text-property (point) 'org-category))
9443 (setq gv `(org-cached-entry-get nil ,pn)))
9444 (if re-p
9445 `(string-match ,pv (or ,gv ""))
9446 `(equal ,pv (or ,gv ""))))
9447 (t `(member ,(downcase tag) tags-list)))
9448 mm (if minus (list 'not mm) mm)
9449 term (substring term (match-end 0)))
9450 (push mm tagsmatcher))
9451 (push (if (> (length tagsmatcher) 1)
9452 (cons 'and tagsmatcher)
9453 (car tagsmatcher))
9454 orlist)
9455 (setq tagsmatcher nil))
9456 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
9457 (setq tagsmatcher
9458 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
9460 ;; Make the todo matcher
9461 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
9462 (setq todomatcher t)
9463 (setq orterms (org-split-string todomatch "|") orlist nil)
9464 (while (setq term (pop orterms))
9465 (while (string-match re term)
9466 (setq minus (and (match-end 1)
9467 (equal (match-string 1 term) "-"))
9468 kwd (match-string 2 term)
9469 re-p (equal (string-to-char kwd) ?{)
9470 term (substring term (match-end 0))
9471 mm (if re-p
9472 `(string-match ,(substring kwd 1 -1) todo)
9473 (list 'equal 'todo kwd))
9474 mm (if minus (list 'not mm) mm))
9475 (push mm todomatcher))
9476 (push (if (> (length todomatcher) 1)
9477 (cons 'and todomatcher)
9478 (car todomatcher))
9479 orlist)
9480 (setq todomatcher nil))
9481 (setq todomatcher (if (> (length orlist) 1)
9482 (cons 'or orlist) (car orlist))))
9484 ;; Return the string and lisp forms of the matcher
9485 (setq matcher (if todomatcher
9486 (list 'and tagsmatcher todomatcher)
9487 tagsmatcher))
9488 (cons match0 matcher)))
9490 (defun org-match-any-p (re list)
9491 "Does re match any element of list?"
9492 (setq list (mapcar (lambda (x) (string-match re x)) list))
9493 (delq nil list))
9495 (defvar org-add-colon-after-tag-completion nil) ;; dynamically skoped param
9496 (defvar org-tags-overlay (org-make-overlay 1 1))
9497 (org-detach-overlay org-tags-overlay)
9499 (defun org-align-tags-here (to-col)
9500 ;; Assumes that this is a headline
9501 (let ((pos (point)) (col (current-column)) tags)
9502 (beginning-of-line 1)
9503 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
9504 (< pos (match-beginning 2)))
9505 (progn
9506 (setq tags (match-string 2))
9507 (goto-char (match-beginning 1))
9508 (insert " ")
9509 (delete-region (point) (1+ (match-end 0)))
9510 (backward-char 1)
9511 (move-to-column
9512 (max (1+ (current-column))
9513 (1+ col)
9514 (if (> to-col 0)
9515 to-col
9516 (- (abs to-col) (length tags))))
9518 (insert tags)
9519 (move-to-column (min (current-column) col) t))
9520 (goto-char pos))))
9522 (defun org-set-tags (&optional arg just-align)
9523 "Set the tags for the current headline.
9524 With prefix ARG, realign all tags in headings in the current buffer."
9525 (interactive "P")
9526 (let* ((re (concat "^" outline-regexp))
9527 (current (org-get-tags-string))
9528 (col (current-column))
9529 (org-setting-tags t)
9530 table current-tags inherited-tags ; computed below when needed
9531 tags p0 c0 c1 rpl)
9532 (if arg
9533 (save-excursion
9534 (goto-char (point-min))
9535 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
9536 (while (re-search-forward re nil t)
9537 (org-set-tags nil t)
9538 (end-of-line 1)))
9539 (message "All tags realigned to column %d" org-tags-column))
9540 (if just-align
9541 (setq tags current)
9542 ;; Get a new set of tags from the user
9543 (save-excursion
9544 (setq table (or org-tag-alist (org-get-buffer-tags))
9545 org-last-tags-completion-table table
9546 current-tags (org-split-string current ":")
9547 inherited-tags (nreverse
9548 (nthcdr (length current-tags)
9549 (nreverse (org-get-tags-at))))
9550 tags
9551 (if (or (eq t org-use-fast-tag-selection)
9552 (and org-use-fast-tag-selection
9553 (delq nil (mapcar 'cdr table))))
9554 (org-fast-tag-selection
9555 current-tags inherited-tags table
9556 (if org-fast-tag-selection-include-todo org-todo-key-alist))
9557 (let ((org-add-colon-after-tag-completion t))
9558 (org-trim
9559 (org-without-partial-completion
9560 (completing-read "Tags: " 'org-tags-completion-function
9561 nil nil current 'org-tags-history)))))))
9562 (while (string-match "[-+&]+" tags)
9563 ;; No boolean logic, just a list
9564 (setq tags (replace-match ":" t t tags))))
9566 (if (string-match "\\`[\t ]*\\'" tags)
9567 (setq tags "")
9568 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
9569 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
9571 ;; Insert new tags at the correct column
9572 (beginning-of-line 1)
9573 (cond
9574 ((and (equal current "") (equal tags "")))
9575 ((re-search-forward
9576 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
9577 (point-at-eol) t)
9578 (if (equal tags "")
9579 (setq rpl "")
9580 (goto-char (match-beginning 0))
9581 (setq c0 (current-column) p0 (point)
9582 c1 (max (1+ c0) (if (> org-tags-column 0)
9583 org-tags-column
9584 (- (- org-tags-column) (length tags))))
9585 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
9586 (replace-match rpl t t)
9587 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
9588 tags)
9589 (t (error "Tags alignment failed")))
9590 (move-to-column col)
9591 (unless just-align
9592 (run-hooks 'org-after-tags-change-hook)))))
9594 (defun org-change-tag-in-region (beg end tag off)
9595 "Add or remove TAG for each entry in the region.
9596 This works in the agenda, and also in an org-mode buffer."
9597 (interactive
9598 (list (region-beginning) (region-end)
9599 (let ((org-last-tags-completion-table
9600 (if (org-mode-p)
9601 (org-get-buffer-tags)
9602 (org-global-tags-completion-table))))
9603 (completing-read
9604 "Tag: " 'org-tags-completion-function nil nil nil
9605 'org-tags-history))
9606 (progn
9607 (message "[s]et or [r]emove? ")
9608 (equal (read-char-exclusive) ?r))))
9609 (if (fboundp 'deactivate-mark) (deactivate-mark))
9610 (let ((agendap (equal major-mode 'org-agenda-mode))
9611 l1 l2 m buf pos newhead (cnt 0))
9612 (goto-char end)
9613 (setq l2 (1- (org-current-line)))
9614 (goto-char beg)
9615 (setq l1 (org-current-line))
9616 (loop for l from l1 to l2 do
9617 (goto-line l)
9618 (setq m (get-text-property (point) 'org-hd-marker))
9619 (when (or (and (org-mode-p) (org-on-heading-p))
9620 (and agendap m))
9621 (setq buf (if agendap (marker-buffer m) (current-buffer))
9622 pos (if agendap m (point)))
9623 (with-current-buffer buf
9624 (save-excursion
9625 (save-restriction
9626 (goto-char pos)
9627 (setq cnt (1+ cnt))
9628 (org-toggle-tag tag (if off 'off 'on))
9629 (setq newhead (org-get-heading)))))
9630 (and agendap (org-agenda-change-all-lines newhead m))))
9631 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
9633 (defun org-tags-completion-function (string predicate &optional flag)
9634 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
9635 (confirm (lambda (x) (stringp (car x)))))
9636 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
9637 (setq s1 (match-string 1 string)
9638 s2 (match-string 2 string))
9639 (setq s1 "" s2 string))
9640 (cond
9641 ((eq flag nil)
9642 ;; try completion
9643 (setq rtn (try-completion s2 ctable confirm))
9644 (if (stringp rtn)
9645 (setq rtn
9646 (concat s1 s2 (substring rtn (length s2))
9647 (if (and org-add-colon-after-tag-completion
9648 (assoc rtn ctable))
9649 ":" ""))))
9650 rtn)
9651 ((eq flag t)
9652 ;; all-completions
9653 (all-completions s2 ctable confirm)
9655 ((eq flag 'lambda)
9656 ;; exact match?
9657 (assoc s2 ctable)))
9660 (defun org-fast-tag-insert (kwd tags face &optional end)
9661 "Insert KDW, and the TAGS, the latter with face FACE. Also inser END."
9662 (insert (format "%-12s" (concat kwd ":"))
9663 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
9664 (or end "")))
9666 (defun org-fast-tag-show-exit (flag)
9667 (save-excursion
9668 (goto-line 3)
9669 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
9670 (replace-match ""))
9671 (when flag
9672 (end-of-line 1)
9673 (move-to-column (- (window-width) 19) t)
9674 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
9676 (defun org-set-current-tags-overlay (current prefix)
9677 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
9678 (if (featurep 'xemacs)
9679 (org-overlay-display org-tags-overlay (concat prefix s)
9680 'secondary-selection)
9681 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
9682 (org-overlay-display org-tags-overlay (concat prefix s)))))
9684 (defun org-fast-tag-selection (current inherited table &optional todo-table)
9685 "Fast tag selection with single keys.
9686 CURRENT is the current list of tags in the headline, INHERITED is the
9687 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
9688 possibly with grouping information. TODO-TABLE is a similar table with
9689 TODO keywords, should these have keys assigned to them.
9690 If the keys are nil, a-z are automatically assigned.
9691 Returns the new tags string, or nil to not change the current settings."
9692 (let* ((fulltable (append table todo-table))
9693 (maxlen (apply 'max (mapcar
9694 (lambda (x)
9695 (if (stringp (car x)) (string-width (car x)) 0))
9696 fulltable)))
9697 (buf (current-buffer))
9698 (expert (eq org-fast-tag-selection-single-key 'expert))
9699 (buffer-tags nil)
9700 (fwidth (+ maxlen 3 1 3))
9701 (ncol (/ (- (window-width) 4) fwidth))
9702 (i-face 'org-done)
9703 (c-face 'org-todo)
9704 tg cnt e c char c1 c2 ntable tbl rtn
9705 ov-start ov-end ov-prefix
9706 (exit-after-next org-fast-tag-selection-single-key)
9707 (done-keywords org-done-keywords)
9708 groups ingroup)
9709 (save-excursion
9710 (beginning-of-line 1)
9711 (if (looking-at
9712 (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
9713 (setq ov-start (match-beginning 1)
9714 ov-end (match-end 1)
9715 ov-prefix "")
9716 (setq ov-start (1- (point-at-eol))
9717 ov-end (1+ ov-start))
9718 (skip-chars-forward "^\n\r")
9719 (setq ov-prefix
9720 (concat
9721 (buffer-substring (1- (point)) (point))
9722 (if (> (current-column) org-tags-column)
9724 (make-string (- org-tags-column (current-column)) ?\ ))))))
9725 (org-move-overlay org-tags-overlay ov-start ov-end)
9726 (save-window-excursion
9727 (if expert
9728 (set-buffer (get-buffer-create " *Org tags*"))
9729 (delete-other-windows)
9730 (split-window-vertically)
9731 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
9732 (erase-buffer)
9733 (org-set-local 'org-done-keywords done-keywords)
9734 (org-fast-tag-insert "Inherited" inherited i-face "\n")
9735 (org-fast-tag-insert "Current" current c-face "\n\n")
9736 (org-fast-tag-show-exit exit-after-next)
9737 (org-set-current-tags-overlay current ov-prefix)
9738 (setq tbl fulltable char ?a cnt 0)
9739 (while (setq e (pop tbl))
9740 (cond
9741 ((equal e '(:startgroup))
9742 (push '() groups) (setq ingroup t)
9743 (when (not (= cnt 0))
9744 (setq cnt 0)
9745 (insert "\n"))
9746 (insert "{ "))
9747 ((equal e '(:endgroup))
9748 (setq ingroup nil cnt 0)
9749 (insert "}\n"))
9751 (setq tg (car e) c2 nil)
9752 (if (cdr e)
9753 (setq c (cdr e))
9754 ;; automatically assign a character.
9755 (setq c1 (string-to-char
9756 (downcase (substring
9757 tg (if (= (string-to-char tg) ?@) 1 0)))))
9758 (if (or (rassoc c1 ntable) (rassoc c1 table))
9759 (while (or (rassoc char ntable) (rassoc char table))
9760 (setq char (1+ char)))
9761 (setq c2 c1))
9762 (setq c (or c2 char)))
9763 (if ingroup (push tg (car groups)))
9764 (setq tg (org-add-props tg nil 'face
9765 (cond
9766 ((not (assoc tg table))
9767 (org-get-todo-face tg))
9768 ((member tg current) c-face)
9769 ((member tg inherited) i-face)
9770 (t nil))))
9771 (if (and (= cnt 0) (not ingroup)) (insert " "))
9772 (insert "[" c "] " tg (make-string
9773 (- fwidth 4 (length tg)) ?\ ))
9774 (push (cons tg c) ntable)
9775 (when (= (setq cnt (1+ cnt)) ncol)
9776 (insert "\n")
9777 (if ingroup (insert " "))
9778 (setq cnt 0)))))
9779 (setq ntable (nreverse ntable))
9780 (insert "\n")
9781 (goto-char (point-min))
9782 (if (and (not expert) (fboundp 'fit-window-to-buffer))
9783 (fit-window-to-buffer))
9784 (setq rtn
9785 (catch 'exit
9786 (while t
9787 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free%s%s"
9788 (if groups " [!] no groups" " [!]groups")
9789 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
9790 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
9791 (cond
9792 ((= c ?\r) (throw 'exit t))
9793 ((= c ?!)
9794 (setq groups (not groups))
9795 (goto-char (point-min))
9796 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
9797 ((= c ?\C-c)
9798 (if (not expert)
9799 (org-fast-tag-show-exit
9800 (setq exit-after-next (not exit-after-next)))
9801 (setq expert nil)
9802 (delete-other-windows)
9803 (split-window-vertically)
9804 (org-switch-to-buffer-other-window " *Org tags*")
9805 (and (fboundp 'fit-window-to-buffer)
9806 (fit-window-to-buffer))))
9807 ((or (= c ?\C-g)
9808 (and (= c ?q) (not (rassoc c ntable))))
9809 (org-detach-overlay org-tags-overlay)
9810 (setq quit-flag t))
9811 ((= c ?\ )
9812 (setq current nil)
9813 (if exit-after-next (setq exit-after-next 'now)))
9814 ((= c ?\t)
9815 (condition-case nil
9816 (setq tg (completing-read
9817 "Tag: "
9818 (or buffer-tags
9819 (with-current-buffer buf
9820 (org-get-buffer-tags)))))
9821 (quit (setq tg "")))
9822 (when (string-match "\\S-" tg)
9823 (add-to-list 'buffer-tags (list tg))
9824 (if (member tg current)
9825 (setq current (delete tg current))
9826 (push tg current)))
9827 (if exit-after-next (setq exit-after-next 'now)))
9828 ((setq e (rassoc c todo-table) tg (car e))
9829 (with-current-buffer buf
9830 (save-excursion (org-todo tg)))
9831 (if exit-after-next (setq exit-after-next 'now)))
9832 ((setq e (rassoc c ntable) tg (car e))
9833 (if (member tg current)
9834 (setq current (delete tg current))
9835 (loop for g in groups do
9836 (if (member tg g)
9837 (mapc (lambda (x)
9838 (setq current (delete x current)))
9839 g)))
9840 (push tg current))
9841 (if exit-after-next (setq exit-after-next 'now))))
9843 ;; Create a sorted list
9844 (setq current
9845 (sort current
9846 (lambda (a b)
9847 (assoc b (cdr (memq (assoc a ntable) ntable))))))
9848 (if (eq exit-after-next 'now) (throw 'exit t))
9849 (goto-char (point-min))
9850 (beginning-of-line 2)
9851 (delete-region (point) (point-at-eol))
9852 (org-fast-tag-insert "Current" current c-face)
9853 (org-set-current-tags-overlay current ov-prefix)
9854 (while (re-search-forward
9855 (org-re "\\[.\\] \\([[:alnum:]_@]+\\)") nil t)
9856 (setq tg (match-string 1))
9857 (add-text-properties
9858 (match-beginning 1) (match-end 1)
9859 (list 'face
9860 (cond
9861 ((member tg current) c-face)
9862 ((member tg inherited) i-face)
9863 (t (get-text-property (match-beginning 1) 'face))))))
9864 (goto-char (point-min)))))
9865 (org-detach-overlay org-tags-overlay)
9866 (if rtn
9867 (mapconcat 'identity current ":")
9868 nil))))
9870 (defun org-get-tags-string ()
9871 "Get the TAGS string in the current headline."
9872 (unless (org-on-heading-p t)
9873 (error "Not on a heading"))
9874 (save-excursion
9875 (beginning-of-line 1)
9876 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
9877 (org-match-string-no-properties 1)
9878 "")))
9880 (defun org-get-tags ()
9881 "Get the list of tags specified in the current headline."
9882 (org-split-string (org-get-tags-string) ":"))
9884 (defun org-get-buffer-tags ()
9885 "Get a table of all tags used in the buffer, for completion."
9886 (let (tags)
9887 (save-excursion
9888 (goto-char (point-min))
9889 (while (re-search-forward
9890 (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t\r\n]") nil t)
9891 (when (equal (char-after (point-at-bol 0)) ?*)
9892 (mapc (lambda (x) (add-to-list 'tags x))
9893 (org-split-string (org-match-string-no-properties 1) ":")))))
9894 (mapcar 'list tags)))
9897 ;;;; Properties
9899 ;;; Setting and retrieving properties
9901 (defconst org-special-properties
9902 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "PRIORITY"
9903 "TIMESTAMP" "TIMESTAMP_IA")
9904 "The special properties valid in Org-mode.
9906 These are properties that are not defined in the property drawer,
9907 but in some other way.")
9909 (defconst org-default-properties
9910 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION"
9911 "LOCATION" "LOGGING" "COLUMNS")
9912 "Some properties that are used by Org-mode for various purposes.
9913 Being in this list makes sure that they are offered for completion.")
9915 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
9916 "Regular expression matching the first line of a property drawer.")
9918 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
9919 "Regular expression matching the first line of a property drawer.")
9921 (defun org-property-action ()
9922 "Do an action on properties."
9923 (interactive)
9924 (let (c)
9925 (org-at-property-p)
9926 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
9927 (setq c (read-char-exclusive))
9928 (cond
9929 ((equal c ?s)
9930 (call-interactively 'org-set-property))
9931 ((equal c ?d)
9932 (call-interactively 'org-delete-property))
9933 ((equal c ?D)
9934 (call-interactively 'org-delete-property-globally))
9935 ((equal c ?c)
9936 (call-interactively 'org-compute-property-at-point))
9937 (t (error "No such property action %c" c)))))
9939 (defun org-at-property-p ()
9940 "Is the cursor in a property line?"
9941 ;; FIXME: Does not check if we are actually in the drawer.
9942 ;; FIXME: also returns true on any drawers.....
9943 ;; This is used by C-c C-c for property action.
9944 (save-excursion
9945 (beginning-of-line 1)
9946 (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))))
9948 (defun org-get-property-block (&optional beg end force)
9949 "Return the (beg . end) range of the body of the property drawer.
9950 BEG and END can be beginning and end of subtree, if not given
9951 they will be found.
9952 If the drawer does not exist and FORCE is non-nil, create the drawer."
9953 (catch 'exit
9954 (save-excursion
9955 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
9956 (end (or end (progn (outline-next-heading) (point)))))
9957 (goto-char beg)
9958 (if (re-search-forward org-property-start-re end t)
9959 (setq beg (1+ (match-end 0)))
9960 (if force
9961 (save-excursion
9962 (org-insert-property-drawer)
9963 (setq end (progn (outline-next-heading) (point))))
9964 (throw 'exit nil))
9965 (goto-char beg)
9966 (if (re-search-forward org-property-start-re end t)
9967 (setq beg (1+ (match-end 0)))))
9968 (if (re-search-forward org-property-end-re end t)
9969 (setq end (match-beginning 0))
9970 (or force (throw 'exit nil))
9971 (goto-char beg)
9972 (setq end beg)
9973 (org-indent-line-function)
9974 (insert ":END:\n"))
9975 (cons beg end)))))
9977 (defun org-entry-properties (&optional pom which)
9978 "Get all properties of the entry at point-or-marker POM.
9979 This includes the TODO keyword, the tags, time strings for deadline,
9980 scheduled, and clocking, and any additional properties defined in the
9981 entry. The return value is an alist, keys may occur multiple times
9982 if the property key was used several times.
9983 POM may also be nil, in which case the current entry is used.
9984 If WHICH is nil or `all', get all properties. If WHICH is
9985 `special' or `standard', only get that subclass."
9986 (setq which (or which 'all))
9987 (org-with-point-at pom
9988 (let ((clockstr (substring org-clock-string 0 -1))
9989 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY"))
9990 beg end range props sum-props key value string clocksum)
9991 (save-excursion
9992 (when (condition-case nil (org-back-to-heading t) (error nil))
9993 (setq beg (point))
9994 (setq sum-props (get-text-property (point) 'org-summaries))
9995 (setq clocksum (get-text-property (point) :org-clock-minutes))
9996 (outline-next-heading)
9997 (setq end (point))
9998 (when (memq which '(all special))
9999 ;; Get the special properties, like TODO and tags
10000 (goto-char beg)
10001 (when (and (looking-at org-todo-line-regexp) (match-end 2))
10002 (push (cons "TODO" (org-match-string-no-properties 2)) props))
10003 (when (looking-at org-priority-regexp)
10004 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
10005 (when (and (setq value (org-get-tags-string))
10006 (string-match "\\S-" value))
10007 (push (cons "TAGS" value) props))
10008 (when (setq value (org-get-tags-at))
10009 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":") ":"))
10010 props))
10011 (while (re-search-forward org-maybe-keyword-time-regexp end t)
10012 (setq key (if (match-end 1) (substring (org-match-string-no-properties 1) 0 -1))
10013 string (if (equal key clockstr)
10014 (org-no-properties
10015 (org-trim
10016 (buffer-substring
10017 (match-beginning 3) (goto-char (point-at-eol)))))
10018 (substring (org-match-string-no-properties 3) 1 -1)))
10019 (unless key
10020 (if (= (char-after (match-beginning 3)) ?\[)
10021 (setq key "TIMESTAMP_IA")
10022 (setq key "TIMESTAMP")))
10023 (when (or (equal key clockstr) (not (assoc key props)))
10024 (push (cons key string) props)))
10028 (when (memq which '(all standard))
10029 ;; Get the standard properties, like :PORP: ...
10030 (setq range (org-get-property-block beg end))
10031 (when range
10032 (goto-char (car range))
10033 (while (re-search-forward
10034 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
10035 (cdr range) t)
10036 (setq key (org-match-string-no-properties 1)
10037 value (org-trim (or (org-match-string-no-properties 2) "")))
10038 (unless (member key excluded)
10039 (push (cons key (or value "")) props)))))
10040 (if clocksum
10041 (push (cons "CLOCKSUM"
10042 (org-column-number-to-string (/ (float clocksum) 60.)
10043 'add_times))
10044 props))
10045 (append sum-props (nreverse props)))))))
10047 (defun org-entry-get (pom property &optional inherit)
10048 "Get value of PROPERTY for entry at point-or-marker POM.
10049 If INHERIT is non-nil and the entry does not have the property,
10050 then also check higher levels of the hierarchy.
10051 If INHERIT is the symbol `selective', use inheritance only if the setting
10052 in `org-use-property-inheritance' selects PROPERTY for inheritance.
10053 If the property is present but empty, the return value is the empty string.
10054 If the property is not present at all, nil is returned."
10055 (org-with-point-at pom
10056 (if (and inherit (if (eq inherit 'selective)
10057 (org-property-inherit-p property)
10059 (org-entry-get-with-inheritance property)
10060 (if (member property org-special-properties)
10061 ;; We need a special property. Use brute force, get all properties.
10062 (cdr (assoc property (org-entry-properties nil 'special)))
10063 (let ((range (org-get-property-block)))
10064 (if (and range
10065 (goto-char (car range))
10066 (re-search-forward
10067 (concat "^[ \t]*:" property ":[ \t]*\\(.*\\S-\\)?")
10068 (cdr range) t))
10069 ;; Found the property, return it.
10070 (if (match-end 1)
10071 (org-match-string-no-properties 1)
10072 "")))))))
10074 (defun org-entry-delete (pom property)
10075 "Delete the property PROPERTY from entry at point-or-marker POM."
10076 (org-with-point-at pom
10077 (if (member property org-special-properties)
10078 nil ; cannot delete these properties.
10079 (let ((range (org-get-property-block)))
10080 (if (and range
10081 (goto-char (car range))
10082 (re-search-forward
10083 (concat "^[ \t]*:" property ":[ \t]*\\(.*\\S-\\)")
10084 (cdr range) t))
10085 (progn
10086 (delete-region (match-beginning 0) (1+ (point-at-eol)))
10088 nil)))))
10090 ;; Multi-values properties are properties that contain multiple values
10091 ;; These values are assumed to be single words, separated by whitespace.
10092 (defun org-entry-add-to-multivalued-property (pom property value)
10093 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
10094 (let* ((old (org-entry-get pom property))
10095 (values (and old (org-split-string old "[ \t]"))))
10096 (unless (member value values)
10097 (setq values (cons value values))
10098 (org-entry-put pom property
10099 (mapconcat 'identity values " ")))))
10101 (defun org-entry-remove-from-multivalued-property (pom property value)
10102 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
10103 (let* ((old (org-entry-get pom property))
10104 (values (and old (org-split-string old "[ \t]"))))
10105 (when (member value values)
10106 (setq values (delete value values))
10107 (org-entry-put pom property
10108 (mapconcat 'identity values " ")))))
10110 (defun org-entry-member-in-multivalued-property (pom property value)
10111 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
10112 (let* ((old (org-entry-get pom property))
10113 (values (and old (org-split-string old "[ \t]"))))
10114 (member value values)))
10116 (defvar org-entry-property-inherited-from (make-marker))
10118 (defun org-entry-get-with-inheritance (property)
10119 "Get entry property, and search higher levels if not present."
10120 (let (tmp)
10121 (save-excursion
10122 (save-restriction
10123 (widen)
10124 (catch 'ex
10125 (while t
10126 (when (setq tmp (org-entry-get nil property))
10127 (org-back-to-heading t)
10128 (move-marker org-entry-property-inherited-from (point))
10129 (throw 'ex tmp))
10130 (or (org-up-heading-safe) (throw 'ex nil)))))
10131 (or tmp (cdr (assoc property org-local-properties))
10132 (cdr (assoc property org-global-properties))))))
10134 (defun org-entry-put (pom property value)
10135 "Set PROPERTY to VALUE for entry at point-or-marker POM."
10136 (org-with-point-at pom
10137 (org-back-to-heading t)
10138 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
10139 range)
10140 (cond
10141 ((equal property "TODO")
10142 (when (and (stringp value) (string-match "\\S-" value)
10143 (not (member value org-todo-keywords-1)))
10144 (error "\"%s\" is not a valid TODO state" value))
10145 (if (or (not value)
10146 (not (string-match "\\S-" value)))
10147 (setq value 'none))
10148 (org-todo value)
10149 (org-set-tags nil 'align))
10150 ((equal property "PRIORITY")
10151 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
10152 (string-to-char value) ?\ ))
10153 (org-set-tags nil 'align))
10154 ((equal property "SCHEDULED")
10155 (if (re-search-forward org-scheduled-time-regexp end t)
10156 (cond
10157 ((eq value 'earlier) (org-timestamp-change -1 'day))
10158 ((eq value 'later) (org-timestamp-change 1 'day))
10159 (t (call-interactively 'org-schedule)))
10160 (call-interactively 'org-schedule)))
10161 ((equal property "DEADLINE")
10162 (if (re-search-forward org-deadline-time-regexp end t)
10163 (cond
10164 ((eq value 'earlier) (org-timestamp-change -1 'day))
10165 ((eq value 'later) (org-timestamp-change 1 'day))
10166 (t (call-interactively 'org-deadline)))
10167 (call-interactively 'org-deadline)))
10168 ((member property org-special-properties)
10169 (error "The %s property can not yet be set with `org-entry-put'"
10170 property))
10171 (t ; a non-special property
10172 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
10173 (setq range (org-get-property-block beg end 'force))
10174 (goto-char (car range))
10175 (if (re-search-forward
10176 (concat "^[ \t]*:" property ":\\(.*\\)") (cdr range) t)
10177 (progn
10178 (delete-region (match-beginning 1) (match-end 1))
10179 (goto-char (match-beginning 1)))
10180 (goto-char (cdr range))
10181 (insert "\n")
10182 (backward-char 1)
10183 (org-indent-line-function)
10184 (insert ":" property ":"))
10185 (and value (insert " " value))
10186 (org-indent-line-function)))))))
10188 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
10189 "Get all property keys in the current buffer.
10190 With INCLUDE-SPECIALS, also list the special properties that relect things
10191 like tags and TODO state.
10192 With INCLUDE-DEFAULTS, also include properties that has special meaning
10193 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING.
10194 With INCLUDE-COLUMNS, also include property names given in COLUMN
10195 formats in the current buffer."
10196 (let (rtn range cfmt cols s p)
10197 (save-excursion
10198 (save-restriction
10199 (widen)
10200 (goto-char (point-min))
10201 (while (re-search-forward org-property-start-re nil t)
10202 (setq range (org-get-property-block))
10203 (goto-char (car range))
10204 (while (re-search-forward
10205 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
10206 (cdr range) t)
10207 (add-to-list 'rtn (org-match-string-no-properties 1)))
10208 (outline-next-heading))))
10210 (when include-specials
10211 (setq rtn (append org-special-properties rtn)))
10213 (when include-defaults
10214 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties))
10216 (when include-columns
10217 (save-excursion
10218 (save-restriction
10219 (widen)
10220 (goto-char (point-min))
10221 (while (re-search-forward
10222 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
10223 nil t)
10224 (setq cfmt (match-string 2) s 0)
10225 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
10226 cfmt s)
10227 (setq s (match-end 0)
10228 p (match-string 1 cfmt))
10229 (unless (or (equal p "ITEM")
10230 (member p org-special-properties))
10231 (add-to-list 'rtn (match-string 1 cfmt))))))))
10233 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
10235 (defun org-property-values (key)
10236 "Return a list of all values of property KEY."
10237 (save-excursion
10238 (save-restriction
10239 (widen)
10240 (goto-char (point-min))
10241 (let ((re (concat "^[ \t]*:" key ":[ \t]*\\(\\S-.*\\)"))
10242 values)
10243 (while (re-search-forward re nil t)
10244 (add-to-list 'values (org-trim (match-string 1))))
10245 (delete "" values)))))
10247 (defun org-insert-property-drawer ()
10248 "Insert a property drawer into the current entry."
10249 (interactive)
10250 (org-back-to-heading t)
10251 (looking-at outline-regexp)
10252 (let ((indent (- (match-end 0)(match-beginning 0)))
10253 (beg (point))
10254 (re (concat "^[ \t]*" org-keyword-time-regexp))
10255 end hiddenp)
10256 (outline-next-heading)
10257 (setq end (point))
10258 (goto-char beg)
10259 (while (re-search-forward re end t))
10260 (setq hiddenp (org-invisible-p))
10261 (end-of-line 1)
10262 (and (equal (char-after) ?\n) (forward-char 1))
10263 (org-skip-over-state-notes)
10264 (skip-chars-backward " \t\n\r")
10265 (if (eq (char-before) ?*) (forward-char 1))
10266 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
10267 (beginning-of-line 0)
10268 (indent-to-column indent)
10269 (beginning-of-line 2)
10270 (indent-to-column indent)
10271 (beginning-of-line 0)
10272 (if hiddenp
10273 (save-excursion
10274 (org-back-to-heading t)
10275 (hide-entry))
10276 (org-flag-drawer t))))
10278 (defun org-set-property (property value)
10279 "In the current entry, set PROPERTY to VALUE.
10280 When called interactively, this will prompt for a property name, offering
10281 completion on existing and default properties. And then it will prompt
10282 for a value, offering competion either on allowed values (via an inherited
10283 xxx_ALL property) or on existing values in other instances of this property
10284 in the current file."
10285 (interactive
10286 (let* ((prop (completing-read
10287 "Property: " (mapcar 'list (org-buffer-property-keys nil t t))))
10288 (cur (org-entry-get nil prop))
10289 (allowed (org-property-get-allowed-values nil prop 'table))
10290 (existing (mapcar 'list (org-property-values prop)))
10291 (val (if allowed
10292 (completing-read "Value: " allowed nil 'req-match)
10293 (completing-read
10294 (concat "Value" (if (and cur (string-match "\\S-" cur))
10295 (concat "[" cur "]") "")
10296 ": ")
10297 existing nil nil "" nil cur))))
10298 (list prop (if (equal val "") cur val))))
10299 (unless (equal (org-entry-get nil property) value)
10300 (org-entry-put nil property value)))
10302 (defun org-delete-property (property)
10303 "In the current entry, delete PROPERTY."
10304 (interactive
10305 (let* ((prop (completing-read
10306 "Property: " (org-entry-properties nil 'standard))))
10307 (list prop)))
10308 (message "Property %s %s" property
10309 (if (org-entry-delete nil property)
10310 "deleted"
10311 "was not present in the entry")))
10313 (defun org-delete-property-globally (property)
10314 "Remove PROPERTY globally, from all entries."
10315 (interactive
10316 (let* ((prop (completing-read
10317 "Globally remove property: "
10318 (mapcar 'list (org-buffer-property-keys)))))
10319 (list prop)))
10320 (save-excursion
10321 (save-restriction
10322 (widen)
10323 (goto-char (point-min))
10324 (let ((cnt 0))
10325 (while (re-search-forward
10326 (concat "^[ \t]*:" (regexp-quote property) ":.*\n?")
10327 nil t)
10328 (setq cnt (1+ cnt))
10329 (replace-match ""))
10330 (message "Property \"%s\" removed from %d entries" property cnt)))))
10332 (defvar org-columns-current-fmt-compiled) ; defined below
10334 (defun org-compute-property-at-point ()
10335 "Compute the property at point.
10336 This looks for an enclosing column format, extracts the operator and
10337 then applies it to the proerty in the column format's scope."
10338 (interactive)
10339 (unless (org-at-property-p)
10340 (error "Not at a property"))
10341 (let ((prop (org-match-string-no-properties 2)))
10342 (org-columns-get-format-and-top-level)
10343 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
10344 (error "No operator defined for property %s" prop))
10345 (org-columns-compute prop)))
10347 (defun org-property-get-allowed-values (pom property &optional table)
10348 "Get allowed values for the property PROPERTY.
10349 When TABLE is non-nil, return an alist that can directly be used for
10350 completion."
10351 (let (vals)
10352 (cond
10353 ((equal property "TODO")
10354 (setq vals (org-with-point-at pom
10355 (append org-todo-keywords-1 '("")))))
10356 ((equal property "PRIORITY")
10357 (let ((n org-lowest-priority))
10358 (while (>= n org-highest-priority)
10359 (push (char-to-string n) vals)
10360 (setq n (1- n)))))
10361 ((member property org-special-properties))
10363 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
10365 (when (and vals (string-match "\\S-" vals))
10366 (setq vals (car (read-from-string (concat "(" vals ")"))))
10367 (setq vals (mapcar (lambda (x)
10368 (cond ((stringp x) x)
10369 ((numberp x) (number-to-string x))
10370 ((symbolp x) (symbol-name x))
10371 (t "???")))
10372 vals)))))
10373 (if table (mapcar 'list vals) vals)))
10375 (defun org-property-previous-allowed-value (&optional previous)
10376 "Switch to the next allowed value for this property."
10377 (interactive)
10378 (org-property-next-allowed-value t))
10380 (defun org-property-next-allowed-value (&optional previous)
10381 "Switch to the next allowed value for this property."
10382 (interactive)
10383 (unless (org-at-property-p)
10384 (error "Not at a property"))
10385 (let* ((key (match-string 2))
10386 (value (match-string 3))
10387 (allowed (or (org-property-get-allowed-values (point) key)
10388 (and (member value '("[ ]" "[-]" "[X]"))
10389 '("[ ]" "[X]"))))
10390 nval)
10391 (unless allowed
10392 (error "Allowed values for this property have not been defined"))
10393 (if previous (setq allowed (reverse allowed)))
10394 (if (member value allowed)
10395 (setq nval (car (cdr (member value allowed)))))
10396 (setq nval (or nval (car allowed)))
10397 (if (equal nval value)
10398 (error "Only one allowed value for this property"))
10399 (org-at-property-p)
10400 (replace-match (concat " :" key ": " nval) t t)
10401 (org-indent-line-function)
10402 (beginning-of-line 1)
10403 (skip-chars-forward " \t")))
10405 (defun org-find-entry-with-id (ident)
10406 "Locate the entry that contains the ID property with exact value IDENT.
10407 IDENT can be a string, a symbol or a number, this function will search for
10408 the string representation of it.
10409 Return the position where this entry starts, or nil if there is no such entry."
10410 (let ((id (cond
10411 ((stringp ident) ident)
10412 ((symbol-name ident) (symbol-name ident))
10413 ((numberp ident) (number-to-string ident))
10414 (t (error "IDENT %s must be a string, symbol or number" ident))))
10415 (case-fold-search nil))
10416 (save-excursion
10417 (save-restriction
10418 (widen)
10419 (goto-char (point-min))
10420 (when (re-search-forward
10421 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
10422 nil t)
10423 (org-back-to-heading)
10424 (point))))))
10426 ;;; Column View
10428 (defvar org-columns-overlays nil
10429 "Holds the list of current column overlays.")
10431 (defvar org-columns-current-fmt nil
10432 "Local variable, holds the currently active column format.")
10433 (defvar org-columns-current-fmt-compiled nil
10434 "Local variable, holds the currently active column format.
10435 This is the compiled version of the format.")
10436 (defvar org-columns-current-widths nil
10437 "Loval variable, holds the currently widths of fields.")
10438 (defvar org-columns-current-maxwidths nil
10439 "Loval variable, holds the currently active maximum column widths.")
10440 (defvar org-columns-begin-marker (make-marker)
10441 "Points to the position where last a column creation command was called.")
10442 (defvar org-columns-top-level-marker (make-marker)
10443 "Points to the position where current columns region starts.")
10445 (defvar org-columns-map (make-sparse-keymap)
10446 "The keymap valid in column display.")
10448 (defun org-columns-content ()
10449 "Switch to contents view while in columns view."
10450 (interactive)
10451 (org-overview)
10452 (org-content))
10454 (org-defkey org-columns-map "c" 'org-columns-content)
10455 (org-defkey org-columns-map "o" 'org-overview)
10456 (org-defkey org-columns-map "e" 'org-columns-edit-value)
10457 (org-defkey org-columns-map "\C-c\C-t" 'org-columns-todo)
10458 (org-defkey org-columns-map "\C-c\C-c" 'org-columns-set-tags-or-toggle)
10459 (org-defkey org-columns-map "\C-c\C-o" 'org-columns-open-link)
10460 (org-defkey org-columns-map "v" 'org-columns-show-value)
10461 (org-defkey org-columns-map "q" 'org-columns-quit)
10462 (org-defkey org-columns-map "r" 'org-columns-redo)
10463 (org-defkey org-columns-map "g" 'org-columns-redo)
10464 (org-defkey org-columns-map [left] 'backward-char)
10465 (org-defkey org-columns-map "\M-b" 'backward-char)
10466 (org-defkey org-columns-map "a" 'org-columns-edit-allowed)
10467 (org-defkey org-columns-map "s" 'org-columns-edit-attributes)
10468 (org-defkey org-columns-map "\M-f" (lambda () (interactive) (goto-char (1+ (point)))))
10469 (org-defkey org-columns-map [right] (lambda () (interactive) (goto-char (1+ (point)))))
10470 (org-defkey org-columns-map [(shift right)] 'org-columns-next-allowed-value)
10471 (org-defkey org-columns-map "n" 'org-columns-next-allowed-value)
10472 (org-defkey org-columns-map [(shift left)] 'org-columns-previous-allowed-value)
10473 (org-defkey org-columns-map "p" 'org-columns-previous-allowed-value)
10474 (org-defkey org-columns-map "<" 'org-columns-narrow)
10475 (org-defkey org-columns-map ">" 'org-columns-widen)
10476 (org-defkey org-columns-map [(meta right)] 'org-columns-move-right)
10477 (org-defkey org-columns-map [(meta left)] 'org-columns-move-left)
10478 (org-defkey org-columns-map [(shift meta right)] 'org-columns-new)
10479 (org-defkey org-columns-map [(shift meta left)] 'org-columns-delete)
10481 (easy-menu-define org-columns-menu org-columns-map "Org Column Menu"
10482 '("Column"
10483 ["Edit property" org-columns-edit-value t]
10484 ["Next allowed value" org-columns-next-allowed-value t]
10485 ["Previous allowed value" org-columns-previous-allowed-value t]
10486 ["Show full value" org-columns-show-value t]
10487 ["Edit allowed values" org-columns-edit-allowed t]
10488 "--"
10489 ["Edit column attributes" org-columns-edit-attributes t]
10490 ["Increase column width" org-columns-widen t]
10491 ["Decrease column width" org-columns-narrow t]
10492 "--"
10493 ["Move column right" org-columns-move-right t]
10494 ["Move column left" org-columns-move-left t]
10495 ["Add column" org-columns-new t]
10496 ["Delete column" org-columns-delete t]
10497 "--"
10498 ["CONTENTS" org-columns-content t]
10499 ["OVERVIEW" org-overview t]
10500 ["Refresh columns display" org-columns-redo t]
10501 "--"
10502 ["Open link" org-columns-open-link t]
10503 "--"
10504 ["Quit" org-columns-quit t]))
10506 (defun org-columns-new-overlay (beg end &optional string face)
10507 "Create a new column overlay and add it to the list."
10508 (let ((ov (org-make-overlay beg end)))
10509 (org-overlay-put ov 'face (or face 'secondary-selection))
10510 (org-overlay-display ov string face)
10511 (push ov org-columns-overlays)
10512 ov))
10514 (defun org-columns-display-here (&optional props)
10515 "Overlay the current line with column display."
10516 (interactive)
10517 (let* ((fmt org-columns-current-fmt-compiled)
10518 (beg (point-at-bol))
10519 (level-face (save-excursion
10520 (beginning-of-line 1)
10521 (and (looking-at "\\(\\**\\)\\(\\* \\)")
10522 (org-get-level-face 2))))
10523 (color (list :foreground
10524 (face-attribute (or level-face 'default) :foreground)))
10525 props pom property ass width f string ov column val modval)
10526 ;; Check if the entry is in another buffer.
10527 (unless props
10528 (if (eq major-mode 'org-agenda-mode)
10529 (setq pom (or (get-text-property (point) 'org-hd-marker)
10530 (get-text-property (point) 'org-marker))
10531 props (if pom (org-entry-properties pom) nil))
10532 (setq props (org-entry-properties nil))))
10533 ;; Walk the format
10534 (while (setq column (pop fmt))
10535 (setq property (car column)
10536 ass (if (equal property "ITEM")
10537 (cons "ITEM"
10538 (save-match-data
10539 (org-no-properties
10540 (org-remove-tabs
10541 (buffer-substring-no-properties
10542 (point-at-bol) (point-at-eol))))))
10543 (assoc property props))
10544 width (or (cdr (assoc property org-columns-current-maxwidths))
10545 (nth 2 column)
10546 (length property))
10547 f (format "%%-%d.%ds | " width width)
10548 val (or (cdr ass) "")
10549 modval (if (equal property "ITEM")
10550 (org-columns-cleanup-item val org-columns-current-fmt-compiled))
10551 string (format f (or modval val)))
10552 ;; Create the overlay
10553 (org-unmodified
10554 (setq ov (org-columns-new-overlay
10555 beg (setq beg (1+ beg)) string
10556 (list color 'org-column)))
10557 ;;; (list (get-text-property (point-at-bol) 'face) 'org-column)))
10558 (org-overlay-put ov 'keymap org-columns-map)
10559 (org-overlay-put ov 'org-columns-key property)
10560 (org-overlay-put ov 'org-columns-value (cdr ass))
10561 (org-overlay-put ov 'org-columns-value-modified modval)
10562 (org-overlay-put ov 'org-columns-pom pom)
10563 (org-overlay-put ov 'org-columns-format f))
10564 (if (or (not (char-after beg))
10565 (equal (char-after beg) ?\n))
10566 (let ((inhibit-read-only t))
10567 (save-excursion
10568 (goto-char beg)
10569 (org-unmodified (insert " ")))))) ;; FIXME: add props and remove later?
10570 ;; Make the rest of the line disappear.
10571 (org-unmodified
10572 (setq ov (org-columns-new-overlay beg (point-at-eol)))
10573 (org-overlay-put ov 'invisible t)
10574 (org-overlay-put ov 'keymap org-columns-map)
10575 (org-overlay-put ov 'intangible t)
10576 (push ov org-columns-overlays)
10577 (setq ov (org-make-overlay (1- (point-at-eol)) (1+ (point-at-eol))))
10578 (org-overlay-put ov 'keymap org-columns-map)
10579 (push ov org-columns-overlays)
10580 (let ((inhibit-read-only t))
10581 (put-text-property (max (point-min) (1- (point-at-bol)))
10582 (min (point-max) (1+ (point-at-eol)))
10583 'read-only "Type `e' to edit property")))))
10585 (defvar org-previous-header-line-format nil
10586 "The header line format before column view was turned on.")
10587 (defvar org-columns-inhibit-recalculation nil
10588 "Inhibit recomputing of columns on column view startup.")
10591 (defvar header-line-format)
10592 (defun org-columns-display-here-title ()
10593 "Overlay the newline before the current line with the table title."
10594 (interactive)
10595 (let ((fmt org-columns-current-fmt-compiled)
10596 string (title "")
10597 property width f column str widths)
10598 (while (setq column (pop fmt))
10599 (setq property (car column)
10600 str (or (nth 1 column) property)
10601 width (or (cdr (assoc property org-columns-current-maxwidths))
10602 (nth 2 column)
10603 (length str))
10604 widths (push width widths)
10605 f (format "%%-%d.%ds | " width width)
10606 string (format f str)
10607 title (concat title string)))
10608 (setq title (concat
10609 (org-add-props " " nil 'display '(space :align-to 0))
10610 (org-add-props title nil 'face '(:weight bold :underline t))))
10611 (org-set-local 'org-previous-header-line-format header-line-format)
10612 (org-set-local 'org-columns-current-widths (nreverse widths))
10613 (setq header-line-format title)))
10615 (defun org-columns-remove-overlays ()
10616 "Remove all currently active column overlays."
10617 (interactive)
10618 (when (marker-buffer org-columns-begin-marker)
10619 (with-current-buffer (marker-buffer org-columns-begin-marker)
10620 (when (local-variable-p 'org-previous-header-line-format)
10621 (setq header-line-format org-previous-header-line-format)
10622 (kill-local-variable 'org-previous-header-line-format))
10623 (move-marker org-columns-begin-marker nil)
10624 (move-marker org-columns-top-level-marker nil)
10625 (org-unmodified
10626 (mapc 'org-delete-overlay org-columns-overlays)
10627 (setq org-columns-overlays nil)
10628 (let ((inhibit-read-only t))
10629 (remove-text-properties (point-min) (point-max) '(read-only t)))))))
10631 (defun org-columns-cleanup-item (item fmt)
10632 "Remove from ITEM what is a column in the format FMT."
10633 (if (not org-complex-heading-regexp)
10634 item
10635 (when (string-match org-complex-heading-regexp item)
10636 (concat
10637 (org-add-props (concat (match-string 1 item) " ") nil
10638 'org-whitespace (* 2 (1- (org-reduced-level (- (match-end 1) (match-beginning 1))))))
10639 (and (match-end 2) (not (assoc "TODO" fmt)) (concat " " (match-string 2 item)))
10640 (and (match-end 3) (not (assoc "PRIORITY" fmt)) (concat " " (match-string 3 item)))
10641 " " (match-string 4 item)
10642 (and (match-end 5) (not (assoc "TAGS" fmt)) (concat " " (match-string 5 item)))))))
10644 (defun org-columns-show-value ()
10645 "Show the full value of the property."
10646 (interactive)
10647 (let ((value (get-char-property (point) 'org-columns-value)))
10648 (message "Value is: %s" (or value ""))))
10650 (defun org-columns-quit ()
10651 "Remove the column overlays and in this way exit column editing."
10652 (interactive)
10653 (org-unmodified
10654 (org-columns-remove-overlays)
10655 (let ((inhibit-read-only t))
10656 (remove-text-properties (point-min) (point-max) '(read-only t))))
10657 (when (eq major-mode 'org-agenda-mode)
10658 (message
10659 "Modification not yet reflected in Agenda buffer, use `r' to refresh")))
10661 (defun org-columns-check-computed ()
10662 "Check if this column value is computed.
10663 If yes, throw an error indicating that changing it does not make sense."
10664 (let ((val (get-char-property (point) 'org-columns-value)))
10665 (when (and (stringp val)
10666 (get-char-property 0 'org-computed val))
10667 (error "This value is computed from the entry's children"))))
10669 (defun org-columns-todo (&optional arg)
10670 "Change the TODO state during column view."
10671 (interactive "P")
10672 (org-columns-edit-value "TODO"))
10674 (defun org-columns-set-tags-or-toggle (&optional arg)
10675 "Toggle checkbox at point, or set tags for current headline."
10676 (interactive "P")
10677 (if (string-match "\\`\\[[ xX-]\\]\\'"
10678 (get-char-property (point) 'org-columns-value))
10679 (org-columns-next-allowed-value)
10680 (org-columns-edit-value "TAGS")))
10682 (defun org-columns-edit-value (&optional key)
10683 "Edit the value of the property at point in column view.
10684 Where possible, use the standard interface for changing this line."
10685 (interactive)
10686 (org-columns-check-computed)
10687 (let* ((external-key key)
10688 (col (current-column))
10689 (key (or key (get-char-property (point) 'org-columns-key)))
10690 (value (get-char-property (point) 'org-columns-value))
10691 (bol (point-at-bol)) (eol (point-at-eol))
10692 (pom (or (get-text-property bol 'org-hd-marker)
10693 (point))) ; keep despite of compiler waring
10694 (line-overlays
10695 (delq nil (mapcar (lambda (x)
10696 (and (eq (overlay-buffer x) (current-buffer))
10697 (>= (overlay-start x) bol)
10698 (<= (overlay-start x) eol)
10700 org-columns-overlays)))
10701 nval eval allowed)
10702 (cond
10703 ((equal key "CLOCKSUM")
10704 (error "This special column cannot be edited"))
10705 ((equal key "ITEM")
10706 (setq eval '(org-with-point-at pom
10707 (org-edit-headline))))
10708 ((equal key "TODO")
10709 (setq eval '(org-with-point-at pom
10710 (let ((current-prefix-arg
10711 (if external-key current-prefix-arg '(4))))
10712 (call-interactively 'org-todo)))))
10713 ((equal key "PRIORITY")
10714 (setq eval '(org-with-point-at pom
10715 (call-interactively 'org-priority))))
10716 ((equal key "TAGS")
10717 (setq eval '(org-with-point-at pom
10718 (let ((org-fast-tag-selection-single-key
10719 (if (eq org-fast-tag-selection-single-key 'expert)
10720 t org-fast-tag-selection-single-key)))
10721 (call-interactively 'org-set-tags)))))
10722 ((equal key "DEADLINE")
10723 (setq eval '(org-with-point-at pom
10724 (call-interactively 'org-deadline))))
10725 ((equal key "SCHEDULED")
10726 (setq eval '(org-with-point-at pom
10727 (call-interactively 'org-schedule))))
10729 (setq allowed (org-property-get-allowed-values pom key 'table))
10730 (if allowed
10731 (setq nval (completing-read "Value: " allowed nil t))
10732 (setq nval (read-string "Edit: " value)))
10733 (setq nval (org-trim nval))
10734 (when (not (equal nval value))
10735 (setq eval '(org-entry-put pom key nval)))))
10736 (when eval
10737 (let ((inhibit-read-only t))
10738 (remove-text-properties (max (point-min) (1- bol)) eol '(read-only t))
10739 (unwind-protect
10740 (progn
10741 (setq org-columns-overlays
10742 (org-delete-all line-overlays org-columns-overlays))
10743 (mapc 'org-delete-overlay line-overlays)
10744 (org-columns-eval eval))
10745 (org-columns-display-here))))
10746 (move-to-column col)
10747 (if (and (org-mode-p)
10748 (nth 3 (assoc key org-columns-current-fmt-compiled)))
10749 (org-columns-update key))))
10751 (defun org-edit-headline () ; FIXME: this is not columns specific
10752 "Edit the current headline, the part without TODO keyword, TAGS."
10753 (org-back-to-heading)
10754 (when (looking-at org-todo-line-regexp)
10755 (let ((pre (buffer-substring (match-beginning 0) (match-beginning 3)))
10756 (txt (match-string 3))
10757 (post "")
10758 txt2)
10759 (if (string-match (org-re "[ \t]+:[[:alnum:]:_@]+:[ \t]*$") txt)
10760 (setq post (match-string 0 txt)
10761 txt (substring txt 0 (match-beginning 0))))
10762 (setq txt2 (read-string "Edit: " txt))
10763 (when (not (equal txt txt2))
10764 (beginning-of-line 1)
10765 (insert pre txt2 post)
10766 (delete-region (point) (point-at-eol))
10767 (org-set-tags nil t)))))
10769 (defun org-columns-edit-allowed ()
10770 "Edit the list of allowed values for the current property."
10771 (interactive)
10772 (let* ((key (get-char-property (point) 'org-columns-key))
10773 (key1 (concat key "_ALL"))
10774 (allowed (org-entry-get (point) key1 t))
10775 nval)
10776 ;; FIXME: Cover editing TODO, TAGS etc in-buffer settings.????
10777 (setq nval (read-string "Allowed: " allowed))
10778 (org-entry-put
10779 (cond ((marker-position org-entry-property-inherited-from)
10780 org-entry-property-inherited-from)
10781 ((marker-position org-columns-top-level-marker)
10782 org-columns-top-level-marker))
10783 key1 nval)))
10785 (defun org-columns-eval (form)
10786 (let (hidep)
10787 (save-excursion
10788 (beginning-of-line 1)
10789 ;; `next-line' is needed here, because it skips invisible line.
10790 (condition-case nil (org-no-warnings (next-line 1)) (error nil))
10791 (setq hidep (org-on-heading-p 1)))
10792 (eval form)
10793 (and hidep (hide-entry))))
10795 (defun org-columns-previous-allowed-value ()
10796 "Switch to the previous allowed value for this column."
10797 (interactive)
10798 (org-columns-next-allowed-value t))
10800 (defun org-columns-next-allowed-value (&optional previous)
10801 "Switch to the next allowed value for this column."
10802 (interactive)
10803 (org-columns-check-computed)
10804 (let* ((col (current-column))
10805 (key (get-char-property (point) 'org-columns-key))
10806 (value (get-char-property (point) 'org-columns-value))
10807 (bol (point-at-bol)) (eol (point-at-eol))
10808 (pom (or (get-text-property bol 'org-hd-marker)
10809 (point))) ; keep despite of compiler waring
10810 (line-overlays
10811 (delq nil (mapcar (lambda (x)
10812 (and (eq (overlay-buffer x) (current-buffer))
10813 (>= (overlay-start x) bol)
10814 (<= (overlay-start x) eol)
10816 org-columns-overlays)))
10817 (allowed (or (org-property-get-allowed-values pom key)
10818 (and (memq
10819 (nth 4 (assoc key org-columns-current-fmt-compiled))
10820 '(checkbox checkbox-n-of-m checkbox-percent))
10821 '("[ ]" "[X]"))))
10822 nval)
10823 (when (equal key "ITEM")
10824 (error "Cannot edit item headline from here"))
10825 (unless (or allowed (member key '("SCHEDULED" "DEADLINE")))
10826 (error "Allowed values for this property have not been defined"))
10827 (if (member key '("SCHEDULED" "DEADLINE"))
10828 (setq nval (if previous 'earlier 'later))
10829 (if previous (setq allowed (reverse allowed)))
10830 (if (member value allowed)
10831 (setq nval (car (cdr (member value allowed)))))
10832 (setq nval (or nval (car allowed)))
10833 (if (equal nval value)
10834 (error "Only one allowed value for this property")))
10835 (let ((inhibit-read-only t))
10836 (remove-text-properties (1- bol) eol '(read-only t))
10837 (unwind-protect
10838 (progn
10839 (setq org-columns-overlays
10840 (org-delete-all line-overlays org-columns-overlays))
10841 (mapc 'org-delete-overlay line-overlays)
10842 (org-columns-eval '(org-entry-put pom key nval)))
10843 (org-columns-display-here)))
10844 (move-to-column col)
10845 (if (and (org-mode-p)
10846 (nth 3 (assoc key org-columns-current-fmt-compiled)))
10847 (org-columns-update key))))
10849 (defun org-verify-version (task)
10850 (cond
10851 ((eq task 'columns)
10852 (if (or (featurep 'xemacs)
10853 (< emacs-major-version 22))
10854 (error "Emacs 22 is required for the columns feature")))))
10856 (defun org-columns-open-link (&optional arg)
10857 (interactive "P")
10858 (let ((value (get-char-property (point) 'org-columns-value)))
10859 (org-open-link-from-string value arg)))
10861 (defun org-open-link-from-string (s &optional arg)
10862 "Open a link in the string S, as if it was in Org-mode."
10863 (interactive)
10864 (with-temp-buffer
10865 (let ((org-inhibit-startup t))
10866 (org-mode)
10867 (insert s)
10868 (goto-char (point-min))
10869 (org-open-at-point arg))))
10871 (defun org-columns-get-format-and-top-level ()
10872 (let (fmt)
10873 (when (condition-case nil (org-back-to-heading) (error nil))
10874 (move-marker org-entry-property-inherited-from nil)
10875 (setq fmt (org-entry-get nil "COLUMNS" t)))
10876 (setq fmt (or fmt org-columns-default-format))
10877 (org-set-local 'org-columns-current-fmt fmt)
10878 (org-columns-compile-format fmt)
10879 (if (marker-position org-entry-property-inherited-from)
10880 (move-marker org-columns-top-level-marker
10881 org-entry-property-inherited-from)
10882 (move-marker org-columns-top-level-marker (point)))
10883 fmt))
10885 (defun org-columns ()
10886 "Turn on column view on an org-mode file."
10887 (interactive)
10888 (org-verify-version 'columns)
10889 (org-columns-remove-overlays)
10890 (move-marker org-columns-begin-marker (point))
10891 (let (beg end fmt cache maxwidths)
10892 (setq fmt (org-columns-get-format-and-top-level))
10893 (save-excursion
10894 (goto-char org-columns-top-level-marker)
10895 (setq beg (point))
10896 (unless org-columns-inhibit-recalculation
10897 (org-columns-compute-all))
10898 (setq end (or (condition-case nil (org-end-of-subtree t t) (error nil))
10899 (point-max)))
10900 ;; Get and cache the properties
10901 (goto-char beg)
10902 (when (assoc "CLOCKSUM" org-columns-current-fmt-compiled)
10903 (save-excursion
10904 (save-restriction
10905 (narrow-to-region beg end)
10906 (org-clock-sum))))
10907 (while (re-search-forward (concat "^" outline-regexp) end t)
10908 (push (cons (org-current-line) (org-entry-properties)) cache))
10909 (when cache
10910 (setq maxwidths (org-columns-get-autowidth-alist fmt cache))
10911 (org-set-local 'org-columns-current-maxwidths maxwidths)
10912 (org-columns-display-here-title)
10913 (mapc (lambda (x)
10914 (goto-line (car x))
10915 (org-columns-display-here (cdr x)))
10916 cache)))))
10918 (defun org-columns-new (&optional prop title width op fmt &rest rest)
10919 "Insert a new column, to the left of the current column."
10920 (interactive)
10921 (let ((editp (and prop (assoc prop org-columns-current-fmt-compiled)))
10922 cell)
10923 (setq prop (completing-read
10924 "Property: " (mapcar 'list (org-buffer-property-keys t nil t))
10925 nil nil prop))
10926 (setq title (read-string (concat "Column title [" prop "]: ") (or title prop)))
10927 (setq width (read-string "Column width: " (if width (number-to-string width))))
10928 (if (string-match "\\S-" width)
10929 (setq width (string-to-number width))
10930 (setq width nil))
10931 (setq fmt (completing-read "Summary [none]: "
10932 '(("none") ("add_numbers") ("currency") ("add_times") ("checkbox") ("checkbox-n-of-m") ("checkbox-percent"))
10933 nil t))
10934 (if (string-match "\\S-" fmt)
10935 (setq fmt (intern fmt))
10936 (setq fmt nil))
10937 (if (eq fmt 'none) (setq fmt nil))
10938 (if editp
10939 (progn
10940 (setcar editp prop)
10941 (setcdr editp (list title width nil fmt)))
10942 (setq cell (nthcdr (1- (current-column))
10943 org-columns-current-fmt-compiled))
10944 (setcdr cell (cons (list prop title width nil fmt)
10945 (cdr cell))))
10946 (org-columns-store-format)
10947 (org-columns-redo)))
10949 (defun org-columns-delete ()
10950 "Delete the column at point from columns view."
10951 (interactive)
10952 (let* ((n (current-column))
10953 (title (nth 1 (nth n org-columns-current-fmt-compiled))))
10954 (when (y-or-n-p
10955 (format "Are you sure you want to remove column \"%s\"? " title))
10956 (setq org-columns-current-fmt-compiled
10957 (delq (nth n org-columns-current-fmt-compiled)
10958 org-columns-current-fmt-compiled))
10959 (org-columns-store-format)
10960 (org-columns-redo)
10961 (if (>= (current-column) (length org-columns-current-fmt-compiled))
10962 (backward-char 1)))))
10964 (defun org-columns-edit-attributes ()
10965 "Edit the attributes of the current column."
10966 (interactive)
10967 (let* ((n (current-column))
10968 (info (nth n org-columns-current-fmt-compiled)))
10969 (apply 'org-columns-new info)))
10971 (defun org-columns-widen (arg)
10972 "Make the column wider by ARG characters."
10973 (interactive "p")
10974 (let* ((n (current-column))
10975 (entry (nth n org-columns-current-fmt-compiled))
10976 (width (or (nth 2 entry)
10977 (cdr (assoc (car entry) org-columns-current-maxwidths)))))
10978 (setq width (max 1 (+ width arg)))
10979 (setcar (nthcdr 2 entry) width)
10980 (org-columns-store-format)
10981 (org-columns-redo)))
10983 (defun org-columns-narrow (arg)
10984 "Make the column nrrower by ARG characters."
10985 (interactive "p")
10986 (org-columns-widen (- arg)))
10988 (defun org-columns-move-right ()
10989 "Swap this column with the one to the right."
10990 (interactive)
10991 (let* ((n (current-column))
10992 (cell (nthcdr n org-columns-current-fmt-compiled))
10994 (when (>= n (1- (length org-columns-current-fmt-compiled)))
10995 (error "Cannot shift this column further to the right"))
10996 (setq e (car cell))
10997 (setcar cell (car (cdr cell)))
10998 (setcdr cell (cons e (cdr (cdr cell))))
10999 (org-columns-store-format)
11000 (org-columns-redo)
11001 (forward-char 1)))
11003 (defun org-columns-move-left ()
11004 "Swap this column with the one to the left."
11005 (interactive)
11006 (let* ((n (current-column)))
11007 (when (= n 0)
11008 (error "Cannot shift this column further to the left"))
11009 (backward-char 1)
11010 (org-columns-move-right)
11011 (backward-char 1)))
11013 (defun org-columns-store-format ()
11014 "Store the text version of the current columns format in appropriate place.
11015 This is either in the COLUMNS property of the node starting the current column
11016 display, or in the #+COLUMNS line of the current buffer."
11017 (let (fmt (cnt 0))
11018 (setq fmt (org-columns-uncompile-format org-columns-current-fmt-compiled))
11019 (org-set-local 'org-columns-current-fmt fmt)
11020 (if (marker-position org-columns-top-level-marker)
11021 (save-excursion
11022 (goto-char org-columns-top-level-marker)
11023 (if (and (org-at-heading-p)
11024 (org-entry-get nil "COLUMNS"))
11025 (org-entry-put nil "COLUMNS" fmt)
11026 (goto-char (point-min))
11027 ;; Overwrite all #+COLUMNS lines....
11028 (while (re-search-forward "^#\\+COLUMNS:.*" nil t)
11029 (setq cnt (1+ cnt))
11030 (replace-match (concat "#+COLUMNS: " fmt) t t))
11031 (unless (> cnt 0)
11032 (goto-char (point-min))
11033 (or (org-on-heading-p t) (outline-next-heading))
11034 (let ((inhibit-read-only t))
11035 (insert-before-markers "#+COLUMNS: " fmt "\n")))
11036 (org-set-local 'org-columns-default-format fmt))))))
11038 (defvar org-overriding-columns-format nil
11039 "When set, overrides any other definition.")
11040 (defvar org-agenda-view-columns-initially nil
11041 "When set, switch to columns view immediately after creating the agenda.")
11043 (defun org-agenda-columns ()
11044 "Turn on column view in the agenda."
11045 (interactive)
11046 (org-verify-version 'columns)
11047 (org-columns-remove-overlays)
11048 (move-marker org-columns-begin-marker (point))
11049 (let (fmt cache maxwidths m)
11050 (cond
11051 ((and (local-variable-p 'org-overriding-columns-format)
11052 org-overriding-columns-format)
11053 (setq fmt org-overriding-columns-format))
11054 ((setq m (get-text-property (point-at-bol) 'org-hd-marker))
11055 (setq fmt (org-entry-get m "COLUMNS" t)))
11056 ((and (boundp 'org-columns-current-fmt)
11057 (local-variable-p 'org-columns-current-fmt)
11058 org-columns-current-fmt)
11059 (setq fmt org-columns-current-fmt))
11060 ((setq m (next-single-property-change (point-min) 'org-hd-marker))
11061 (setq m (get-text-property m 'org-hd-marker))
11062 (setq fmt (org-entry-get m "COLUMNS" t))))
11063 (setq fmt (or fmt org-columns-default-format))
11064 (org-set-local 'org-columns-current-fmt fmt)
11065 (org-columns-compile-format fmt)
11066 (save-excursion
11067 ;; Get and cache the properties
11068 (goto-char (point-min))
11069 (while (not (eobp))
11070 (when (setq m (or (get-text-property (point) 'org-hd-marker)
11071 (get-text-property (point) 'org-marker)))
11072 (push (cons (org-current-line) (org-entry-properties m)) cache))
11073 (beginning-of-line 2))
11074 (when cache
11075 (setq maxwidths (org-columns-get-autowidth-alist fmt cache))
11076 (org-set-local 'org-columns-current-maxwidths maxwidths)
11077 (org-columns-display-here-title)
11078 (mapc (lambda (x)
11079 (goto-line (car x))
11080 (org-columns-display-here (cdr x)))
11081 cache)))))
11083 (defun org-columns-get-autowidth-alist (s cache)
11084 "Derive the maximum column widths from the format and the cache."
11085 (let ((start 0) rtn)
11086 (while (string-match (org-re "%\\([[:alpha:]][[:alnum:]_-]*\\)") s start)
11087 (push (cons (match-string 1 s) 1) rtn)
11088 (setq start (match-end 0)))
11089 (mapc (lambda (x)
11090 (setcdr x (apply 'max
11091 (mapcar
11092 (lambda (y)
11093 (length (or (cdr (assoc (car x) (cdr y))) " ")))
11094 cache))))
11095 rtn)
11096 rtn))
11098 (defun org-columns-compute-all ()
11099 "Compute all columns that have operators defined."
11100 (org-unmodified
11101 (remove-text-properties (point-min) (point-max) '(org-summaries t)))
11102 (let ((columns org-columns-current-fmt-compiled) col)
11103 (while (setq col (pop columns))
11104 (when (nth 3 col)
11105 (save-excursion
11106 (org-columns-compute (car col)))))))
11108 (defun org-columns-update (property)
11109 "Recompute PROPERTY, and update the columns display for it."
11110 (org-columns-compute property)
11111 (let (fmt val pos)
11112 (save-excursion
11113 (mapc (lambda (ov)
11114 (when (equal (org-overlay-get ov 'org-columns-key) property)
11115 (setq pos (org-overlay-start ov))
11116 (goto-char pos)
11117 (when (setq val (cdr (assoc property
11118 (get-text-property
11119 (point-at-bol) 'org-summaries))))
11120 (setq fmt (org-overlay-get ov 'org-columns-format))
11121 (org-overlay-put ov 'org-columns-value val)
11122 (org-overlay-put ov 'display (format fmt val)))))
11123 org-columns-overlays))))
11125 (defun org-columns-compute (property)
11126 "Sum the values of property PROPERTY hierarchically, for the entire buffer."
11127 (interactive)
11128 (let* ((re (concat "^" outline-regexp))
11129 (lmax 30) ; Does anyone use deeper levels???
11130 (lsum (make-vector lmax 0))
11131 (lflag (make-vector lmax nil))
11132 (level 0)
11133 (ass (assoc property org-columns-current-fmt-compiled))
11134 (format (nth 4 ass))
11135 (printf (nth 5 ass))
11136 (beg org-columns-top-level-marker)
11137 last-level val valflag flag end sumpos sum-alist sum str str1 useval)
11138 (save-excursion
11139 ;; Find the region to compute
11140 (goto-char beg)
11141 (setq end (condition-case nil (org-end-of-subtree t) (error (point-max))))
11142 (goto-char end)
11143 ;; Walk the tree from the back and do the computations
11144 (while (re-search-backward re beg t)
11145 (setq sumpos (match-beginning 0)
11146 last-level level
11147 level (org-outline-level)
11148 val (org-entry-get nil property)
11149 valflag (and val (string-match "\\S-" val)))
11150 (cond
11151 ((< level last-level)
11152 ;; put the sum of lower levels here as a property
11153 (setq sum (aref lsum last-level) ; current sum
11154 flag (aref lflag last-level) ; any valid entries from children?
11155 str (org-column-number-to-string sum format printf)
11156 str1 (org-add-props (copy-sequence str) nil 'org-computed t 'face 'bold)
11157 useval (if flag str1 (if valflag val ""))
11158 sum-alist (get-text-property sumpos 'org-summaries))
11159 (if (assoc property sum-alist)
11160 (setcdr (assoc property sum-alist) useval)
11161 (push (cons property useval) sum-alist)
11162 (org-unmodified
11163 (add-text-properties sumpos (1+ sumpos)
11164 (list 'org-summaries sum-alist))))
11165 (when val
11166 (org-entry-put nil property (if flag str val)))
11167 ;; add current to current level accumulator
11168 (when (or flag valflag)
11169 (aset lsum level (+ (aref lsum level)
11170 (if flag sum (org-column-string-to-number
11171 (if flag str val) format))))
11172 (aset lflag level t))
11173 ;; clear accumulators for deeper levels
11174 (loop for l from (1+ level) to (1- lmax) do
11175 (aset lsum l 0)
11176 (aset lflag l nil)))
11177 ((>= level last-level)
11178 ;; add what we have here to the accumulator for this level
11179 (aset lsum level (+ (aref lsum level)
11180 (org-column-string-to-number (or val "0") format)))
11181 (and valflag (aset lflag level t)))
11182 (t (error "This should not happen")))))))
11184 (defun org-columns-redo ()
11185 "Construct the column display again."
11186 (interactive)
11187 (message "Recomputing columns...")
11188 (save-excursion
11189 (if (marker-position org-columns-begin-marker)
11190 (goto-char org-columns-begin-marker))
11191 (org-columns-remove-overlays)
11192 (if (org-mode-p)
11193 (call-interactively 'org-columns)
11194 (call-interactively 'org-agenda-columns)))
11195 (message "Recomputing columns...done"))
11197 (defun org-columns-not-in-agenda ()
11198 (if (eq major-mode 'org-agenda-mode)
11199 (error "This command is only allowed in Org-mode buffers")))
11202 (defun org-string-to-number (s)
11203 "Convert string to number, and interpret hh:mm:ss."
11204 (if (not (string-match ":" s))
11205 (string-to-number s)
11206 (let ((l (nreverse (org-split-string s ":"))) (sum 0.0))
11207 (while l
11208 (setq sum (+ (string-to-number (pop l)) (/ sum 60))))
11209 sum)))
11211 (defun org-column-number-to-string (n fmt &optional printf)
11212 "Convert a computed column number to a string value, according to FMT."
11213 (cond
11214 ((eq fmt 'add_times)
11215 (let* ((h (floor n)) (m (floor (+ 0.5 (* 60 (- n h))))))
11216 (format "%d:%02d" h m)))
11217 ((eq fmt 'checkbox)
11218 (cond ((= n (floor n)) "[X]")
11219 ((> n 1.) "[-]")
11220 (t "[ ]")))
11221 ((memq fmt '(checkbox-n-of-m checkbox-percent))
11222 (let* ((n1 (floor n)) (n2 (floor (+ .5 (* 1000000 (- n n1))))))
11223 (org-nofm-to-completion n1 (+ n2 n1) (eq fmt 'checkbox-percent))))
11224 (printf (format printf n))
11225 ((eq fmt 'currency)
11226 (format "%.2f" n))
11227 (t (number-to-string n))))
11229 (defun org-nofm-to-completion (n m &optional percent)
11230 (if (not percent)
11231 (format "[%d/%d]" n m)
11232 (format "[%d%%]"(floor (+ 0.5 (* 100. (/ (* 1.0 n) m)))))))
11234 (defun org-column-string-to-number (s fmt)
11235 "Convert a column value to a number that can be used for column computing."
11236 (cond
11237 ((string-match ":" s)
11238 (let ((l (nreverse (org-split-string s ":"))) (sum 0.0))
11239 (while l
11240 (setq sum (+ (string-to-number (pop l)) (/ sum 60))))
11241 sum))
11242 ((memq fmt '(checkbox checkbox-n-of-m checkbox-percent))
11243 (if (equal s "[X]") 1. 0.000001))
11244 (t (string-to-number s))))
11246 (defun org-columns-uncompile-format (cfmt)
11247 "Turn the compiled columns format back into a string representation."
11248 (let ((rtn "") e s prop title op width fmt printf)
11249 (while (setq e (pop cfmt))
11250 (setq prop (car e)
11251 title (nth 1 e)
11252 width (nth 2 e)
11253 op (nth 3 e)
11254 fmt (nth 4 e)
11255 printf (nth 5 e))
11256 (cond
11257 ((eq fmt 'add_times) (setq op ":"))
11258 ((eq fmt 'checkbox) (setq op "X"))
11259 ((eq fmt 'checkbox-n-of-m) (setq op "X/"))
11260 ((eq fmt 'checkbox-percent) (setq op "X%"))
11261 ((eq fmt 'add_numbers) (setq op "+"))
11262 ((eq fmt 'currency) (setq op "$")))
11263 (if (and op printf) (setq op (concat op ";" printf)))
11264 (if (equal title prop) (setq title nil))
11265 (setq s (concat "%" (if width (number-to-string width))
11266 prop
11267 (if title (concat "(" title ")"))
11268 (if op (concat "{" op "}"))))
11269 (setq rtn (concat rtn " " s)))
11270 (org-trim rtn)))
11272 (defun org-columns-compile-format (fmt)
11273 "Turn a column format string into an alist of specifications.
11274 The alist has one entry for each column in the format. The elements of
11275 that list are:
11276 property the property
11277 title the title field for the columns
11278 width the column width in characters, can be nil for automatic
11279 operator the operator if any
11280 format the output format for computed results, derived from operator
11281 printf a printf format for computed values"
11282 (let ((start 0) width prop title op f printf)
11283 (setq org-columns-current-fmt-compiled nil)
11284 (while (string-match
11285 (org-re "%\\([0-9]+\\)?\\([[:alnum:]_-]+\\)\\(?:(\\([^)]+\\))\\)?\\(?:{\\([^}]+\\)}\\)?\\s-*")
11286 fmt start)
11287 (setq start (match-end 0)
11288 width (match-string 1 fmt)
11289 prop (match-string 2 fmt)
11290 title (or (match-string 3 fmt) prop)
11291 op (match-string 4 fmt)
11292 f nil
11293 printf nil)
11294 (if width (setq width (string-to-number width)))
11295 (when (and op (string-match ";" op))
11296 (setq printf (substring op (match-end 0))
11297 op (substring op 0 (match-beginning 0))))
11298 (cond
11299 ((equal op "+") (setq f 'add_numbers))
11300 ((equal op "$") (setq f 'currency))
11301 ((equal op ":") (setq f 'add_times))
11302 ((equal op "X") (setq f 'checkbox))
11303 ((equal op "X/") (setq f 'checkbox-n-of-m))
11304 ((equal op "X%") (setq f 'checkbox-percent))
11306 (push (list prop title width op f printf) org-columns-current-fmt-compiled))
11307 (setq org-columns-current-fmt-compiled
11308 (nreverse org-columns-current-fmt-compiled))))
11311 ;;; Dynamic block for Column view
11313 (defun org-columns-capture-view (&optional maxlevel skip-empty-rows)
11314 "Get the column view of the current buffer or subtree.
11315 The first optional argument MAXLEVEL sets the level limit. A
11316 second optional argument SKIP-EMPTY-ROWS tells whether to skip
11317 empty rows, an empty row being one where all the column view
11318 specifiers except ITEM are empty. This function returns a list
11319 containing the title row and all other rows. Each row is a list
11320 of fields."
11321 (save-excursion
11322 (let* ((title (mapcar 'cadr org-columns-current-fmt-compiled))
11323 (n (length title)) row tbl)
11324 (goto-char (point-min))
11325 (while (and (re-search-forward "^\\(\\*+\\) " nil t)
11326 (or (null maxlevel)
11327 (>= maxlevel
11328 (if org-odd-levels-only
11329 (/ (1+ (length (match-string 1))) 2)
11330 (length (match-string 1))))))
11331 (when (get-char-property (match-beginning 0) 'org-columns-key)
11332 (setq row nil)
11333 (loop for i from 0 to (1- n) do
11334 (push (or (get-char-property (+ (match-beginning 0) i) 'org-columns-value-modified)
11335 (get-char-property (+ (match-beginning 0) i) 'org-columns-value)
11337 row))
11338 (setq row (nreverse row))
11339 (unless (and skip-empty-rows
11340 (eq 1 (length (delete "" (delete-dups row)))))
11341 (push row tbl))))
11342 (append (list title 'hline) (nreverse tbl)))))
11344 (defun org-dblock-write:columnview (params)
11345 "Write the column view table.
11346 PARAMS is a property list of parameters:
11348 :width enforce same column widths with <N> specifiers.
11349 :id the :ID: property of the entry where the columns view
11350 should be built, as a string. When `local', call locally.
11351 When `global' call column view with the cursor at the beginning
11352 of the buffer (usually this means that the whole buffer switches
11353 to column view).
11354 :hlines When t, insert a hline before each item. When a number, insert
11355 a hline before each level <= that number.
11356 :vlines When t, make each column a colgroup to enforce vertical lines.
11357 :maxlevel When set to a number, don't capture headlines below this level.
11358 :skip-empty-rows
11359 When t, skip rows where all specifiers other than ITEM are empty."
11360 (let ((pos (move-marker (make-marker) (point)))
11361 (hlines (plist-get params :hlines))
11362 (vlines (plist-get params :vlines))
11363 (maxlevel (plist-get params :maxlevel))
11364 (skip-empty-rows (plist-get params :skip-empty-rows))
11365 tbl id idpos nfields tmp)
11366 (save-excursion
11367 (save-restriction
11368 (when (setq id (plist-get params :id))
11369 (cond ((not id) nil)
11370 ((eq id 'global) (goto-char (point-min)))
11371 ((eq id 'local) nil)
11372 ((setq idpos (org-find-entry-with-id id))
11373 (goto-char idpos))
11374 (t (error "Cannot find entry with :ID: %s" id))))
11375 (org-columns)
11376 (setq tbl (org-columns-capture-view maxlevel skip-empty-rows))
11377 (setq nfields (length (car tbl)))
11378 (org-columns-quit)))
11379 (goto-char pos)
11380 (move-marker pos nil)
11381 (when tbl
11382 (when (plist-get params :hlines)
11383 (setq tmp nil)
11384 (while tbl
11385 (if (eq (car tbl) 'hline)
11386 (push (pop tbl) tmp)
11387 (if (string-match "\\` *\\(\\*+\\)" (caar tbl))
11388 (if (and (not (eq (car tmp) 'hline))
11389 (or (eq hlines t)
11390 (and (numberp hlines) (<= (- (match-end 1) (match-beginning 1)) hlines))))
11391 (push 'hline tmp)))
11392 (push (pop tbl) tmp)))
11393 (setq tbl (nreverse tmp)))
11394 (when vlines
11395 (setq tbl (mapcar (lambda (x)
11396 (if (eq 'hline x) x (cons "" x)))
11397 tbl))
11398 (setq tbl (append tbl (list (cons "/" (make-list nfields "<>"))))))
11399 (setq pos (point))
11400 (insert (org-listtable-to-string tbl))
11401 (when (plist-get params :width)
11402 (insert "\n|" (mapconcat (lambda (x) (format "<%d>" (max 3 x)))
11403 org-columns-current-widths "|")))
11404 (goto-char pos)
11405 (org-table-align))))
11407 (defun org-listtable-to-string (tbl)
11408 "Convert a listtable TBL to a string that contains the Org-mode table.
11409 The table still need to be alligned. The resulting string has no leading
11410 and tailing newline characters."
11411 (mapconcat
11412 (lambda (x)
11413 (cond
11414 ((listp x)
11415 (concat "|" (mapconcat 'identity x "|") "|"))
11416 ((eq x 'hline) "|-|")
11417 (t (error "Garbage in listtable: %s" x))))
11418 tbl "\n"))
11420 (defun org-insert-columns-dblock ()
11421 "Create a dynamic block capturing a column view table."
11422 (interactive)
11423 (let ((defaults '(:name "columnview" :hlines 1))
11424 (id (completing-read
11425 "Capture columns (local, global, entry with :ID: property) [local]: "
11426 (append '(("global") ("local"))
11427 (mapcar 'list (org-property-values "ID"))))))
11428 (if (equal id "") (setq id 'local))
11429 (if (equal id "global") (setq id 'global))
11430 (setq defaults (append defaults (list :id id)))
11431 (org-create-dblock defaults)
11432 (org-update-dblock)))
11434 ;;;; Timestamps
11436 (defvar org-last-changed-timestamp nil)
11437 (defvar org-time-was-given) ; dynamically scoped parameter
11438 (defvar org-end-time-was-given) ; dynamically scoped parameter
11439 (defvar org-ts-what) ; dynamically scoped parameter
11441 (defun org-time-stamp (arg)
11442 "Prompt for a date/time and insert a time stamp.
11443 If the user specifies a time like HH:MM, or if this command is called
11444 with a prefix argument, the time stamp will contain date and time.
11445 Otherwise, only the date will be included. All parts of a date not
11446 specified by the user will be filled in from the current date/time.
11447 So if you press just return without typing anything, the time stamp
11448 will represent the current date/time. If there is already a timestamp
11449 at the cursor, it will be modified."
11450 (interactive "P")
11451 (let* ((ts nil)
11452 (default-time
11453 ;; Default time is either today, or, when entering a range,
11454 ;; the range start.
11455 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
11456 (save-excursion
11457 (re-search-backward
11458 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
11459 (- (point) 20) t)))
11460 (apply 'encode-time (org-parse-time-string (match-string 1)))
11461 (current-time)))
11462 (default-input (and ts (org-get-compact-tod ts)))
11463 org-time-was-given org-end-time-was-given time)
11464 (cond
11465 ((and (org-at-timestamp-p)
11466 (eq last-command 'org-time-stamp)
11467 (eq this-command 'org-time-stamp))
11468 (insert "--")
11469 (setq time (let ((this-command this-command))
11470 (org-read-date arg 'totime nil nil default-time default-input)))
11471 (org-insert-time-stamp time (or org-time-was-given arg)))
11472 ((org-at-timestamp-p)
11473 (setq time (let ((this-command this-command))
11474 (org-read-date arg 'totime nil nil default-time default-input)))
11475 (when (org-at-timestamp-p) ; just to get the match data
11476 (replace-match "")
11477 (setq org-last-changed-timestamp
11478 (org-insert-time-stamp
11479 time (or org-time-was-given arg)
11480 nil nil nil (list org-end-time-was-given))))
11481 (message "Timestamp updated"))
11483 (setq time (let ((this-command this-command))
11484 (org-read-date arg 'totime nil nil default-time default-input)))
11485 (org-insert-time-stamp time (or org-time-was-given arg)
11486 nil nil nil (list org-end-time-was-given))))))
11488 ;; FIXME: can we use this for something else????
11489 ;; like computing time differences?????
11490 (defun org-get-compact-tod (s)
11491 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
11492 (let* ((t1 (match-string 1 s))
11493 (h1 (string-to-number (match-string 2 s)))
11494 (m1 (string-to-number (match-string 3 s)))
11495 (t2 (and (match-end 4) (match-string 5 s)))
11496 (h2 (and t2 (string-to-number (match-string 6 s))))
11497 (m2 (and t2 (string-to-number (match-string 7 s))))
11498 dh dm)
11499 (if (not t2)
11501 (setq dh (- h2 h1) dm (- m2 m1))
11502 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
11503 (concat t1 "+" (number-to-string dh)
11504 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
11506 (defun org-time-stamp-inactive (&optional arg)
11507 "Insert an inactive time stamp.
11508 An inactive time stamp is enclosed in square brackets instead of angle
11509 brackets. It is inactive in the sense that it does not trigger agenda entries,
11510 does not link to the calendar and cannot be changed with the S-cursor keys.
11511 So these are more for recording a certain time/date."
11512 (interactive "P")
11513 (let (org-time-was-given org-end-time-was-given time)
11514 (setq time (org-read-date arg 'totime))
11515 (org-insert-time-stamp time (or org-time-was-given arg) 'inactive
11516 nil nil (list org-end-time-was-given))))
11518 (defvar org-date-ovl (org-make-overlay 1 1))
11519 (org-overlay-put org-date-ovl 'face 'org-warning)
11520 (org-detach-overlay org-date-ovl)
11522 (defvar org-ans1) ; dynamically scoped parameter
11523 (defvar org-ans2) ; dynamically scoped parameter
11525 (defvar org-plain-time-of-day-regexp) ; defined below
11527 (defvar org-read-date-overlay nil)
11528 (defvar org-dcst nil) ; dynamically scoped
11530 (defun org-read-date (&optional with-time to-time from-string prompt
11531 default-time default-input)
11532 "Read a date, possibly a time, and make things smooth for the user.
11533 The prompt will suggest to enter an ISO date, but you can also enter anything
11534 which will at least partially be understood by `parse-time-string'.
11535 Unrecognized parts of the date will default to the current day, month, year,
11536 hour and minute. If this command is called to replace a timestamp at point,
11537 of to enter the second timestamp of a range, the default time is taken from the
11538 existing stamp. For example,
11539 3-2-5 --> 2003-02-05
11540 feb 15 --> currentyear-02-15
11541 sep 12 9 --> 2009-09-12
11542 12:45 --> today 12:45
11543 22 sept 0:34 --> currentyear-09-22 0:34
11544 12 --> currentyear-currentmonth-12
11545 Fri --> nearest Friday (today or later)
11546 etc.
11548 Furthermore you can specify a relative date by giving, as the *first* thing
11549 in the input: a plus/minus sign, a number and a letter [dwmy] to indicate
11550 change in days weeks, months, years.
11551 With a single plus or minus, the date is relative to today. With a double
11552 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
11553 +4d --> four days from today
11554 +4 --> same as above
11555 +2w --> two weeks from today
11556 ++5 --> five days from default date
11558 The function understands only English month and weekday abbreviations,
11559 but this can be configured with the variables `parse-time-months' and
11560 `parse-time-weekdays'.
11562 While prompting, a calendar is popped up - you can also select the
11563 date with the mouse (button 1). The calendar shows a period of three
11564 months. To scroll it to other months, use the keys `>' and `<'.
11565 If you don't like the calendar, turn it off with
11566 \(setq org-read-date-popup-calendar nil)
11568 With optional argument TO-TIME, the date will immediately be converted
11569 to an internal time.
11570 With an optional argument WITH-TIME, the prompt will suggest to also
11571 insert a time. Note that when WITH-TIME is not set, you can still
11572 enter a time, and this function will inform the calling routine about
11573 this change. The calling routine may then choose to change the format
11574 used to insert the time stamp into the buffer to include the time.
11575 With optional argument FROM-STRING, read from this string instead from
11576 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
11577 the time/date that is used for everything that is not specified by the
11578 user."
11579 (require 'parse-time)
11580 (let* ((org-time-stamp-rounding-minutes
11581 (if (equal with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
11582 (org-dcst org-display-custom-times)
11583 (ct (org-current-time))
11584 (def (or default-time ct))
11585 (defdecode (decode-time def))
11586 (dummy (progn
11587 (when (< (nth 2 defdecode) org-extend-today-until)
11588 (setcar (nthcdr 2 defdecode) -1)
11589 (setcar (nthcdr 1 defdecode) 59)
11590 (setq def (apply 'encode-time defdecode)
11591 defdecode (decode-time def)))))
11592 (calendar-move-hook nil)
11593 (view-diary-entries-initially nil)
11594 (view-calendar-holidays-initially nil)
11595 (timestr (format-time-string
11596 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") def))
11597 (prompt (concat (if prompt (concat prompt " ") "")
11598 (format "Date+time [%s]: " timestr)))
11599 ans (org-ans0 "") org-ans1 org-ans2 final)
11601 (cond
11602 (from-string (setq ans from-string))
11603 (org-read-date-popup-calendar
11604 (save-excursion
11605 (save-window-excursion
11606 (calendar)
11607 (calendar-forward-day (- (time-to-days def)
11608 (calendar-absolute-from-gregorian
11609 (calendar-current-date))))
11610 (org-eval-in-calendar nil t)
11611 (let* ((old-map (current-local-map))
11612 (map (copy-keymap calendar-mode-map))
11613 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
11614 (org-defkey map (kbd "RET") 'org-calendar-select)
11615 (org-defkey map (if (featurep 'xemacs) [button1] [mouse-1])
11616 'org-calendar-select-mouse)
11617 (org-defkey map (if (featurep 'xemacs) [button2] [mouse-2])
11618 'org-calendar-select-mouse)
11619 (org-defkey minibuffer-local-map [(meta shift left)]
11620 (lambda () (interactive)
11621 (org-eval-in-calendar '(calendar-backward-month 1))))
11622 (org-defkey minibuffer-local-map [(meta shift right)]
11623 (lambda () (interactive)
11624 (org-eval-in-calendar '(calendar-forward-month 1))))
11625 (org-defkey minibuffer-local-map [(meta shift up)]
11626 (lambda () (interactive)
11627 (org-eval-in-calendar '(calendar-backward-year 1))))
11628 (org-defkey minibuffer-local-map [(meta shift down)]
11629 (lambda () (interactive)
11630 (org-eval-in-calendar '(calendar-forward-year 1))))
11631 (org-defkey minibuffer-local-map [(shift up)]
11632 (lambda () (interactive)
11633 (org-eval-in-calendar '(calendar-backward-week 1))))
11634 (org-defkey minibuffer-local-map [(shift down)]
11635 (lambda () (interactive)
11636 (org-eval-in-calendar '(calendar-forward-week 1))))
11637 (org-defkey minibuffer-local-map [(shift left)]
11638 (lambda () (interactive)
11639 (org-eval-in-calendar '(calendar-backward-day 1))))
11640 (org-defkey minibuffer-local-map [(shift right)]
11641 (lambda () (interactive)
11642 (org-eval-in-calendar '(calendar-forward-day 1))))
11643 (org-defkey minibuffer-local-map ">"
11644 (lambda () (interactive)
11645 (org-eval-in-calendar '(scroll-calendar-left 1))))
11646 (org-defkey minibuffer-local-map "<"
11647 (lambda () (interactive)
11648 (org-eval-in-calendar '(scroll-calendar-right 1))))
11649 (unwind-protect
11650 (progn
11651 (use-local-map map)
11652 (add-hook 'post-command-hook 'org-read-date-display)
11653 (setq org-ans0 (read-string prompt default-input nil nil))
11654 ;; org-ans0: from prompt
11655 ;; org-ans1: from mouse click
11656 ;; org-ans2: from calendar motion
11657 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
11658 (remove-hook 'post-command-hook 'org-read-date-display)
11659 (use-local-map old-map)
11660 (when org-read-date-overlay
11661 (org-delete-overlay org-read-date-overlay)
11662 (setq org-read-date-overlay nil)))))))
11664 (t ; Naked prompt only
11665 (unwind-protect
11666 (setq ans (read-string prompt default-input nil timestr))
11667 (when org-read-date-overlay
11668 (org-delete-overlay org-read-date-overlay)
11669 (setq org-read-date-overlay nil)))))
11671 (setq final (org-read-date-analyze ans def defdecode))
11673 (if to-time
11674 (apply 'encode-time final)
11675 (if (and (boundp 'org-time-was-given) org-time-was-given)
11676 (format "%04d-%02d-%02d %02d:%02d"
11677 (nth 5 final) (nth 4 final) (nth 3 final)
11678 (nth 2 final) (nth 1 final))
11679 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
11680 (defvar def)
11681 (defvar defdecode)
11682 (defvar with-time)
11683 (defun org-read-date-display ()
11684 "Display the currrent date prompt interpretation in the minibuffer."
11685 (when org-read-date-display-live
11686 (when org-read-date-overlay
11687 (org-delete-overlay org-read-date-overlay))
11688 (let ((p (point)))
11689 (end-of-line 1)
11690 (while (not (equal (buffer-substring
11691 (max (point-min) (- (point) 4)) (point))
11692 " "))
11693 (insert " "))
11694 (goto-char p))
11695 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
11696 " " (or org-ans1 org-ans2)))
11697 (org-end-time-was-given nil)
11698 (f (org-read-date-analyze ans def defdecode))
11699 (fmts (if org-dcst
11700 org-time-stamp-custom-formats
11701 org-time-stamp-formats))
11702 (fmt (if (or with-time
11703 (and (boundp 'org-time-was-given) org-time-was-given))
11704 (cdr fmts)
11705 (car fmts)))
11706 (txt (concat "=> " (format-time-string fmt (apply 'encode-time f)))))
11707 (when (and org-end-time-was-given
11708 (string-match org-plain-time-of-day-regexp txt))
11709 (setq txt (concat (substring txt 0 (match-end 0)) "-"
11710 org-end-time-was-given
11711 (substring txt (match-end 0)))))
11712 (setq org-read-date-overlay
11713 (make-overlay (1- (point-at-eol)) (point-at-eol)))
11714 (org-overlay-display org-read-date-overlay txt 'secondary-selection))))
11716 (defun org-read-date-analyze (ans def defdecode)
11717 "Analyze the combined answer of the date prompt."
11718 ;; FIXME: cleanup and comment
11719 (let (delta deltan deltaw deltadef year month day
11720 hour minute second wday pm h2 m2 tl wday1
11721 iso-year iso-weekday iso-week iso-year iso-date)
11723 (when (setq delta (org-read-date-get-relative ans (current-time) def))
11724 (setq ans (replace-match "" t t ans)
11725 deltan (car delta)
11726 deltaw (nth 1 delta)
11727 deltadef (nth 2 delta)))
11729 ;; Check if there is an iso week date in there
11730 ;; If yes, sore the info and ostpone interpreting it until the rest
11731 ;; of the parsing is done
11732 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
11733 (setq iso-year (if (match-end 1) (org-small-year-to-year (string-to-number (match-string 1 ans))))
11734 iso-weekday (if (match-end 3) (string-to-number (match-string 3 ans)))
11735 iso-week (string-to-number (match-string 2 ans)))
11736 (setq ans (replace-match "" t t ans)))
11738 ;; Help matching ISO dates with single digit month ot day, like 2006-8-11.
11739 (when (string-match
11740 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
11741 (setq year (if (match-end 2)
11742 (string-to-number (match-string 2 ans))
11743 (string-to-number (format-time-string "%Y")))
11744 month (string-to-number (match-string 3 ans))
11745 day (string-to-number (match-string 4 ans)))
11746 (if (< year 100) (setq year (+ 2000 year)))
11747 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
11748 t nil ans)))
11749 ;; Help matching am/pm times, because `parse-time-string' does not do that.
11750 ;; If there is a time with am/pm, and *no* time without it, we convert
11751 ;; so that matching will be successful.
11752 (loop for i from 1 to 2 do ; twice, for end time as well
11753 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
11754 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
11755 (setq hour (string-to-number (match-string 1 ans))
11756 minute (if (match-end 3)
11757 (string-to-number (match-string 3 ans))
11759 pm (equal ?p
11760 (string-to-char (downcase (match-string 4 ans)))))
11761 (if (and (= hour 12) (not pm))
11762 (setq hour 0)
11763 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
11764 (setq ans (replace-match (format "%02d:%02d" hour minute)
11765 t t ans))))
11767 ;; Check if a time range is given as a duration
11768 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
11769 (setq hour (string-to-number (match-string 1 ans))
11770 h2 (+ hour (string-to-number (match-string 3 ans)))
11771 minute (string-to-number (match-string 2 ans))
11772 m2 (+ minute (if (match-end 5) (string-to-number
11773 (match-string 5 ans))0)))
11774 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
11775 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
11776 t t ans)))
11778 ;; Check if there is a time range
11779 (when (boundp 'org-end-time-was-given)
11780 (setq org-time-was-given nil)
11781 (when (and (string-match org-plain-time-of-day-regexp ans)
11782 (match-end 8))
11783 (setq org-end-time-was-given (match-string 8 ans))
11784 (setq ans (concat (substring ans 0 (match-beginning 7))
11785 (substring ans (match-end 7))))))
11787 (setq tl (parse-time-string ans)
11788 day (or (nth 3 tl) (nth 3 defdecode))
11789 month (or (nth 4 tl)
11790 (if (and org-read-date-prefer-future
11791 (nth 3 tl) (< (nth 3 tl) (nth 3 defdecode)))
11792 (1+ (nth 4 defdecode))
11793 (nth 4 defdecode)))
11794 year (or (nth 5 tl)
11795 (if (and org-read-date-prefer-future
11796 (nth 4 tl) (< (nth 4 tl) (nth 4 defdecode)))
11797 (1+ (nth 5 defdecode))
11798 (nth 5 defdecode)))
11799 hour (or (nth 2 tl) (nth 2 defdecode))
11800 minute (or (nth 1 tl) (nth 1 defdecode))
11801 second (or (nth 0 tl) 0)
11802 wday (nth 6 tl))
11804 ;; Special date definitions below
11805 (cond
11806 (iso-week
11807 ;; There was an iso week
11808 (setq year (or iso-year year)
11809 day (or iso-weekday wday 1)
11810 wday nil ; to make sure that the trigger below does not match
11811 iso-date (calendar-gregorian-from-absolute
11812 (calendar-absolute-from-iso
11813 (list iso-week day year))))
11814 ; FIXME: Should we also push ISO weeks into the future?
11815 ; (when (and org-read-date-prefer-future
11816 ; (not iso-year)
11817 ; (< (calendar-absolute-from-gregorian iso-date)
11818 ; (time-to-days (current-time))))
11819 ; (setq year (1+ year)
11820 ; iso-date (calendar-gregorian-from-absolute
11821 ; (calendar-absolute-from-iso
11822 ; (list iso-week day year)))))
11823 (setq month (car iso-date)
11824 year (nth 2 iso-date)
11825 day (nth 1 iso-date)))
11826 (deltan
11827 (unless deltadef
11828 (let ((now (decode-time (current-time))))
11829 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
11830 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
11831 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
11832 ((equal deltaw "m") (setq month (+ month deltan)))
11833 ((equal deltaw "y") (setq year (+ year deltan)))))
11834 ((and wday (not (nth 3 tl)))
11835 ;; Weekday was given, but no day, so pick that day in the week
11836 ;; on or after the derived date.
11837 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
11838 (unless (equal wday wday1)
11839 (setq day (+ day (% (- wday wday1 -7) 7))))))
11840 (if (and (boundp 'org-time-was-given)
11841 (nth 2 tl))
11842 (setq org-time-was-given t))
11843 (if (< year 100) (setq year (+ 2000 year)))
11844 (if (< year 1970) (setq year (nth 5 defdecode))) ; not representable
11845 (list second minute hour day month year)))
11847 (defvar parse-time-weekdays)
11849 (defun org-read-date-get-relative (s today default)
11850 "Check string S for special relative date string.
11851 TODAY and DEFAULT are internal times, for today and for a default.
11852 Return shift list (N what def-flag)
11853 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
11854 N is the number of WHATs to shift.
11855 DEF-FLAG is t when a double ++ or -- indicates shift relative to
11856 the DEFAULT date rather than TODAY."
11857 (when (string-match
11858 (concat
11859 "\\`[ \t]*\\([-+]\\{1,2\\}\\)"
11860 "\\([0-9]+\\)?"
11861 "\\([dwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
11862 "\\([ \t]\\|$\\)") s)
11863 (let* ((dir (if (match-end 1)
11864 (string-to-char (substring (match-string 1 s) -1))
11865 ?+))
11866 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
11867 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
11868 (what (if (match-end 3) (match-string 3 s) "d"))
11869 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
11870 (date (if rel default today))
11871 (wday (nth 6 (decode-time date)))
11872 delta)
11873 (if wday1
11874 (progn
11875 (setq delta (mod (+ 7 (- wday1 wday)) 7))
11876 (if (= dir ?-) (setq delta (- delta 7)))
11877 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
11878 (list delta "d" rel))
11879 (list (* n (if (= dir ?-) -1 1)) what rel)))))
11881 (defun org-eval-in-calendar (form &optional keepdate)
11882 "Eval FORM in the calendar window and return to current window.
11883 Also, store the cursor date in variable org-ans2."
11884 (let ((sw (selected-window)))
11885 (select-window (get-buffer-window "*Calendar*"))
11886 (eval form)
11887 (when (and (not keepdate) (calendar-cursor-to-date))
11888 (let* ((date (calendar-cursor-to-date))
11889 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
11890 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
11891 (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
11892 (select-window sw)))
11894 ; ;; Update the prompt to show new default date
11895 ; (save-excursion
11896 ; (goto-char (point-min))
11897 ; (when (and org-ans2
11898 ; (re-search-forward "\\[[-0-9]+\\]" nil t)
11899 ; (get-text-property (match-end 0) 'field))
11900 ; (let ((inhibit-read-only t))
11901 ; (replace-match (concat "[" org-ans2 "]") t t)
11902 ; (add-text-properties (point-min) (1+ (match-end 0))
11903 ; (text-properties-at (1+ (point-min)))))))))
11905 (defun org-calendar-select ()
11906 "Return to `org-read-date' with the date currently selected.
11907 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
11908 (interactive)
11909 (when (calendar-cursor-to-date)
11910 (let* ((date (calendar-cursor-to-date))
11911 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
11912 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
11913 (if (active-minibuffer-window) (exit-minibuffer))))
11915 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
11916 "Insert a date stamp for the date given by the internal TIME.
11917 WITH-HM means, use the stamp format that includes the time of the day.
11918 INACTIVE means use square brackets instead of angular ones, so that the
11919 stamp will not contribute to the agenda.
11920 PRE and POST are optional strings to be inserted before and after the
11921 stamp.
11922 The command returns the inserted time stamp."
11923 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
11924 stamp)
11925 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
11926 (insert-before-markers (or pre ""))
11927 (insert-before-markers (setq stamp (format-time-string fmt time)))
11928 (when (listp extra)
11929 (setq extra (car extra))
11930 (if (and (stringp extra)
11931 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
11932 (setq extra (format "-%02d:%02d"
11933 (string-to-number (match-string 1 extra))
11934 (string-to-number (match-string 2 extra))))
11935 (setq extra nil)))
11936 (when extra
11937 (backward-char 1)
11938 (insert-before-markers extra)
11939 (forward-char 1))
11940 (insert-before-markers (or post ""))
11941 stamp))
11943 (defun org-toggle-time-stamp-overlays ()
11944 "Toggle the use of custom time stamp formats."
11945 (interactive)
11946 (setq org-display-custom-times (not org-display-custom-times))
11947 (unless org-display-custom-times
11948 (let ((p (point-min)) (bmp (buffer-modified-p)))
11949 (while (setq p (next-single-property-change p 'display))
11950 (if (and (get-text-property p 'display)
11951 (eq (get-text-property p 'face) 'org-date))
11952 (remove-text-properties
11953 p (setq p (next-single-property-change p 'display))
11954 '(display t))))
11955 (set-buffer-modified-p bmp)))
11956 (if (featurep 'xemacs)
11957 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
11958 (org-restart-font-lock)
11959 (setq org-table-may-need-update t)
11960 (if org-display-custom-times
11961 (message "Time stamps are overlayed with custom format")
11962 (message "Time stamp overlays removed")))
11964 (defun org-display-custom-time (beg end)
11965 "Overlay modified time stamp format over timestamp between BED and END."
11966 (let* ((ts (buffer-substring beg end))
11967 t1 w1 with-hm tf time str w2 (off 0))
11968 (save-match-data
11969 (setq t1 (org-parse-time-string ts t))
11970 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[dwmy]\\)?\\'" ts)
11971 (setq off (- (match-end 0) (match-beginning 0)))))
11972 (setq end (- end off))
11973 (setq w1 (- end beg)
11974 with-hm (and (nth 1 t1) (nth 2 t1))
11975 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
11976 time (org-fix-decoded-time t1)
11977 str (org-add-props
11978 (format-time-string
11979 (substring tf 1 -1) (apply 'encode-time time))
11980 nil 'mouse-face 'highlight)
11981 w2 (length str))
11982 (if (not (= w2 w1))
11983 (add-text-properties (1+ beg) (+ 2 beg)
11984 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
11985 (if (featurep 'xemacs)
11986 (progn
11987 (put-text-property beg end 'invisible t)
11988 (put-text-property beg end 'end-glyph (make-glyph str)))
11989 (put-text-property beg end 'display str))))
11991 (defun org-translate-time (string)
11992 "Translate all timestamps in STRING to custom format.
11993 But do this only if the variable `org-display-custom-times' is set."
11994 (when org-display-custom-times
11995 (save-match-data
11996 (let* ((start 0)
11997 (re org-ts-regexp-both)
11998 t1 with-hm inactive tf time str beg end)
11999 (while (setq start (string-match re string start))
12000 (setq beg (match-beginning 0)
12001 end (match-end 0)
12002 t1 (save-match-data
12003 (org-parse-time-string (substring string beg end) t))
12004 with-hm (and (nth 1 t1) (nth 2 t1))
12005 inactive (equal (substring string beg (1+ beg)) "[")
12006 tf (funcall (if with-hm 'cdr 'car)
12007 org-time-stamp-custom-formats)
12008 time (org-fix-decoded-time t1)
12009 str (format-time-string
12010 (concat
12011 (if inactive "[" "<") (substring tf 1 -1)
12012 (if inactive "]" ">"))
12013 (apply 'encode-time time))
12014 string (replace-match str t t string)
12015 start (+ start (length str)))))))
12016 string)
12018 (defun org-fix-decoded-time (time)
12019 "Set 0 instead of nil for the first 6 elements of time.
12020 Don't touch the rest."
12021 (let ((n 0))
12022 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
12024 (defun org-days-to-time (timestamp-string)
12025 "Difference between TIMESTAMP-STRING and now in days."
12026 (- (time-to-days (org-time-string-to-time timestamp-string))
12027 (time-to-days (current-time))))
12029 (defun org-deadline-close (timestamp-string &optional ndays)
12030 "Is the time in TIMESTAMP-STRING close to the current date?"
12031 (setq ndays (or ndays (org-get-wdays timestamp-string)))
12032 (and (< (org-days-to-time timestamp-string) ndays)
12033 (not (org-entry-is-done-p))))
12035 (defun org-get-wdays (ts)
12036 "Get the deadline lead time appropriate for timestring TS."
12037 (cond
12038 ((<= org-deadline-warning-days 0)
12039 ;; 0 or negative, enforce this value no matter what
12040 (- org-deadline-warning-days))
12041 ((string-match "-\\([0-9]+\\)\\([dwmy]\\)\\(\\'\\|>\\)" ts)
12042 ;; lead time is specified.
12043 (floor (* (string-to-number (match-string 1 ts))
12044 (cdr (assoc (match-string 2 ts)
12045 '(("d" . 1) ("w" . 7)
12046 ("m" . 30.4) ("y" . 365.25)))))))
12047 ;; go for the default.
12048 (t org-deadline-warning-days)))
12050 (defun org-calendar-select-mouse (ev)
12051 "Return to `org-read-date' with the date currently selected.
12052 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
12053 (interactive "e")
12054 (mouse-set-point ev)
12055 (when (calendar-cursor-to-date)
12056 (let* ((date (calendar-cursor-to-date))
12057 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
12058 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
12059 (if (active-minibuffer-window) (exit-minibuffer))))
12061 (defun org-check-deadlines (ndays)
12062 "Check if there are any deadlines due or past due.
12063 A deadline is considered due if it happens within `org-deadline-warning-days'
12064 days from today's date. If the deadline appears in an entry marked DONE,
12065 it is not shown. The prefix arg NDAYS can be used to test that many
12066 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
12067 (interactive "P")
12068 (let* ((org-warn-days
12069 (cond
12070 ((equal ndays '(4)) 100000)
12071 (ndays (prefix-numeric-value ndays))
12072 (t (abs org-deadline-warning-days))))
12073 (case-fold-search nil)
12074 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
12075 (callback
12076 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
12078 (message "%d deadlines past-due or due within %d days"
12079 (org-occur regexp nil callback)
12080 org-warn-days)))
12082 (defun org-check-before-date (date)
12083 "Check if there are deadlines or scheduled entries before DATE."
12084 (interactive (list (org-read-date)))
12085 (let ((case-fold-search nil)
12086 (regexp (concat "\\<\\(" org-deadline-string
12087 "\\|" org-scheduled-string
12088 "\\) *<\\([^>]+\\)>"))
12089 (callback
12090 (lambda () (time-less-p
12091 (org-time-string-to-time (match-string 2))
12092 (org-time-string-to-time date)))))
12093 (message "%d entries before %s"
12094 (org-occur regexp nil callback) date)))
12096 (defun org-evaluate-time-range (&optional to-buffer)
12097 "Evaluate a time range by computing the difference between start and end.
12098 Normally the result is just printed in the echo area, but with prefix arg
12099 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
12100 If the time range is actually in a table, the result is inserted into the
12101 next column.
12102 For time difference computation, a year is assumed to be exactly 365
12103 days in order to avoid rounding problems."
12104 (interactive "P")
12106 (org-clock-update-time-maybe)
12107 (save-excursion
12108 (unless (org-at-date-range-p t)
12109 (goto-char (point-at-bol))
12110 (re-search-forward org-tr-regexp-both (point-at-eol) t))
12111 (if (not (org-at-date-range-p t))
12112 (error "Not at a time-stamp range, and none found in current line")))
12113 (let* ((ts1 (match-string 1))
12114 (ts2 (match-string 2))
12115 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
12116 (match-end (match-end 0))
12117 (time1 (org-time-string-to-time ts1))
12118 (time2 (org-time-string-to-time ts2))
12119 (t1 (time-to-seconds time1))
12120 (t2 (time-to-seconds time2))
12121 (diff (abs (- t2 t1)))
12122 (negative (< (- t2 t1) 0))
12123 ;; (ys (floor (* 365 24 60 60)))
12124 (ds (* 24 60 60))
12125 (hs (* 60 60))
12126 (fy "%dy %dd %02d:%02d")
12127 (fy1 "%dy %dd")
12128 (fd "%dd %02d:%02d")
12129 (fd1 "%dd")
12130 (fh "%02d:%02d")
12131 y d h m align)
12132 (if havetime
12133 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
12135 d (floor (/ diff ds)) diff (mod diff ds)
12136 h (floor (/ diff hs)) diff (mod diff hs)
12137 m (floor (/ diff 60)))
12138 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
12140 d (floor (+ (/ diff ds) 0.5))
12141 h 0 m 0))
12142 (if (not to-buffer)
12143 (message "%s" (org-make-tdiff-string y d h m))
12144 (if (org-at-table-p)
12145 (progn
12146 (goto-char match-end)
12147 (setq align t)
12148 (and (looking-at " *|") (goto-char (match-end 0))))
12149 (goto-char match-end))
12150 (if (looking-at
12151 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
12152 (replace-match ""))
12153 (if negative (insert " -"))
12154 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
12155 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
12156 (insert " " (format fh h m))))
12157 (if align (org-table-align))
12158 (message "Time difference inserted")))))
12160 (defun org-make-tdiff-string (y d h m)
12161 (let ((fmt "")
12162 (l nil))
12163 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
12164 l (push y l)))
12165 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
12166 l (push d l)))
12167 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
12168 l (push h l)))
12169 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
12170 l (push m l)))
12171 (apply 'format fmt (nreverse l))))
12173 (defun org-time-string-to-time (s)
12174 (apply 'encode-time (org-parse-time-string s)))
12176 (defun org-time-string-to-absolute (s &optional daynr prefer show-all)
12177 "Convert a time stamp to an absolute day number.
12178 If there is a specifyer for a cyclic time stamp, get the closest date to
12179 DAYNR.
12180 PREFER and SHOW_ALL are passed through to `org-closest-date'."
12181 (cond
12182 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
12183 (if (org-diary-sexp-entry (match-string 1 s) "" date)
12184 daynr
12185 (+ daynr 1000)))
12186 ((and daynr (string-match "\\+[0-9]+[dwmy]" s))
12187 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
12188 (time-to-days (current-time))) (match-string 0 s)
12189 prefer show-all))
12190 (t (time-to-days (apply 'encode-time (org-parse-time-string s))))))
12192 (defun org-time-from-absolute (d)
12193 "Return the time corresponding to date D.
12194 D may be an absolute day number, or a calendar-type list (month day year)."
12195 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
12196 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
12198 (defun org-calendar-holiday ()
12199 "List of holidays, for Diary display in Org-mode."
12200 (require 'holidays)
12201 (let ((hl (funcall
12202 (if (fboundp 'calendar-check-holidays)
12203 'calendar-check-holidays 'check-calendar-holidays) date)))
12204 (if hl (mapconcat 'identity hl "; "))))
12206 (defun org-diary-sexp-entry (sexp entry date)
12207 "Process a SEXP diary ENTRY for DATE."
12208 (require 'diary-lib)
12209 (let ((result (if calendar-debug-sexp
12210 (let ((stack-trace-on-error t))
12211 (eval (car (read-from-string sexp))))
12212 (condition-case nil
12213 (eval (car (read-from-string sexp)))
12214 (error
12215 (beep)
12216 (message "Bad sexp at line %d in %s: %s"
12217 (org-current-line)
12218 (buffer-file-name) sexp)
12219 (sleep-for 2))))))
12220 (cond ((stringp result) result)
12221 ((and (consp result)
12222 (stringp (cdr result))) (cdr result))
12223 (result entry)
12224 (t nil))))
12226 (defun org-diary-to-ical-string (frombuf)
12227 "Get iCalendar entries from diary entries in buffer FROMBUF.
12228 This uses the icalendar.el library."
12229 (let* ((tmpdir (if (featurep 'xemacs)
12230 (temp-directory)
12231 temporary-file-directory))
12232 (tmpfile (make-temp-name
12233 (expand-file-name "orgics" tmpdir)))
12234 buf rtn b e)
12235 (save-excursion
12236 (set-buffer frombuf)
12237 (icalendar-export-region (point-min) (point-max) tmpfile)
12238 (setq buf (find-buffer-visiting tmpfile))
12239 (set-buffer buf)
12240 (goto-char (point-min))
12241 (if (re-search-forward "^BEGIN:VEVENT" nil t)
12242 (setq b (match-beginning 0)))
12243 (goto-char (point-max))
12244 (if (re-search-backward "^END:VEVENT" nil t)
12245 (setq e (match-end 0)))
12246 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
12247 (kill-buffer buf)
12248 (kill-buffer frombuf)
12249 (delete-file tmpfile)
12250 rtn))
12252 (defun org-closest-date (start current change prefer show-all)
12253 "Find the date closest to CURRENT that is consistent with START and CHANGE.
12254 When PREFER is `past' return a date that is either CURRENT or past.
12255 When PREFER is `future', return a date that is either CURRENT or future.
12256 When SHOW-ALL is nil, only return the current occurence of a time stamp."
12257 ;; Make the proper lists from the dates
12258 (catch 'exit
12259 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
12260 dn dw sday cday n1 n2
12261 d m y y1 y2 date1 date2 nmonths nm ny m2)
12263 (setq start (org-date-to-gregorian start)
12264 current (org-date-to-gregorian
12265 (if show-all
12266 current
12267 (time-to-days (current-time))))
12268 sday (calendar-absolute-from-gregorian start)
12269 cday (calendar-absolute-from-gregorian current))
12271 (if (<= cday sday) (throw 'exit sday))
12273 (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
12274 (setq dn (string-to-number (match-string 1 change))
12275 dw (cdr (assoc (match-string 2 change) a1)))
12276 (error "Invalid change specifyer: %s" change))
12277 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
12278 (cond
12279 ((eq dw 'day)
12280 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
12281 n2 (+ n1 dn)))
12282 ((eq dw 'year)
12283 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
12284 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
12285 (setq date1 (list m d y1)
12286 n1 (calendar-absolute-from-gregorian date1)
12287 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
12288 n2 (calendar-absolute-from-gregorian date2)))
12289 ((eq dw 'month)
12290 ;; approx number of month between the tow dates
12291 (setq nmonths (floor (/ (- cday sday) 30.436875)))
12292 ;; How often does dn fit in there?
12293 (setq d (nth 1 start) m (car start) y (nth 2 start)
12294 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
12295 m (+ m nm)
12296 ny (floor (/ m 12))
12297 y (+ y ny)
12298 m (- m (* ny 12)))
12299 (while (> m 12) (setq m (- m 12) y (1+ y)))
12300 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
12301 (setq m2 (+ m dn) y2 y)
12302 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
12303 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
12304 (while (< n2 cday)
12305 (setq n1 n2 m m2 y y2)
12306 (setq m2 (+ m dn) y2 y)
12307 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
12308 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
12310 (if show-all
12311 (cond
12312 ((eq prefer 'past) n1)
12313 ((eq prefer 'future) (if (= cday n1) n1 n2))
12314 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
12315 (cond
12316 ((eq prefer 'past) n1)
12317 ((eq prefer 'future) (if (= cday n1) n1 n2))
12318 (t (if (= cday n1) n1 n2)))))))
12320 (defun org-date-to-gregorian (date)
12321 "Turn any specification of DATE into a gregorian date for the calendar."
12322 (cond ((integerp date) (calendar-gregorian-from-absolute date))
12323 ((and (listp date) (= (length date) 3)) date)
12324 ((stringp date)
12325 (setq date (org-parse-time-string date))
12326 (list (nth 4 date) (nth 3 date) (nth 5 date)))
12327 ((listp date)
12328 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
12330 (defun org-parse-time-string (s &optional nodefault)
12331 "Parse the standard Org-mode time string.
12332 This should be a lot faster than the normal `parse-time-string'.
12333 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
12334 hour and minute fields will be nil if not given."
12335 (if (string-match org-ts-regexp0 s)
12336 (list 0
12337 (if (or (match-beginning 8) (not nodefault))
12338 (string-to-number (or (match-string 8 s) "0")))
12339 (if (or (match-beginning 7) (not nodefault))
12340 (string-to-number (or (match-string 7 s) "0")))
12341 (string-to-number (match-string 4 s))
12342 (string-to-number (match-string 3 s))
12343 (string-to-number (match-string 2 s))
12344 nil nil nil)
12345 (make-list 9 0)))
12347 (defun org-timestamp-up (&optional arg)
12348 "Increase the date item at the cursor by one.
12349 If the cursor is on the year, change the year. If it is on the month or
12350 the day, change that.
12351 With prefix ARG, change by that many units."
12352 (interactive "p")
12353 (org-timestamp-change (prefix-numeric-value arg)))
12355 (defun org-timestamp-down (&optional arg)
12356 "Decrease the date item at the cursor by one.
12357 If the cursor is on the year, change the year. If it is on the month or
12358 the day, change that.
12359 With prefix ARG, change by that many units."
12360 (interactive "p")
12361 (org-timestamp-change (- (prefix-numeric-value arg))))
12363 (defun org-timestamp-up-day (&optional arg)
12364 "Increase the date in the time stamp by one day.
12365 With prefix ARG, change that many days."
12366 (interactive "p")
12367 (if (and (not (org-at-timestamp-p t))
12368 (org-on-heading-p))
12369 (org-todo 'up)
12370 (org-timestamp-change (prefix-numeric-value arg) 'day)))
12372 (defun org-timestamp-down-day (&optional arg)
12373 "Decrease the date in the time stamp by one day.
12374 With prefix ARG, change that many days."
12375 (interactive "p")
12376 (if (and (not (org-at-timestamp-p t))
12377 (org-on-heading-p))
12378 (org-todo 'down)
12379 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
12381 (defun org-at-timestamp-p (&optional inactive-ok)
12382 "Determine if the cursor is in or at a timestamp."
12383 (interactive)
12384 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
12385 (pos (point))
12386 (ans (or (looking-at tsr)
12387 (save-excursion
12388 (skip-chars-backward "^[<\n\r\t")
12389 (if (> (point) (point-min)) (backward-char 1))
12390 (and (looking-at tsr)
12391 (> (- (match-end 0) pos) -1))))))
12392 (and ans
12393 (boundp 'org-ts-what)
12394 (setq org-ts-what
12395 (cond
12396 ((= pos (match-beginning 0)) 'bracket)
12397 ((= pos (1- (match-end 0))) 'bracket)
12398 ((org-pos-in-match-range pos 2) 'year)
12399 ((org-pos-in-match-range pos 3) 'month)
12400 ((org-pos-in-match-range pos 7) 'hour)
12401 ((org-pos-in-match-range pos 8) 'minute)
12402 ((or (org-pos-in-match-range pos 4)
12403 (org-pos-in-match-range pos 5)) 'day)
12404 ((and (> pos (or (match-end 8) (match-end 5)))
12405 (< pos (match-end 0)))
12406 (- pos (or (match-end 8) (match-end 5))))
12407 (t 'day))))
12408 ans))
12410 (defun org-toggle-timestamp-type ()
12411 "Toggle the type (<active> or [inactive]) of a time stamp."
12412 (interactive)
12413 (when (org-at-timestamp-p t)
12414 (save-excursion
12415 (goto-char (match-beginning 0))
12416 (insert (if (equal (char-after) ?<) "[" "<")) (delete-char 1)
12417 (goto-char (1- (match-end 0)))
12418 (insert (if (equal (char-after) ?>) "]" ">")) (delete-char 1))
12419 (message "Timestamp is now %sactive"
12420 (if (equal (char-before) ?>) "in" ""))))
12422 (defun org-timestamp-change (n &optional what)
12423 "Change the date in the time stamp at point.
12424 The date will be changed by N times WHAT. WHAT can be `day', `month',
12425 `year', `minute', `second'. If WHAT is not given, the cursor position
12426 in the timestamp determines what will be changed."
12427 (let ((pos (point))
12428 with-hm inactive
12429 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
12430 org-ts-what
12431 extra rem
12432 ts time time0)
12433 (if (not (org-at-timestamp-p t))
12434 (error "Not at a timestamp"))
12435 (if (and (not what) (eq org-ts-what 'bracket))
12436 (org-toggle-timestamp-type)
12437 (if (and (not what) (not (eq org-ts-what 'day))
12438 org-display-custom-times
12439 (get-text-property (point) 'display)
12440 (not (get-text-property (1- (point)) 'display)))
12441 (setq org-ts-what 'day))
12442 (setq org-ts-what (or what org-ts-what)
12443 inactive (= (char-after (match-beginning 0)) ?\[)
12444 ts (match-string 0))
12445 (replace-match "")
12446 (if (string-match
12447 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[dwmy]\\)*\\)[]>]"
12449 (setq extra (match-string 1 ts)))
12450 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
12451 (setq with-hm t))
12452 (setq time0 (org-parse-time-string ts))
12453 (when (and (eq org-ts-what 'minute)
12454 (eq current-prefix-arg nil))
12455 (setq n (* dm (org-no-warnings (signum n))))
12456 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
12457 (setcar (cdr time0) (+ (nth 1 time0)
12458 (if (> n 0) (- rem) (- dm rem))))))
12459 (setq time
12460 (encode-time (or (car time0) 0)
12461 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
12462 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
12463 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
12464 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
12465 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
12466 (nthcdr 6 time0)))
12467 (when (integerp org-ts-what)
12468 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
12469 (if (eq what 'calendar)
12470 (let ((cal-date (org-get-date-from-calendar)))
12471 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
12472 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
12473 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
12474 (setcar time0 (or (car time0) 0))
12475 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
12476 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
12477 (setq time (apply 'encode-time time0))))
12478 (setq org-last-changed-timestamp
12479 (org-insert-time-stamp time with-hm inactive nil nil extra))
12480 (org-clock-update-time-maybe)
12481 (goto-char pos)
12482 ;; Try to recenter the calendar window, if any
12483 (if (and org-calendar-follow-timestamp-change
12484 (get-buffer-window "*Calendar*" t)
12485 (memq org-ts-what '(day month year)))
12486 (org-recenter-calendar (time-to-days time))))))
12488 ;; FIXME: does not yet work for lead times
12489 (defun org-modify-ts-extra (s pos n dm)
12490 "Change the different parts of the lead-time and repeat fields in timestamp."
12491 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
12492 ng h m new rem)
12493 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
12494 (cond
12495 ((or (org-pos-in-match-range pos 2)
12496 (org-pos-in-match-range pos 3))
12497 (setq m (string-to-number (match-string 3 s))
12498 h (string-to-number (match-string 2 s)))
12499 (if (org-pos-in-match-range pos 2)
12500 (setq h (+ h n))
12501 (setq n (* dm (org-no-warnings (signum n))))
12502 (when (not (= 0 (setq rem (% m dm))))
12503 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
12504 (setq m (+ m n)))
12505 (if (< m 0) (setq m (+ m 60) h (1- h)))
12506 (if (> m 59) (setq m (- m 60) h (1+ h)))
12507 (setq h (min 24 (max 0 h)))
12508 (setq ng 1 new (format "-%02d:%02d" h m)))
12509 ((org-pos-in-match-range pos 6)
12510 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
12511 ((org-pos-in-match-range pos 5)
12512 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
12514 ((org-pos-in-match-range pos 9)
12515 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
12516 ((org-pos-in-match-range pos 8)
12517 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
12519 (when ng
12520 (setq s (concat
12521 (substring s 0 (match-beginning ng))
12523 (substring s (match-end ng))))))
12526 (defun org-recenter-calendar (date)
12527 "If the calendar is visible, recenter it to DATE."
12528 (let* ((win (selected-window))
12529 (cwin (get-buffer-window "*Calendar*" t))
12530 (calendar-move-hook nil))
12531 (when cwin
12532 (select-window cwin)
12533 (calendar-goto-date (if (listp date) date
12534 (calendar-gregorian-from-absolute date)))
12535 (select-window win))))
12537 (defun org-goto-calendar (&optional arg)
12538 "Go to the Emacs calendar at the current date.
12539 If there is a time stamp in the current line, go to that date.
12540 A prefix ARG can be used to force the current date."
12541 (interactive "P")
12542 (let ((tsr org-ts-regexp) diff
12543 (calendar-move-hook nil)
12544 (view-calendar-holidays-initially nil)
12545 (view-diary-entries-initially nil))
12546 (if (or (org-at-timestamp-p)
12547 (save-excursion
12548 (beginning-of-line 1)
12549 (looking-at (concat ".*" tsr))))
12550 (let ((d1 (time-to-days (current-time)))
12551 (d2 (time-to-days
12552 (org-time-string-to-time (match-string 1)))))
12553 (setq diff (- d2 d1))))
12554 (calendar)
12555 (calendar-goto-today)
12556 (if (and diff (not arg)) (calendar-forward-day diff))))
12558 (defun org-get-date-from-calendar ()
12559 "Return a list (month day year) of date at point in calendar."
12560 (with-current-buffer "*Calendar*"
12561 (save-match-data
12562 (calendar-cursor-to-date))))
12564 (defun org-date-from-calendar ()
12565 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
12566 If there is already a time stamp at the cursor position, update it."
12567 (interactive)
12568 (if (org-at-timestamp-p t)
12569 (org-timestamp-change 0 'calendar)
12570 (let ((cal-date (org-get-date-from-calendar)))
12571 (org-insert-time-stamp
12572 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
12574 ;;; The clock for measuring work time.
12576 (defvar org-mode-line-string "")
12577 (put 'org-mode-line-string 'risky-local-variable t)
12579 (defvar org-mode-line-timer nil)
12580 (defvar org-clock-heading "")
12581 (defvar org-clock-start-time "")
12583 (defun org-update-mode-line ()
12584 (let* ((delta (- (time-to-seconds (current-time))
12585 (time-to-seconds org-clock-start-time)))
12586 (h (floor delta 3600))
12587 (m (floor (- delta (* 3600 h)) 60)))
12588 (setq org-mode-line-string
12589 (propertize (format "-[%d:%02d (%s)]" h m org-clock-heading)
12590 'help-echo "Org-mode clock is running"))
12591 (force-mode-line-update)))
12593 (defvar org-clock-marker (make-marker)
12594 "Marker recording the last clock-in.")
12595 (defvar org-clock-mode-line-entry nil
12596 "Information for the modeline about the running clock.")
12598 (defun org-clock-in ()
12599 "Start the clock on the current item.
12600 If necessary, clock-out of the currently active clock."
12601 (interactive)
12602 (org-clock-out t)
12603 (let (ts)
12604 (save-excursion
12605 (org-back-to-heading t)
12606 (when (and org-clock-in-switch-to-state
12607 (not (looking-at (concat outline-regexp "[ \t]*"
12608 org-clock-in-switch-to-state
12609 "\\>"))))
12610 (org-todo org-clock-in-switch-to-state))
12611 (if (and org-clock-heading-function
12612 (functionp org-clock-heading-function))
12613 (setq org-clock-heading (funcall org-clock-heading-function))
12614 (if (looking-at org-complex-heading-regexp)
12615 (setq org-clock-heading (match-string 4))
12616 (setq org-clock-heading "???")))
12617 (setq org-clock-heading (propertize org-clock-heading 'face nil))
12618 (org-clock-find-position)
12620 (insert "\n") (backward-char 1)
12621 (indent-relative)
12622 (insert org-clock-string " ")
12623 (setq org-clock-start-time (current-time))
12624 (setq ts (org-insert-time-stamp (current-time) 'with-hm 'inactive))
12625 (move-marker org-clock-marker (point) (buffer-base-buffer))
12626 (or global-mode-string (setq global-mode-string '("")))
12627 (or (memq 'org-mode-line-string global-mode-string)
12628 (setq global-mode-string
12629 (append global-mode-string '(org-mode-line-string))))
12630 (org-update-mode-line)
12631 (setq org-mode-line-timer (run-with-timer 60 60 'org-update-mode-line))
12632 (message "Clock started at %s" ts))))
12634 (defun org-clock-find-position ()
12635 "Find the location where the next clock line should be inserted."
12636 (org-back-to-heading t)
12637 (catch 'exit
12638 (let ((beg (save-excursion
12639 (beginning-of-line 2)
12640 (or (bolp) (newline))
12641 (point)))
12642 (end (progn (outline-next-heading) (point)))
12643 (re (concat "^[ \t]*" org-clock-string))
12644 (cnt 0)
12645 first last)
12646 (goto-char beg)
12647 (when (eobp) (newline) (setq end (max (point) end)))
12648 (when (re-search-forward "^[ \t]*:CLOCK:" end t)
12649 ;; we seem to have a CLOCK drawer, so go there.
12650 (beginning-of-line 2)
12651 (throw 'exit t))
12652 ;; Lets count the CLOCK lines
12653 (goto-char beg)
12654 (while (re-search-forward re end t)
12655 (setq first (or first (match-beginning 0))
12656 last (match-beginning 0)
12657 cnt (1+ cnt)))
12658 (when (and (integerp org-clock-into-drawer)
12659 (>= (1+ cnt) org-clock-into-drawer))
12660 ;; Wrap current entries into a new drawer
12661 (goto-char last)
12662 (beginning-of-line 2)
12663 (if (org-at-item-p) (org-end-of-item))
12664 (insert ":END:\n")
12665 (beginning-of-line 0)
12666 (org-indent-line-function)
12667 (goto-char first)
12668 (insert ":CLOCK:\n")
12669 (beginning-of-line 0)
12670 (org-indent-line-function)
12671 (org-flag-drawer t)
12672 (beginning-of-line 2)
12673 (throw 'exit nil))
12675 (goto-char beg)
12676 (while (and (looking-at (concat "[ \t]*" org-keyword-time-regexp))
12677 (not (equal (match-string 1) org-clock-string)))
12678 ;; Planning info, skip to after it
12679 (beginning-of-line 2)
12680 (or (bolp) (newline)))
12681 (when (eq t org-clock-into-drawer)
12682 (insert ":CLOCK:\n:END:\n")
12683 (beginning-of-line -1)
12684 (org-indent-line-function)
12685 (org-flag-drawer t)
12686 (beginning-of-line 2)
12687 (org-indent-line-function)))))
12689 (defun org-clock-out (&optional fail-quietly)
12690 "Stop the currently running clock.
12691 If there is no running clock, throw an error, unless FAIL-QUIETLY is set."
12692 (interactive)
12693 (catch 'exit
12694 (if (not (marker-buffer org-clock-marker))
12695 (if fail-quietly (throw 'exit t) (error "No active clock")))
12696 (let (ts te s h m)
12697 (save-excursion
12698 (set-buffer (marker-buffer org-clock-marker))
12699 (goto-char org-clock-marker)
12700 (beginning-of-line 1)
12701 (if (and (looking-at (concat "[ \t]*" org-keyword-time-regexp))
12702 (equal (match-string 1) org-clock-string))
12703 (setq ts (match-string 2))
12704 (if fail-quietly (throw 'exit nil) (error "Clock start time is gone")))
12705 (goto-char (match-end 0))
12706 (delete-region (point) (point-at-eol))
12707 (insert "--")
12708 (setq te (org-insert-time-stamp (current-time) 'with-hm 'inactive))
12709 (setq s (- (time-to-seconds (apply 'encode-time (org-parse-time-string te)))
12710 (time-to-seconds (apply 'encode-time (org-parse-time-string ts))))
12711 h (floor (/ s 3600))
12712 s (- s (* 3600 h))
12713 m (floor (/ s 60))
12714 s (- s (* 60 s)))
12715 (insert " => " (format "%2d:%02d" h m))
12716 (move-marker org-clock-marker nil)
12717 (when org-log-note-clock-out
12718 (org-add-log-setup 'clock-out))
12719 (when org-mode-line-timer
12720 (cancel-timer org-mode-line-timer)
12721 (setq org-mode-line-timer nil))
12722 (setq global-mode-string
12723 (delq 'org-mode-line-string global-mode-string))
12724 (force-mode-line-update)
12725 (message "Clock stopped at %s after HH:MM = %d:%02d" te h m)))))
12727 (defun org-clock-cancel ()
12728 "Cancel the running clock be removing the start timestamp."
12729 (interactive)
12730 (if (not (marker-buffer org-clock-marker))
12731 (error "No active clock"))
12732 (save-excursion
12733 (set-buffer (marker-buffer org-clock-marker))
12734 (goto-char org-clock-marker)
12735 (delete-region (1- (point-at-bol)) (point-at-eol)))
12736 (setq global-mode-string
12737 (delq 'org-mode-line-string global-mode-string))
12738 (force-mode-line-update)
12739 (message "Clock canceled"))
12741 (defun org-clock-goto (&optional delete-windows)
12742 "Go to the currently clocked-in entry."
12743 (interactive "P")
12744 (if (not (marker-buffer org-clock-marker))
12745 (error "No active clock"))
12746 (switch-to-buffer-other-window
12747 (marker-buffer org-clock-marker))
12748 (if delete-windows (delete-other-windows))
12749 (goto-char org-clock-marker)
12750 (org-show-entry)
12751 (org-back-to-heading)
12752 (recenter))
12754 (defvar org-clock-file-total-minutes nil
12755 "Holds the file total time in minutes, after a call to `org-clock-sum'.")
12756 (make-variable-buffer-local 'org-clock-file-total-minutes)
12758 (defun org-clock-sum (&optional tstart tend)
12759 "Sum the times for each subtree.
12760 Puts the resulting times in minutes as a text property on each headline."
12761 (interactive)
12762 (let* ((bmp (buffer-modified-p))
12763 (re (concat "^\\(\\*+\\)[ \t]\\|^[ \t]*"
12764 org-clock-string
12765 "[ \t]*\\(?:\\(\\[.*?\\]\\)-+\\(\\[.*?\\]\\)\\|=>[ \t]+\\([0-9]+\\):\\([0-9]+\\)\\)"))
12766 (lmax 30)
12767 (ltimes (make-vector lmax 0))
12768 (t1 0)
12769 (level 0)
12770 ts te dt
12771 time)
12772 (remove-text-properties (point-min) (point-max) '(:org-clock-minutes t))
12773 (save-excursion
12774 (goto-char (point-max))
12775 (while (re-search-backward re nil t)
12776 (cond
12777 ((match-end 2)
12778 ;; Two time stamps
12779 (setq ts (match-string 2)
12780 te (match-string 3)
12781 ts (time-to-seconds
12782 (apply 'encode-time (org-parse-time-string ts)))
12783 te (time-to-seconds
12784 (apply 'encode-time (org-parse-time-string te)))
12785 ts (if tstart (max ts tstart) ts)
12786 te (if tend (min te tend) te)
12787 dt (- te ts)
12788 t1 (if (> dt 0) (+ t1 (floor (/ dt 60))) t1)))
12789 ((match-end 4)
12790 ;; A naket time
12791 (setq t1 (+ t1 (string-to-number (match-string 5))
12792 (* 60 (string-to-number (match-string 4))))))
12793 (t ;; A headline
12794 (setq level (- (match-end 1) (match-beginning 1)))
12795 (when (or (> t1 0) (> (aref ltimes level) 0))
12796 (loop for l from 0 to level do
12797 (aset ltimes l (+ (aref ltimes l) t1)))
12798 (setq t1 0 time (aref ltimes level))
12799 (loop for l from level to (1- lmax) do
12800 (aset ltimes l 0))
12801 (goto-char (match-beginning 0))
12802 (put-text-property (point) (point-at-eol) :org-clock-minutes time)))))
12803 (setq org-clock-file-total-minutes (aref ltimes 0)))
12804 (set-buffer-modified-p bmp)))
12806 (defun org-clock-display (&optional total-only)
12807 "Show subtree times in the entire buffer.
12808 If TOTAL-ONLY is non-nil, only show the total time for the entire file
12809 in the echo area."
12810 (interactive)
12811 (org-remove-clock-overlays)
12812 (let (time h m p)
12813 (org-clock-sum)
12814 (unless total-only
12815 (save-excursion
12816 (goto-char (point-min))
12817 (while (or (and (equal (setq p (point)) (point-min))
12818 (get-text-property p :org-clock-minutes))
12819 (setq p (next-single-property-change
12820 (point) :org-clock-minutes)))
12821 (goto-char p)
12822 (when (setq time (get-text-property p :org-clock-minutes))
12823 (org-put-clock-overlay time (funcall outline-level))))
12824 (setq h (/ org-clock-file-total-minutes 60)
12825 m (- org-clock-file-total-minutes (* 60 h)))
12826 ;; Arrange to remove the overlays upon next change.
12827 (when org-remove-highlights-with-change
12828 (org-add-hook 'before-change-functions 'org-remove-clock-overlays
12829 nil 'local))))
12830 (message "Total file time: %d:%02d (%d hours and %d minutes)" h m h m)))
12832 (defvar org-clock-overlays nil)
12833 (make-variable-buffer-local 'org-clock-overlays)
12835 (defun org-put-clock-overlay (time &optional level)
12836 "Put an overlays on the current line, displaying TIME.
12837 If LEVEL is given, prefix time with a corresponding number of stars.
12838 This creates a new overlay and stores it in `org-clock-overlays', so that it
12839 will be easy to remove."
12840 (let* ((c 60) (h (floor (/ time 60))) (m (- time (* 60 h)))
12841 (l (if level (org-get-valid-level level 0) 0))
12842 (off 0)
12843 ov tx)
12844 (move-to-column c)
12845 (unless (eolp) (skip-chars-backward "^ \t"))
12846 (skip-chars-backward " \t")
12847 (setq ov (org-make-overlay (1- (point)) (point-at-eol))
12848 tx (concat (buffer-substring (1- (point)) (point))
12849 (make-string (+ off (max 0 (- c (current-column)))) ?.)
12850 (org-add-props (format "%s %2d:%02d%s"
12851 (make-string l ?*) h m
12852 (make-string (- 16 l) ?\ ))
12853 '(face secondary-selection))
12854 ""))
12855 (if (not (featurep 'xemacs))
12856 (org-overlay-put ov 'display tx)
12857 (org-overlay-put ov 'invisible t)
12858 (org-overlay-put ov 'end-glyph (make-glyph tx)))
12859 (push ov org-clock-overlays)))
12861 (defun org-remove-clock-overlays (&optional beg end noremove)
12862 "Remove the occur highlights from the buffer.
12863 BEG and END are ignored. If NOREMOVE is nil, remove this function
12864 from the `before-change-functions' in the current buffer."
12865 (interactive)
12866 (unless org-inhibit-highlight-removal
12867 (mapc 'org-delete-overlay org-clock-overlays)
12868 (setq org-clock-overlays nil)
12869 (unless noremove
12870 (remove-hook 'before-change-functions
12871 'org-remove-clock-overlays 'local))))
12873 (defun org-clock-out-if-current ()
12874 "Clock out if the current entry contains the running clock.
12875 This is used to stop the clock after a TODO entry is marked DONE,
12876 and is only done if the variable `org-clock-out-when-done' is not nil."
12877 (when (and org-clock-out-when-done
12878 (member state org-done-keywords)
12879 (equal (marker-buffer org-clock-marker) (current-buffer))
12880 (< (point) org-clock-marker)
12881 (> (save-excursion (outline-next-heading) (point))
12882 org-clock-marker))
12883 ;; Clock out, but don't accept a logging message for this.
12884 (let ((org-log-note-clock-out nil))
12885 (org-clock-out))))
12887 (add-hook 'org-after-todo-state-change-hook
12888 'org-clock-out-if-current)
12890 (defun org-check-running-clock ()
12891 "Check if the current buffer contains the running clock.
12892 If yes, offer to stop it and to save the buffer with the changes."
12893 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
12894 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
12895 (buffer-name))))
12896 (org-clock-out)
12897 (when (y-or-n-p "Save changed buffer?")
12898 (save-buffer))))
12900 (defun org-clock-report (&optional arg)
12901 "Create a table containing a report about clocked time.
12902 If the cursor is inside an existing clocktable block, then the table
12903 will be updated. If not, a new clocktable will be inserted.
12904 When called with a prefix argument, move to the first clock table in the
12905 buffer and update it."
12906 (interactive "P")
12907 (org-remove-clock-overlays)
12908 (when arg
12909 (org-find-dblock "clocktable")
12910 (org-show-entry))
12911 (if (org-in-clocktable-p)
12912 (goto-char (org-in-clocktable-p))
12913 (org-create-dblock (list :name "clocktable"
12914 :maxlevel 2 :scope 'file)))
12915 (org-update-dblock))
12917 (defun org-in-clocktable-p ()
12918 "Check if the cursor is in a clocktable."
12919 (let ((pos (point)) start)
12920 (save-excursion
12921 (end-of-line 1)
12922 (and (re-search-backward "^#\\+BEGIN:[ \t]+clocktable" nil t)
12923 (setq start (match-beginning 0))
12924 (re-search-forward "^#\\+END:.*" nil t)
12925 (>= (match-end 0) pos)
12926 start))))
12928 (defun org-clock-update-time-maybe ()
12929 "If this is a CLOCK line, update it and return t.
12930 Otherwise, return nil."
12931 (interactive)
12932 (save-excursion
12933 (beginning-of-line 1)
12934 (skip-chars-forward " \t")
12935 (when (looking-at org-clock-string)
12936 (let ((re (concat "[ \t]*" org-clock-string
12937 " *[[<]\\([^]>]+\\)[]>]-+[[<]\\([^]>]+\\)[]>]"
12938 "\\([ \t]*=>.*\\)?"))
12939 ts te h m s)
12940 (if (not (looking-at re))
12942 (and (match-end 3) (delete-region (match-beginning 3) (match-end 3)))
12943 (end-of-line 1)
12944 (setq ts (match-string 1)
12945 te (match-string 2))
12946 (setq s (- (time-to-seconds
12947 (apply 'encode-time (org-parse-time-string te)))
12948 (time-to-seconds
12949 (apply 'encode-time (org-parse-time-string ts))))
12950 h (floor (/ s 3600))
12951 s (- s (* 3600 h))
12952 m (floor (/ s 60))
12953 s (- s (* 60 s)))
12954 (insert " => " (format "%2d:%02d" h m))
12955 t)))))
12957 (defun org-clock-special-range (key &optional time as-strings)
12958 "Return two times bordering a special time range.
12959 Key is a symbol specifying the range and can be one of `today', `yesterday',
12960 `thisweek', `lastweek', `thismonth', `lastmonth', `thisyear', `lastyear'.
12961 A week starts Monday 0:00 and ends Sunday 24:00.
12962 The range is determined relative to TIME. TIME defaults to the current time.
12963 The return value is a cons cell with two internal times like the ones
12964 returned by `current time' or `encode-time'. if AS-STRINGS is non-nil,
12965 the returned times will be formatted strings."
12966 (let* ((tm (decode-time (or time (current-time))))
12967 (s 0) (m (nth 1 tm)) (h (nth 2 tm))
12968 (d (nth 3 tm)) (month (nth 4 tm)) (y (nth 5 tm))
12969 (dow (nth 6 tm))
12970 s1 m1 h1 d1 month1 y1 diff ts te fm)
12971 (cond
12972 ((eq key 'today)
12973 (setq h 0 m 0 h1 24 m1 0))
12974 ((eq key 'yesterday)
12975 (setq d (1- d) h 0 m 0 h1 24 m1 0))
12976 ((eq key 'thisweek)
12977 (setq diff (if (= dow 0) 6 (1- dow))
12978 m 0 h 0 d (- d diff) d1 (+ 7 d)))
12979 ((eq key 'lastweek)
12980 (setq diff (+ 7 (if (= dow 0) 6 (1- dow)))
12981 m 0 h 0 d (- d diff) d1 (+ 7 d)))
12982 ((eq key 'thismonth)
12983 (setq d 1 h 0 m 0 d1 1 month1 (1+ month) h1 0 m1 0))
12984 ((eq key 'lastmonth)
12985 (setq d 1 h 0 m 0 d1 1 month (1- month) month1 (1+ month) h1 0 m1 0))
12986 ((eq key 'thisyear)
12987 (setq m 0 h 0 d 1 month 1 y1 (1+ y)))
12988 ((eq key 'lastyear)
12989 (setq m 0 h 0 d 1 month 1 y (1- y) y1 (1+ y)))
12990 (t (error "No such time block %s" key)))
12991 (setq ts (encode-time s m h d month y)
12992 te (encode-time (or s1 s) (or m1 m) (or h1 h)
12993 (or d1 d) (or month1 month) (or y1 y)))
12994 (setq fm (cdr org-time-stamp-formats))
12995 (if as-strings
12996 (cons (format-time-string fm ts) (format-time-string fm te))
12997 (cons ts te))))
12999 (defun org-dblock-write:clocktable (params)
13000 "Write the standard clocktable."
13001 (catch 'exit
13002 (let* ((hlchars '((1 . "*") (2 . "/")))
13003 (ins (make-marker))
13004 (total-time nil)
13005 (scope (plist-get params :scope))
13006 (tostring (plist-get params :tostring))
13007 (multifile (plist-get params :multifile))
13008 (header (plist-get params :header))
13009 (maxlevel (or (plist-get params :maxlevel) 3))
13010 (step (plist-get params :step))
13011 (emph (plist-get params :emphasize))
13012 (ts (plist-get params :tstart))
13013 (te (plist-get params :tend))
13014 (block (plist-get params :block))
13015 (link (plist-get params :link))
13016 ipos time h m p level hlc hdl
13017 cc beg end pos tbl)
13018 (when step
13019 (org-clocktable-steps params)
13020 (throw 'exit nil))
13021 (when block
13022 (setq cc (org-clock-special-range block nil t)
13023 ts (car cc) te (cdr cc)))
13024 (if ts (setq ts (time-to-seconds
13025 (apply 'encode-time (org-parse-time-string ts)))))
13026 (if te (setq te (time-to-seconds
13027 (apply 'encode-time (org-parse-time-string te)))))
13028 (move-marker ins (point))
13029 (setq ipos (point))
13031 ;; Get the right scope
13032 (setq pos (point))
13033 (save-restriction
13034 (cond
13035 ((not scope))
13036 ((eq scope 'file) (widen))
13037 ((eq scope 'subtree) (org-narrow-to-subtree))
13038 ((eq scope 'tree)
13039 (while (org-up-heading-safe))
13040 (org-narrow-to-subtree))
13041 ((and (symbolp scope) (string-match "^tree\\([0-9]+\\)$"
13042 (symbol-name scope)))
13043 (setq level (string-to-number (match-string 1 (symbol-name scope))))
13044 (catch 'exit
13045 (while (org-up-heading-safe)
13046 (looking-at outline-regexp)
13047 (if (<= (org-reduced-level (funcall outline-level)) level)
13048 (throw 'exit nil))))
13049 (org-narrow-to-subtree))
13050 ((or (listp scope) (eq scope 'agenda))
13051 (let* ((files (if (listp scope) scope (org-agenda-files)))
13052 (scope 'agenda)
13053 (p1 (copy-sequence params))
13054 file)
13055 (plist-put p1 :tostring t)
13056 (plist-put p1 :multifile t)
13057 (plist-put p1 :scope 'file)
13058 (org-prepare-agenda-buffers files)
13059 (while (setq file (pop files))
13060 (with-current-buffer (find-buffer-visiting file)
13061 (push (org-clocktable-add-file
13062 file (org-dblock-write:clocktable p1)) tbl)
13063 (setq total-time (+ (or total-time 0)
13064 org-clock-file-total-minutes)))))))
13065 (goto-char pos)
13067 (unless (eq scope 'agenda)
13068 (org-clock-sum ts te)
13069 (goto-char (point-min))
13070 (while (setq p (next-single-property-change (point) :org-clock-minutes))
13071 (goto-char p)
13072 (when (setq time (get-text-property p :org-clock-minutes))
13073 (save-excursion
13074 (beginning-of-line 1)
13075 (when (and (looking-at (org-re "\\(\\*+\\)[ \t]+\\(.*?\\)\\([ \t]+:[[:alnum:]_@:]+:\\)?[ \t]*$"))
13076 (setq level (org-reduced-level
13077 (- (match-end 1) (match-beginning 1))))
13078 (<= level maxlevel))
13079 (setq hlc (if emph (or (cdr (assoc level hlchars)) "") "")
13080 hdl (if (not link)
13081 (match-string 2)
13082 (org-make-link-string
13083 (format "file:%s::%s"
13084 (buffer-file-name)
13085 (save-match-data
13086 (org-make-org-heading-search-string
13087 (match-string 2))))
13088 (match-string 2)))
13089 h (/ time 60)
13090 m (- time (* 60 h)))
13091 (if (and (not multifile) (= level 1)) (push "|-" tbl))
13092 (push (concat
13093 "| " (int-to-string level) "|" hlc hdl hlc " |"
13094 (make-string (1- level) ?|)
13095 hlc (format "%d:%02d" h m) hlc
13096 " |") tbl))))))
13097 (setq tbl (nreverse tbl))
13098 (if tostring
13099 (if tbl (mapconcat 'identity tbl "\n") nil)
13100 (goto-char ins)
13101 (insert-before-markers
13102 (or header
13103 (concat
13104 "Clock summary at ["
13105 (substring
13106 (format-time-string (cdr org-time-stamp-formats))
13107 1 -1)
13108 "]."
13109 (if block
13110 (format " Considered range is /%s/." block)
13112 "\n\n"))
13113 (if (eq scope 'agenda) "|File" "")
13114 "|L|Headline|Time|\n")
13115 (setq total-time (or total-time org-clock-file-total-minutes)
13116 h (/ total-time 60)
13117 m (- total-time (* 60 h)))
13118 (insert-before-markers
13119 "|-\n|"
13120 (if (eq scope 'agenda) "|" "")
13122 "*Total time*| "
13123 (format "*%d:%02d*" h m)
13124 "|\n|-\n")
13125 (setq tbl (delq nil tbl))
13126 (if (and (stringp (car tbl)) (> (length (car tbl)) 1)
13127 (equal (substring (car tbl) 0 2) "|-"))
13128 (pop tbl))
13129 (insert-before-markers (mapconcat
13130 'identity (delq nil tbl)
13131 (if (eq scope 'agenda) "\n|-\n" "\n")))
13132 (backward-delete-char 1)
13133 (goto-char ipos)
13134 (skip-chars-forward "^|")
13135 (org-table-align))))))
13137 (defun org-clocktable-steps (params)
13138 (let* ((p1 (copy-sequence params))
13139 (ts (plist-get p1 :tstart))
13140 (te (plist-get p1 :tend))
13141 (step0 (plist-get p1 :step))
13142 (step (cdr (assoc step0 '((day . 86400) (week . 604800)))))
13143 (block (plist-get p1 :block))
13145 (when block
13146 (setq cc (org-clock-special-range block nil t)
13147 ts (car cc) te (cdr cc)))
13148 (if ts (setq ts (time-to-seconds
13149 (apply 'encode-time (org-parse-time-string ts)))))
13150 (if te (setq te (time-to-seconds
13151 (apply 'encode-time (org-parse-time-string te)))))
13152 (plist-put p1 :header "")
13153 (plist-put p1 :step nil)
13154 (plist-put p1 :block nil)
13155 (while (< ts te)
13156 (or (bolp) (insert "\n"))
13157 (plist-put p1 :tstart (format-time-string
13158 (car org-time-stamp-formats)
13159 (seconds-to-time ts)))
13160 (plist-put p1 :tend (format-time-string
13161 (car org-time-stamp-formats)
13162 (seconds-to-time (setq ts (+ ts step)))))
13163 (insert "\n" (if (eq step0 'day) "Daily report: " "Weekly report starting on: ")
13164 (plist-get p1 :tstart) "\n")
13165 (org-dblock-write:clocktable p1)
13166 (re-search-forward "#\\+END:")
13167 (end-of-line 0))))
13170 (defun org-clocktable-add-file (file table)
13171 (if table
13172 (let ((lines (org-split-string table "\n"))
13173 (ff (file-name-nondirectory file)))
13174 (mapconcat 'identity
13175 (mapcar (lambda (x)
13176 (if (string-match org-table-dataline-regexp x)
13177 (concat "|" ff x)
13179 lines)
13180 "\n"))))
13182 ;; FIXME: I don't think anybody uses this, ask David
13183 (defun org-collect-clock-time-entries ()
13184 "Return an internal list with clocking information.
13185 This list has one entry for each CLOCK interval.
13186 FIXME: describe the elements."
13187 (interactive)
13188 (let ((re (concat "^[ \t]*" org-clock-string
13189 " *\\[\\(.*?\\)\\]--\\[\\(.*?\\)\\]"))
13190 rtn beg end next cont level title total closedp leafp
13191 clockpos titlepos h m donep)
13192 (save-excursion
13193 (org-clock-sum)
13194 (goto-char (point-min))
13195 (while (re-search-forward re nil t)
13196 (setq clockpos (match-beginning 0)
13197 beg (match-string 1) end (match-string 2)
13198 cont (match-end 0))
13199 (setq beg (apply 'encode-time (org-parse-time-string beg))
13200 end (apply 'encode-time (org-parse-time-string end)))
13201 (org-back-to-heading t)
13202 (setq donep (org-entry-is-done-p))
13203 (setq titlepos (point)
13204 total (or (get-text-property (1+ (point)) :org-clock-minutes) 0)
13205 h (/ total 60) m (- total (* 60 h))
13206 total (cons h m))
13207 (looking-at "\\(\\*+\\) +\\(.*\\)")
13208 (setq level (- (match-end 1) (match-beginning 1))
13209 title (org-match-string-no-properties 2))
13210 (save-excursion (outline-next-heading) (setq next (point)))
13211 (setq closedp (re-search-forward org-closed-time-regexp next t))
13212 (goto-char next)
13213 (setq leafp (and (looking-at "^\\*+ ")
13214 (<= (- (match-end 0) (point)) level)))
13215 (push (list beg end clockpos closedp donep
13216 total title titlepos level leafp)
13217 rtn)
13218 (goto-char cont)))
13219 (nreverse rtn)))
13221 ;;;; Agenda files
13223 (defun org-agenda-files (&optional unrestricted)
13224 "Get the list of agenda files.
13225 Optional UNRESTRICTED means return the full list even if a restriction
13226 is currently in place."
13227 (let ((files
13228 (cond
13229 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
13230 ((stringp org-agenda-files) (org-read-agenda-file-list))
13231 ((listp org-agenda-files) org-agenda-files)
13232 (t (error "Invalid value of `org-agenda-files'")))))
13233 (setq files (apply 'append
13234 (mapcar (lambda (f)
13235 (if (file-directory-p f)
13236 (directory-files f t
13237 org-agenda-file-regexp)
13238 (list f)))
13239 files)))
13240 (if org-agenda-skip-unavailable-files
13241 (delq nil
13242 (mapcar (function
13243 (lambda (file)
13244 (and (file-readable-p file) file)))
13245 files))
13246 files))) ; `org-check-agenda-file' will remove them from the list
13248 (defun org-edit-agenda-file-list ()
13249 "Edit the list of agenda files.
13250 Depending on setup, this either uses customize to edit the variable
13251 `org-agenda-files', or it visits the file that is holding the list. In the
13252 latter case, the buffer is set up in a way that saving it automatically kills
13253 the buffer and restores the previous window configuration."
13254 (interactive)
13255 (if (stringp org-agenda-files)
13256 (let ((cw (current-window-configuration)))
13257 (find-file org-agenda-files)
13258 (org-set-local 'org-window-configuration cw)
13259 (org-add-hook 'after-save-hook
13260 (lambda ()
13261 (set-window-configuration
13262 (prog1 org-window-configuration
13263 (kill-buffer (current-buffer))))
13264 (org-install-agenda-files-menu)
13265 (message "New agenda file list installed"))
13266 nil 'local)
13267 (message "%s" (substitute-command-keys
13268 "Edit list and finish with \\[save-buffer]")))
13269 (customize-variable 'org-agenda-files)))
13271 (defun org-store-new-agenda-file-list (list)
13272 "Set new value for the agenda file list and save it correcly."
13273 (if (stringp org-agenda-files)
13274 (let ((f org-agenda-files) b)
13275 (while (setq b (find-buffer-visiting f)) (kill-buffer b))
13276 (with-temp-file f
13277 (insert (mapconcat 'identity list "\n") "\n")))
13278 (let ((org-mode-hook nil) (default-major-mode 'fundamental-mode))
13279 (setq org-agenda-files list)
13280 (customize-save-variable 'org-agenda-files org-agenda-files))))
13282 (defun org-read-agenda-file-list ()
13283 "Read the list of agenda files from a file."
13284 (when (stringp org-agenda-files)
13285 (with-temp-buffer
13286 (insert-file-contents org-agenda-files)
13287 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*"))))
13290 ;;;###autoload
13291 (defun org-cycle-agenda-files ()
13292 "Cycle through the files in `org-agenda-files'.
13293 If the current buffer visits an agenda file, find the next one in the list.
13294 If the current buffer does not, find the first agenda file."
13295 (interactive)
13296 (let* ((fs (org-agenda-files t))
13297 (files (append fs (list (car fs))))
13298 (tcf (if buffer-file-name (file-truename buffer-file-name)))
13299 file)
13300 (unless files (error "No agenda files"))
13301 (catch 'exit
13302 (while (setq file (pop files))
13303 (if (equal (file-truename file) tcf)
13304 (when (car files)
13305 (find-file (car files))
13306 (throw 'exit t))))
13307 (find-file (car fs)))
13308 (if (buffer-base-buffer) (switch-to-buffer (buffer-base-buffer)))))
13310 (defun org-agenda-file-to-front (&optional to-end)
13311 "Move/add the current file to the top of the agenda file list.
13312 If the file is not present in the list, it is added to the front. If it is
13313 present, it is moved there. With optional argument TO-END, add/move to the
13314 end of the list."
13315 (interactive "P")
13316 (let ((org-agenda-skip-unavailable-files nil)
13317 (file-alist (mapcar (lambda (x)
13318 (cons (file-truename x) x))
13319 (org-agenda-files t)))
13320 (ctf (file-truename buffer-file-name))
13321 x had)
13322 (setq x (assoc ctf file-alist) had x)
13324 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
13325 (if to-end
13326 (setq file-alist (append (delq x file-alist) (list x)))
13327 (setq file-alist (cons x (delq x file-alist))))
13328 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
13329 (org-install-agenda-files-menu)
13330 (message "File %s to %s of agenda file list"
13331 (if had "moved" "added") (if to-end "end" "front"))))
13333 (defun org-remove-file (&optional file)
13334 "Remove current file from the list of files in variable `org-agenda-files'.
13335 These are the files which are being checked for agenda entries.
13336 Optional argument FILE means, use this file instead of the current."
13337 (interactive)
13338 (let* ((org-agenda-skip-unavailable-files nil)
13339 (file (or file buffer-file-name))
13340 (true-file (file-truename file))
13341 (afile (abbreviate-file-name file))
13342 (files (delq nil (mapcar
13343 (lambda (x)
13344 (if (equal true-file
13345 (file-truename x))
13346 nil x))
13347 (org-agenda-files t)))))
13348 (if (not (= (length files) (length (org-agenda-files t))))
13349 (progn
13350 (org-store-new-agenda-file-list files)
13351 (org-install-agenda-files-menu)
13352 (message "Removed file: %s" afile))
13353 (message "File was not in list: %s (not removed)" afile))))
13355 (defun org-file-menu-entry (file)
13356 (vector file (list 'find-file file) t))
13358 (defun org-check-agenda-file (file)
13359 "Make sure FILE exists. If not, ask user what to do."
13360 (when (not (file-exists-p file))
13361 (message "non-existent file %s. [R]emove from list or [A]bort?"
13362 (abbreviate-file-name file))
13363 (let ((r (downcase (read-char-exclusive))))
13364 (cond
13365 ((equal r ?r)
13366 (org-remove-file file)
13367 (throw 'nextfile t))
13368 (t (error "Abort"))))))
13370 (defun org-get-agenda-file-buffer (file)
13371 "Get a buffer visiting FILE. If the buffer needs to be created, add
13372 it to the list of buffers which might be released later."
13373 (let ((buf (org-find-base-buffer-visiting file)))
13374 (if buf
13375 buf ; just return it
13376 ;; Make a new buffer and remember it
13377 (setq buf (find-file-noselect file))
13378 (if buf (push buf org-agenda-new-buffers))
13379 buf)))
13381 (defun org-release-buffers (blist)
13382 "Release all buffers in list, asking the user for confirmation when needed.
13383 When a buffer is unmodified, it is just killed. When modified, it is saved
13384 \(if the user agrees) and then killed."
13385 (let (buf file)
13386 (while (setq buf (pop blist))
13387 (setq file (buffer-file-name buf))
13388 (when (and (buffer-modified-p buf)
13389 file
13390 (y-or-n-p (format "Save file %s? " file)))
13391 (with-current-buffer buf (save-buffer)))
13392 (kill-buffer buf))))
13394 (defun org-prepare-agenda-buffers (files)
13395 "Create buffers for all agenda files, protect archived trees and comments."
13396 (interactive)
13397 (let ((pa '(:org-archived t))
13398 (pc '(:org-comment t))
13399 (pall '(:org-archived t :org-comment t))
13400 (inhibit-read-only t)
13401 (rea (concat ":" org-archive-tag ":"))
13402 bmp file re)
13403 (save-excursion
13404 (save-restriction
13405 (while (setq file (pop files))
13406 (if (bufferp file)
13407 (set-buffer file)
13408 (org-check-agenda-file file)
13409 (set-buffer (org-get-agenda-file-buffer file)))
13410 (widen)
13411 (setq bmp (buffer-modified-p))
13412 (org-refresh-category-properties)
13413 (setq org-todo-keywords-for-agenda
13414 (append org-todo-keywords-for-agenda org-todo-keywords-1))
13415 (setq org-done-keywords-for-agenda
13416 (append org-done-keywords-for-agenda org-done-keywords))
13417 (save-excursion
13418 (remove-text-properties (point-min) (point-max) pall)
13419 (when org-agenda-skip-archived-trees
13420 (goto-char (point-min))
13421 (while (re-search-forward rea nil t)
13422 (if (org-on-heading-p t)
13423 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
13424 (goto-char (point-min))
13425 (setq re (concat "^\\*+ +" org-comment-string "\\>"))
13426 (while (re-search-forward re nil t)
13427 (add-text-properties
13428 (match-beginning 0) (org-end-of-subtree t) pc)))
13429 (set-buffer-modified-p bmp))))))
13431 ;;;; Embedded LaTeX
13433 (defvar org-cdlatex-mode-map (make-sparse-keymap)
13434 "Keymap for the minor `org-cdlatex-mode'.")
13436 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
13437 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
13438 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
13439 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
13440 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
13442 (defvar org-cdlatex-texmathp-advice-is-done nil
13443 "Flag remembering if we have applied the advice to texmathp already.")
13445 (define-minor-mode org-cdlatex-mode
13446 "Toggle the minor `org-cdlatex-mode'.
13447 This mode supports entering LaTeX environment and math in LaTeX fragments
13448 in Org-mode.
13449 \\{org-cdlatex-mode-map}"
13450 nil " OCDL" nil
13451 (when org-cdlatex-mode (require 'cdlatex))
13452 (unless org-cdlatex-texmathp-advice-is-done
13453 (setq org-cdlatex-texmathp-advice-is-done t)
13454 (defadvice texmathp (around org-math-always-on activate)
13455 "Always return t in org-mode buffers.
13456 This is because we want to insert math symbols without dollars even outside
13457 the LaTeX math segments. If Orgmode thinks that point is actually inside
13458 en embedded LaTeX fragement, let texmathp do its job.
13459 \\[org-cdlatex-mode-map]"
13460 (interactive)
13461 (let (p)
13462 (cond
13463 ((not (org-mode-p)) ad-do-it)
13464 ((eq this-command 'cdlatex-math-symbol)
13465 (setq ad-return-value t
13466 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
13468 (let ((p (org-inside-LaTeX-fragment-p)))
13469 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
13470 (setq ad-return-value t
13471 texmathp-why '("Org-mode embedded math" . 0))
13472 (if p ad-do-it)))))))))
13474 (defun turn-on-org-cdlatex ()
13475 "Unconditionally turn on `org-cdlatex-mode'."
13476 (org-cdlatex-mode 1))
13478 (defun org-inside-LaTeX-fragment-p ()
13479 "Test if point is inside a LaTeX fragment.
13480 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
13481 sequence appearing also before point.
13482 Even though the matchers for math are configurable, this function assumes
13483 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
13484 delimiters are skipped when they have been removed by customization.
13485 The return value is nil, or a cons cell with the delimiter and
13486 and the position of this delimiter.
13488 This function does a reasonably good job, but can locally be fooled by
13489 for example currency specifications. For example it will assume being in
13490 inline math after \"$22.34\". The LaTeX fragment formatter will only format
13491 fragments that are properly closed, but during editing, we have to live
13492 with the uncertainty caused by missing closing delimiters. This function
13493 looks only before point, not after."
13494 (catch 'exit
13495 (let ((pos (point))
13496 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
13497 (lim (progn
13498 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
13499 (point)))
13500 dd-on str (start 0) m re)
13501 (goto-char pos)
13502 (when dodollar
13503 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
13504 re (nth 1 (assoc "$" org-latex-regexps)))
13505 (while (string-match re str start)
13506 (cond
13507 ((= (match-end 0) (length str))
13508 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
13509 ((= (match-end 0) (- (length str) 5))
13510 (throw 'exit nil))
13511 (t (setq start (match-end 0))))))
13512 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
13513 (goto-char pos)
13514 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
13515 (and (match-beginning 2) (throw 'exit nil))
13516 ;; count $$
13517 (while (re-search-backward "\\$\\$" lim t)
13518 (setq dd-on (not dd-on)))
13519 (goto-char pos)
13520 (if dd-on (cons "$$" m))))))
13523 (defun org-try-cdlatex-tab ()
13524 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
13525 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
13526 - inside a LaTeX fragment, or
13527 - after the first word in a line, where an abbreviation expansion could
13528 insert a LaTeX environment."
13529 (when org-cdlatex-mode
13530 (cond
13531 ((save-excursion
13532 (skip-chars-backward "a-zA-Z0-9*")
13533 (skip-chars-backward " \t")
13534 (bolp))
13535 (cdlatex-tab) t)
13536 ((org-inside-LaTeX-fragment-p)
13537 (cdlatex-tab) t)
13538 (t nil))))
13540 (defun org-cdlatex-underscore-caret (&optional arg)
13541 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
13542 Revert to the normal definition outside of these fragments."
13543 (interactive "P")
13544 (if (org-inside-LaTeX-fragment-p)
13545 (call-interactively 'cdlatex-sub-superscript)
13546 (let (org-cdlatex-mode)
13547 (call-interactively (key-binding (vector last-input-event))))))
13549 (defun org-cdlatex-math-modify (&optional arg)
13550 "Execute `cdlatex-math-modify' in LaTeX fragments.
13551 Revert to the normal definition outside of these fragments."
13552 (interactive "P")
13553 (if (org-inside-LaTeX-fragment-p)
13554 (call-interactively 'cdlatex-math-modify)
13555 (let (org-cdlatex-mode)
13556 (call-interactively (key-binding (vector last-input-event))))))
13558 (defvar org-latex-fragment-image-overlays nil
13559 "List of overlays carrying the images of latex fragments.")
13560 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
13562 (defun org-remove-latex-fragment-image-overlays ()
13563 "Remove all overlays with LaTeX fragment images in current buffer."
13564 (mapc 'org-delete-overlay org-latex-fragment-image-overlays)
13565 (setq org-latex-fragment-image-overlays nil))
13567 (defun org-preview-latex-fragment (&optional subtree)
13568 "Preview the LaTeX fragment at point, or all locally or globally.
13569 If the cursor is in a LaTeX fragment, create the image and overlay
13570 it over the source code. If there is no fragment at point, display
13571 all fragments in the current text, from one headline to the next. With
13572 prefix SUBTREE, display all fragments in the current subtree. With a
13573 double prefix `C-u C-u', or when the cursor is before the first headline,
13574 display all fragments in the buffer.
13575 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
13576 (interactive "P")
13577 (org-remove-latex-fragment-image-overlays)
13578 (save-excursion
13579 (save-restriction
13580 (let (beg end at msg)
13581 (cond
13582 ((or (equal subtree '(16))
13583 (not (save-excursion
13584 (re-search-backward (concat "^" outline-regexp) nil t))))
13585 (setq beg (point-min) end (point-max)
13586 msg "Creating images for buffer...%s"))
13587 ((equal subtree '(4))
13588 (org-back-to-heading)
13589 (setq beg (point) end (org-end-of-subtree t)
13590 msg "Creating images for subtree...%s"))
13592 (if (setq at (org-inside-LaTeX-fragment-p))
13593 (goto-char (max (point-min) (- (cdr at) 2)))
13594 (org-back-to-heading))
13595 (setq beg (point) end (progn (outline-next-heading) (point))
13596 msg (if at "Creating image...%s"
13597 "Creating images for entry...%s"))))
13598 (message msg "")
13599 (narrow-to-region beg end)
13600 (goto-char beg)
13601 (org-format-latex
13602 (concat "ltxpng/" (file-name-sans-extension
13603 (file-name-nondirectory
13604 buffer-file-name)))
13605 default-directory 'overlays msg at 'forbuffer)
13606 (message msg "done. Use `C-c C-c' to remove images.")))))
13608 (defvar org-latex-regexps
13609 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
13610 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
13611 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
13612 ("$" "\\([^$]\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([ .,?;:'\")\000]\\|$\\)" 2 nil)
13613 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
13614 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 t)
13615 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 t))
13616 "Regular expressions for matching embedded LaTeX.")
13618 (defun org-format-latex (prefix &optional dir overlays msg at forbuffer)
13619 "Replace LaTeX fragments with links to an image, and produce images."
13620 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
13621 (let* ((prefixnodir (file-name-nondirectory prefix))
13622 (absprefix (expand-file-name prefix dir))
13623 (todir (file-name-directory absprefix))
13624 (opt org-format-latex-options)
13625 (matchers (plist-get opt :matchers))
13626 (re-list org-latex-regexps)
13627 (cnt 0) txt link beg end re e checkdir
13628 m n block linkfile movefile ov)
13629 ;; Check if there are old images files with this prefix, and remove them
13630 (when (file-directory-p todir)
13631 (mapc 'delete-file
13632 (directory-files
13633 todir 'full
13634 (concat (regexp-quote prefixnodir) "_[0-9]+\\.png$"))))
13635 ;; Check the different regular expressions
13636 (while (setq e (pop re-list))
13637 (setq m (car e) re (nth 1 e) n (nth 2 e)
13638 block (if (nth 3 e) "\n\n" ""))
13639 (when (member m matchers)
13640 (goto-char (point-min))
13641 (while (re-search-forward re nil t)
13642 (when (or (not at) (equal (cdr at) (match-beginning n)))
13643 (setq txt (match-string n)
13644 beg (match-beginning n) end (match-end n)
13645 cnt (1+ cnt)
13646 linkfile (format "%s_%04d.png" prefix cnt)
13647 movefile (format "%s_%04d.png" absprefix cnt)
13648 link (concat block "[[file:" linkfile "]]" block))
13649 (if msg (message msg cnt))
13650 (goto-char beg)
13651 (unless checkdir ; make sure the directory exists
13652 (setq checkdir t)
13653 (or (file-directory-p todir) (make-directory todir)))
13654 (org-create-formula-image
13655 txt movefile opt forbuffer)
13656 (if overlays
13657 (progn
13658 (setq ov (org-make-overlay beg end))
13659 (if (featurep 'xemacs)
13660 (progn
13661 (org-overlay-put ov 'invisible t)
13662 (org-overlay-put
13663 ov 'end-glyph
13664 (make-glyph (vector 'png :file movefile))))
13665 (org-overlay-put
13666 ov 'display
13667 (list 'image :type 'png :file movefile :ascent 'center)))
13668 (push ov org-latex-fragment-image-overlays)
13669 (goto-char end))
13670 (delete-region beg end)
13671 (insert link))))))))
13673 ;; This function borrows from Ganesh Swami's latex2png.el
13674 (defun org-create-formula-image (string tofile options buffer)
13675 (let* ((tmpdir (if (featurep 'xemacs)
13676 (temp-directory)
13677 temporary-file-directory))
13678 (texfilebase (make-temp-name
13679 (expand-file-name "orgtex" tmpdir)))
13680 (texfile (concat texfilebase ".tex"))
13681 (dvifile (concat texfilebase ".dvi"))
13682 (pngfile (concat texfilebase ".png"))
13683 (fnh (face-attribute 'default :height nil))
13684 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
13685 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
13686 (fg (or (plist-get options (if buffer :foreground :html-foreground))
13687 "Black"))
13688 (bg (or (plist-get options (if buffer :background :html-background))
13689 "Transparent")))
13690 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
13691 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
13692 (with-temp-file texfile
13693 (insert org-format-latex-header
13694 "\n\\begin{document}\n" string "\n\\end{document}\n"))
13695 (let ((dir default-directory))
13696 (condition-case nil
13697 (progn
13698 (cd tmpdir)
13699 (call-process "latex" nil nil nil texfile))
13700 (error nil))
13701 (cd dir))
13702 (if (not (file-exists-p dvifile))
13703 (progn (message "Failed to create dvi file from %s" texfile) nil)
13704 (call-process "dvipng" nil nil nil
13705 "-E" "-fg" fg "-bg" bg
13706 "-D" dpi
13707 ;;"-x" scale "-y" scale
13708 "-T" "tight"
13709 "-o" pngfile
13710 dvifile)
13711 (if (not (file-exists-p pngfile))
13712 (progn (message "Failed to create png file from %s" texfile) nil)
13713 ;; Use the requested file name and clean up
13714 (copy-file pngfile tofile 'replace)
13715 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
13716 (delete-file (concat texfilebase e)))
13717 pngfile))))
13719 (defun org-dvipng-color (attr)
13720 "Return an rgb color specification for dvipng."
13721 (apply 'format "rgb %s %s %s"
13722 (mapcar 'org-normalize-color
13723 (color-values (face-attribute 'default attr nil)))))
13725 (defun org-normalize-color (value)
13726 "Return string to be used as color value for an RGB component."
13727 (format "%g" (/ value 65535.0)))
13730 ;;;; Key bindings
13732 ;; Make `C-c C-x' a prefix key
13733 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
13735 ;; TAB key with modifiers
13736 (org-defkey org-mode-map "\C-i" 'org-cycle)
13737 (org-defkey org-mode-map [(tab)] 'org-cycle)
13738 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
13739 (org-defkey org-mode-map [(meta tab)] 'org-complete)
13740 (org-defkey org-mode-map "\M-\t" 'org-complete)
13741 (org-defkey org-mode-map "\M-\C-i" 'org-complete)
13742 ;; The following line is necessary under Suse GNU/Linux
13743 (unless (featurep 'xemacs)
13744 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
13745 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
13746 (define-key org-mode-map [backtab] 'org-shifttab)
13748 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
13749 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
13750 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
13752 ;; Cursor keys with modifiers
13753 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
13754 (org-defkey org-mode-map [(meta right)] 'org-metaright)
13755 (org-defkey org-mode-map [(meta up)] 'org-metaup)
13756 (org-defkey org-mode-map [(meta down)] 'org-metadown)
13758 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
13759 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
13760 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
13761 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
13763 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
13764 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
13765 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
13766 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
13768 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
13769 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
13771 ;;; Extra keys for tty access.
13772 ;; We only set them when really needed because otherwise the
13773 ;; menus don't show the simple keys
13775 (when (or (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
13776 (not window-system))
13777 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
13778 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
13779 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
13780 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
13781 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
13782 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
13783 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
13784 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
13785 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
13786 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
13787 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
13788 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
13789 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
13790 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
13791 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
13792 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
13793 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
13794 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
13795 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
13796 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
13797 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
13798 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft))
13800 ;; All the other keys
13802 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
13803 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
13804 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree)
13805 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
13806 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
13807 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-toggle-archive-tag)
13808 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
13809 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
13810 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
13811 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
13812 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
13813 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
13814 (org-defkey org-mode-map "\C-c\C-v" 'org-show-todo-tree)
13815 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
13816 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
13817 (org-defkey org-mode-map "\C-c\\" 'org-tags-sparse-tree) ; Minor-mode res.
13818 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
13819 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
13820 (org-defkey org-mode-map [(control return)] 'org-insert-heading-after-current)
13821 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
13822 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
13823 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
13824 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
13825 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
13826 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
13827 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
13828 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
13829 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
13830 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
13831 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
13832 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
13833 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
13834 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
13835 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
13836 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
13837 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
13838 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
13839 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
13840 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
13841 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
13842 (org-defkey org-mode-map "\C-c^" 'org-sort)
13843 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
13844 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
13845 (org-defkey org-mode-map "\C-c#" 'org-update-checkbox-count)
13846 (org-defkey org-mode-map "\C-m" 'org-return)
13847 (org-defkey org-mode-map "\C-j" 'org-return-indent)
13848 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
13849 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
13850 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
13851 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
13852 (org-defkey org-mode-map "\C-c'" 'org-table-edit-formulas)
13853 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
13854 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
13855 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
13856 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
13857 (org-defkey org-mode-map "\C-c\C-q" 'org-table-wrap-region)
13858 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
13859 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
13860 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
13861 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
13862 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
13864 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-cut-special)
13865 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
13866 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
13867 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
13869 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
13870 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
13871 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
13872 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
13873 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
13874 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
13875 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
13876 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
13877 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
13878 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
13879 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
13880 (org-defkey org-mode-map "\C-c\C-xr" 'org-insert-columns-dblock)
13882 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
13884 (when (featurep 'xemacs)
13885 (org-defkey org-mode-map 'button3 'popup-mode-menu))
13887 (defvar org-table-auto-blank-field) ; defined in org-table.el
13888 (defun org-self-insert-command (N)
13889 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
13890 If the cursor is in a table looking at whitespace, the whitespace is
13891 overwritten, and the table is not marked as requiring realignment."
13892 (interactive "p")
13893 (if (and (org-table-p)
13894 (progn
13895 ;; check if we blank the field, and if that triggers align
13896 (and (featurep 'org-table) org-table-auto-blank-field
13897 (member last-command
13898 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
13899 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
13900 ;; got extra space, this field does not determine column width
13901 (let (org-table-may-need-update) (org-table-blank-field))
13902 ;; no extra space, this field may determine column width
13903 (org-table-blank-field)))
13905 (eq N 1)
13906 (looking-at "[^|\n]* |"))
13907 (let (org-table-may-need-update)
13908 (goto-char (1- (match-end 0)))
13909 (delete-backward-char 1)
13910 (goto-char (match-beginning 0))
13911 (self-insert-command N))
13912 (setq org-table-may-need-update t)
13913 (self-insert-command N)
13914 (org-fix-tags-on-the-fly)))
13916 (defun org-fix-tags-on-the-fly ()
13917 (when (and (equal (char-after (point-at-bol)) ?*)
13918 (org-on-heading-p))
13919 (org-align-tags-here org-tags-column)))
13921 (defun org-delete-backward-char (N)
13922 "Like `delete-backward-char', insert whitespace at field end in tables.
13923 When deleting backwards, in tables this function will insert whitespace in
13924 front of the next \"|\" separator, to keep the table aligned. The table will
13925 still be marked for re-alignment if the field did fill the entire column,
13926 because, in this case the deletion might narrow the column."
13927 (interactive "p")
13928 (if (and (org-table-p)
13929 (eq N 1)
13930 (string-match "|" (buffer-substring (point-at-bol) (point)))
13931 (looking-at ".*?|"))
13932 (let ((pos (point))
13933 (noalign (looking-at "[^|\n\r]* |"))
13934 (c org-table-may-need-update))
13935 (backward-delete-char N)
13936 (skip-chars-forward "^|")
13937 (insert " ")
13938 (goto-char (1- pos))
13939 ;; noalign: if there were two spaces at the end, this field
13940 ;; does not determine the width of the column.
13941 (if noalign (setq org-table-may-need-update c)))
13942 (backward-delete-char N)
13943 (org-fix-tags-on-the-fly)))
13945 (defun org-delete-char (N)
13946 "Like `delete-char', but insert whitespace at field end in tables.
13947 When deleting characters, in tables this function will insert whitespace in
13948 front of the next \"|\" separator, to keep the table aligned. The table will
13949 still be marked for re-alignment if the field did fill the entire column,
13950 because, in this case the deletion might narrow the column."
13951 (interactive "p")
13952 (if (and (org-table-p)
13953 (not (bolp))
13954 (not (= (char-after) ?|))
13955 (eq N 1))
13956 (if (looking-at ".*?|")
13957 (let ((pos (point))
13958 (noalign (looking-at "[^|\n\r]* |"))
13959 (c org-table-may-need-update))
13960 (replace-match (concat
13961 (substring (match-string 0) 1 -1)
13962 " |"))
13963 (goto-char pos)
13964 ;; noalign: if there were two spaces at the end, this field
13965 ;; does not determine the width of the column.
13966 (if noalign (setq org-table-may-need-update c)))
13967 (delete-char N))
13968 (delete-char N)
13969 (org-fix-tags-on-the-fly)))
13971 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
13972 (put 'org-self-insert-command 'delete-selection t)
13973 (put 'orgtbl-self-insert-command 'delete-selection t)
13974 (put 'org-delete-char 'delete-selection 'supersede)
13975 (put 'org-delete-backward-char 'delete-selection 'supersede)
13977 ;; Make `flyspell-mode' delay after some commands
13978 (put 'org-self-insert-command 'flyspell-delayed t)
13979 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
13980 (put 'org-delete-char 'flyspell-delayed t)
13981 (put 'org-delete-backward-char 'flyspell-delayed t)
13983 ;; Make pabbrev-mode expand after org-mode commands
13984 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
13985 (put 'orgybl-self-insert-command 'pabbrev-expand-after-command t)
13987 ;; How to do this: Measure non-white length of current string
13988 ;; If equal to column width, we should realign.
13990 (defun org-remap (map &rest commands)
13991 "In MAP, remap the functions given in COMMANDS.
13992 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
13993 (let (new old)
13994 (while commands
13995 (setq old (pop commands) new (pop commands))
13996 (if (fboundp 'command-remapping)
13997 (org-defkey map (vector 'remap old) new)
13998 (substitute-key-definition old new map global-map)))))
14000 (when (eq org-enable-table-editor 'optimized)
14001 ;; If the user wants maximum table support, we need to hijack
14002 ;; some standard editing functions
14003 (org-remap org-mode-map
14004 'self-insert-command 'org-self-insert-command
14005 'delete-char 'org-delete-char
14006 'delete-backward-char 'org-delete-backward-char)
14007 (org-defkey org-mode-map "|" 'org-force-self-insert))
14009 (defun org-shiftcursor-error ()
14010 "Throw an error because Shift-Cursor command was applied in wrong context."
14011 (error "This command is active in special context like tables, headlines or timestamps"))
14013 (defun org-shifttab (&optional arg)
14014 "Global visibility cycling or move to previous table field.
14015 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
14016 on context.
14017 See the individual commands for more information."
14018 (interactive "P")
14019 (cond
14020 ((org-at-table-p) (call-interactively 'org-table-previous-field))
14021 (arg (message "Content view to level: ")
14022 (org-content (prefix-numeric-value arg))
14023 (setq org-cycle-global-status 'overview))
14024 (t (call-interactively 'org-global-cycle))))
14026 (defun org-shiftmetaleft ()
14027 "Promote subtree or delete table column.
14028 Calls `org-promote-subtree', `org-outdent-item',
14029 or `org-table-delete-column', depending on context.
14030 See the individual commands for more information."
14031 (interactive)
14032 (cond
14033 ((org-at-table-p) (call-interactively 'org-table-delete-column))
14034 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
14035 ((org-at-item-p) (call-interactively 'org-outdent-item))
14036 (t (org-shiftcursor-error))))
14038 (defun org-shiftmetaright ()
14039 "Demote subtree or insert table column.
14040 Calls `org-demote-subtree', `org-indent-item',
14041 or `org-table-insert-column', depending on context.
14042 See the individual commands for more information."
14043 (interactive)
14044 (cond
14045 ((org-at-table-p) (call-interactively 'org-table-insert-column))
14046 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
14047 ((org-at-item-p) (call-interactively 'org-indent-item))
14048 (t (org-shiftcursor-error))))
14050 (defun org-shiftmetaup (&optional arg)
14051 "Move subtree up or kill table row.
14052 Calls `org-move-subtree-up' or `org-table-kill-row' or
14053 `org-move-item-up' depending on context. See the individual commands
14054 for more information."
14055 (interactive "P")
14056 (cond
14057 ((org-at-table-p) (call-interactively 'org-table-kill-row))
14058 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
14059 ((org-at-item-p) (call-interactively 'org-move-item-up))
14060 (t (org-shiftcursor-error))))
14061 (defun org-shiftmetadown (&optional arg)
14062 "Move subtree down or insert table row.
14063 Calls `org-move-subtree-down' or `org-table-insert-row' or
14064 `org-move-item-down', depending on context. See the individual
14065 commands for more information."
14066 (interactive "P")
14067 (cond
14068 ((org-at-table-p) (call-interactively 'org-table-insert-row))
14069 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
14070 ((org-at-item-p) (call-interactively 'org-move-item-down))
14071 (t (org-shiftcursor-error))))
14073 (defun org-metaleft (&optional arg)
14074 "Promote heading or move table column to left.
14075 Calls `org-do-promote' or `org-table-move-column', depending on context.
14076 With no specific context, calls the Emacs default `backward-word'.
14077 See the individual commands for more information."
14078 (interactive "P")
14079 (cond
14080 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
14081 ((or (org-on-heading-p) (org-region-active-p))
14082 (call-interactively 'org-do-promote))
14083 ((org-at-item-p) (call-interactively 'org-outdent-item))
14084 (t (call-interactively 'backward-word))))
14086 (defun org-metaright (&optional arg)
14087 "Demote subtree or move table column to right.
14088 Calls `org-do-demote' or `org-table-move-column', depending on context.
14089 With no specific context, calls the Emacs default `forward-word'.
14090 See the individual commands for more information."
14091 (interactive "P")
14092 (cond
14093 ((org-at-table-p) (call-interactively 'org-table-move-column))
14094 ((or (org-on-heading-p) (org-region-active-p))
14095 (call-interactively 'org-do-demote))
14096 ((org-at-item-p) (call-interactively 'org-indent-item))
14097 (t (call-interactively 'forward-word))))
14099 (defun org-metaup (&optional arg)
14100 "Move subtree up or move table row up.
14101 Calls `org-move-subtree-up' or `org-table-move-row' or
14102 `org-move-item-up', depending on context. See the individual commands
14103 for more information."
14104 (interactive "P")
14105 (cond
14106 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
14107 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
14108 ((org-at-item-p) (call-interactively 'org-move-item-up))
14109 (t (transpose-lines 1) (beginning-of-line -1))))
14111 (defun org-metadown (&optional arg)
14112 "Move subtree down or move table row down.
14113 Calls `org-move-subtree-down' or `org-table-move-row' or
14114 `org-move-item-down', depending on context. See the individual
14115 commands for more information."
14116 (interactive "P")
14117 (cond
14118 ((org-at-table-p) (call-interactively 'org-table-move-row))
14119 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
14120 ((org-at-item-p) (call-interactively 'org-move-item-down))
14121 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
14123 (defun org-shiftup (&optional arg)
14124 "Increase item in timestamp or increase priority of current headline.
14125 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
14126 depending on context. See the individual commands for more information."
14127 (interactive "P")
14128 (cond
14129 ((org-at-timestamp-p t)
14130 (call-interactively (if org-edit-timestamp-down-means-later
14131 'org-timestamp-down 'org-timestamp-up)))
14132 ((org-on-heading-p) (call-interactively 'org-priority-up))
14133 ((org-at-item-p) (call-interactively 'org-previous-item))
14134 (t (call-interactively 'org-beginning-of-item) (beginning-of-line 1))))
14136 (defun org-shiftdown (&optional arg)
14137 "Decrease item in timestamp or decrease priority of current headline.
14138 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
14139 depending on context. See the individual commands for more information."
14140 (interactive "P")
14141 (cond
14142 ((org-at-timestamp-p t)
14143 (call-interactively (if org-edit-timestamp-down-means-later
14144 'org-timestamp-up 'org-timestamp-down)))
14145 ((org-on-heading-p) (call-interactively 'org-priority-down))
14146 (t (call-interactively 'org-next-item))))
14148 (defun org-shiftright ()
14149 "Next TODO keyword or timestamp one day later, depending on context."
14150 (interactive)
14151 (cond
14152 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
14153 ((org-on-heading-p) (org-call-with-arg 'org-todo 'right))
14154 ((org-at-item-p) (org-call-with-arg 'org-cycle-list-bullet nil))
14155 ((org-at-property-p) (call-interactively 'org-property-next-allowed-value))
14156 (t (org-shiftcursor-error))))
14158 (defun org-shiftleft ()
14159 "Previous TODO keyword or timestamp one day earlier, depending on context."
14160 (interactive)
14161 (cond
14162 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
14163 ((org-on-heading-p) (org-call-with-arg 'org-todo 'left))
14164 ((org-at-item-p) (org-call-with-arg 'org-cycle-list-bullet 'previous))
14165 ((org-at-property-p)
14166 (call-interactively 'org-property-previous-allowed-value))
14167 (t (org-shiftcursor-error))))
14169 (defun org-shiftcontrolright ()
14170 "Switch to next TODO set."
14171 (interactive)
14172 (cond
14173 ((org-on-heading-p) (org-call-with-arg 'org-todo 'nextset))
14174 (t (org-shiftcursor-error))))
14176 (defun org-shiftcontrolleft ()
14177 "Switch to previous TODO set."
14178 (interactive)
14179 (cond
14180 ((org-on-heading-p) (org-call-with-arg 'org-todo 'previousset))
14181 (t (org-shiftcursor-error))))
14183 (defun org-ctrl-c-ret ()
14184 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
14185 (interactive)
14186 (cond
14187 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
14188 (t (call-interactively 'org-insert-heading))))
14190 (defun org-copy-special ()
14191 "Copy region in table or copy current subtree.
14192 Calls `org-table-copy' or `org-copy-subtree', depending on context.
14193 See the individual commands for more information."
14194 (interactive)
14195 (call-interactively
14196 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
14198 (defun org-cut-special ()
14199 "Cut region in table or cut current subtree.
14200 Calls `org-table-copy' or `org-cut-subtree', depending on context.
14201 See the individual commands for more information."
14202 (interactive)
14203 (call-interactively
14204 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
14206 (defun org-paste-special (arg)
14207 "Paste rectangular region into table, or past subtree relative to level.
14208 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
14209 See the individual commands for more information."
14210 (interactive "P")
14211 (if (org-at-table-p)
14212 (org-table-paste-rectangle)
14213 (org-paste-subtree arg)))
14215 (defun org-ctrl-c-ctrl-c (&optional arg)
14216 "Set tags in headline, or update according to changed information at point.
14218 This command does many different things, depending on context:
14220 - If the cursor is in a headline, prompt for tags and insert them
14221 into the current line, aligned to `org-tags-column'. When called
14222 with prefix arg, realign all tags in the current buffer.
14224 - If the cursor is in one of the special #+KEYWORD lines, this
14225 triggers scanning the buffer for these lines and updating the
14226 information.
14228 - If the cursor is inside a table, realign the table. This command
14229 works even if the automatic table editor has been turned off.
14231 - If the cursor is on a #+TBLFM line, re-apply the formulas to
14232 the entire table.
14234 - If the cursor is a the beginning of a dynamic block, update it.
14236 - If the cursor is inside a table created by the table.el package,
14237 activate that table.
14239 - If the current buffer is a remember buffer, close note and file it.
14240 with a prefix argument, file it without further interaction to the default
14241 location.
14243 - If the cursor is on a <<<target>>>, update radio targets and corresponding
14244 links in this buffer.
14246 - If the cursor is on a numbered item in a plain list, renumber the
14247 ordered list.
14249 - If the cursor is on a checkbox, toggle it."
14250 (interactive "P")
14251 (let ((org-enable-table-editor t))
14252 (cond
14253 ((or org-clock-overlays
14254 org-occur-highlights
14255 org-latex-fragment-image-overlays)
14256 (org-remove-clock-overlays)
14257 (org-remove-occur-highlights)
14258 (org-remove-latex-fragment-image-overlays)
14259 (message "Temporary highlights/overlays removed from current buffer"))
14260 ((and (local-variable-p 'org-finish-function (current-buffer))
14261 (fboundp org-finish-function))
14262 (funcall org-finish-function))
14263 ((org-at-property-p)
14264 (call-interactively 'org-property-action))
14265 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
14266 ((org-on-heading-p) (call-interactively 'org-set-tags))
14267 ((org-at-table.el-p)
14268 (require 'table)
14269 (beginning-of-line 1)
14270 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
14271 (call-interactively 'table-recognize-table))
14272 ((org-at-table-p)
14273 (org-table-maybe-eval-formula)
14274 (if arg
14275 (call-interactively 'org-table-recalculate)
14276 (org-table-maybe-recalculate-line))
14277 (call-interactively 'org-table-align))
14278 ((org-at-item-checkbox-p)
14279 (call-interactively 'org-toggle-checkbox))
14280 ((org-at-item-p)
14281 (call-interactively 'org-maybe-renumber-ordered-list))
14282 ((save-excursion (beginning-of-line 1) (looking-at "#\\+BEGIN:"))
14283 ;; Dynamic block
14284 (beginning-of-line 1)
14285 (org-update-dblock))
14286 ((save-excursion (beginning-of-line 1) (looking-at "#\\+\\([A-Z]+\\)"))
14287 (cond
14288 ((equal (match-string 1) "TBLFM")
14289 ;; Recalculate the table before this line
14290 (save-excursion
14291 (beginning-of-line 1)
14292 (skip-chars-backward " \r\n\t")
14293 (if (org-at-table-p)
14294 (org-call-with-arg 'org-table-recalculate t))))
14296 (call-interactively 'org-mode-restart))))
14297 (t (error "C-c C-c can do nothing useful at this location.")))))
14299 (defun org-mode-restart ()
14300 "Restart Org-mode, to scan again for special lines.
14301 Also updates the keyword regular expressions."
14302 (interactive)
14303 (let ((org-inhibit-startup t)) (org-mode))
14304 (message "Org-mode restarted to refresh keyword and special line setup"))
14306 (defun org-kill-note-or-show-branches ()
14307 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
14308 (interactive)
14309 (if (not org-finish-function)
14310 (call-interactively 'show-branches)
14311 (let ((org-note-abort t))
14312 (funcall org-finish-function))))
14314 (defun org-return (&optional indent)
14315 "Goto next table row or insert a newline.
14316 Calls `org-table-next-row' or `newline', depending on context.
14317 See the individual commands for more information."
14318 (interactive)
14319 (cond
14320 ((bobp) (if indent (newline-and-indent) (newline)))
14321 ((and (org-at-heading-p)
14322 (looking-at
14323 (org-re "\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$")))
14324 (org-show-entry)
14325 (end-of-line 1)
14326 (newline))
14327 ((org-at-table-p)
14328 (org-table-justify-field-maybe)
14329 (call-interactively 'org-table-next-row))
14330 (t (if indent (newline-and-indent) (newline)))))
14332 (defun org-return-indent ()
14333 "Goto next table row or insert a newline and indent.
14334 Calls `org-table-next-row' or `newline-and-indent', depending on
14335 context. See the individual commands for more information."
14336 (interactive)
14337 (org-return t))
14339 (defun org-ctrl-c-star ()
14340 "Compute table, or change heading status of lines.
14341 Calls `org-table-recalculate' or `org-toggle-region-headlines',
14342 depending on context. This will also turn a plain list item or a normal
14343 line into a subheading."
14344 (interactive)
14345 (cond
14346 ((org-at-table-p)
14347 (call-interactively 'org-table-recalculate))
14348 ((org-region-active-p)
14349 ;; Convert all lines in region to list items
14350 (call-interactively 'org-toggle-region-headings))
14351 ((org-on-heading-p)
14352 (org-toggle-region-headings (point-at-bol)
14353 (min (1+ (point-at-eol)) (point-max))))
14354 ((org-at-item-p)
14355 ;; Convert to heading
14356 (let ((level (save-match-data
14357 (save-excursion
14358 (condition-case nil
14359 (progn
14360 (org-back-to-heading t)
14361 (funcall outline-level))
14362 (error 0))))))
14363 (replace-match
14364 (concat (make-string (org-get-valid-level level 1) ?*) " ") t t)))
14365 (t (org-toggle-region-headings (point-at-bol)
14366 (min (1+ (point-at-eol)) (point-max))))))
14368 (defun org-ctrl-c-minus ()
14369 "Insert separator line in table or modify bullet status of line.
14370 Also turns a plain line or a region of lines into list items.
14371 Calls `org-table-insert-hline', `org-toggle-region-items', or
14372 `org-cycle-list-bullet', depending on context."
14373 (interactive)
14374 (cond
14375 ((org-at-table-p)
14376 (call-interactively 'org-table-insert-hline))
14377 ((org-on-heading-p)
14378 ;; Convert to item
14379 (save-excursion
14380 (beginning-of-line 1)
14381 (if (looking-at "\\*+ ")
14382 (replace-match (concat (make-string (- (match-end 0) (point) 1) ?\ ) "- ")))))
14383 ((org-region-active-p)
14384 ;; Convert all lines in region to list items
14385 (call-interactively 'org-toggle-region-items))
14386 ((org-in-item-p)
14387 (call-interactively 'org-cycle-list-bullet))
14388 (t (org-toggle-region-items (point-at-bol)
14389 (min (1+ (point-at-eol)) (point-max))))))
14391 (defun org-toggle-region-items (beg end)
14392 "Convert all lines in region to list items.
14393 If the first line is already an item, convert all list items in the region
14394 to normal lines."
14395 (interactive "r")
14396 (let (l2 l)
14397 (save-excursion
14398 (goto-char end)
14399 (setq l2 (org-current-line))
14400 (goto-char beg)
14401 (beginning-of-line 1)
14402 (setq l (1- (org-current-line)))
14403 (if (org-at-item-p)
14404 ;; We already have items, de-itemize
14405 (while (< (setq l (1+ l)) l2)
14406 (when (org-at-item-p)
14407 (goto-char (match-beginning 2))
14408 (delete-region (match-beginning 2) (match-end 2))
14409 (and (looking-at "[ \t]+") (replace-match "")))
14410 (beginning-of-line 2))
14411 (while (< (setq l (1+ l)) l2)
14412 (unless (org-at-item-p)
14413 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
14414 (replace-match "\\1- \\2")))
14415 (beginning-of-line 2))))))
14417 (defun org-toggle-region-headings (beg end)
14418 "Convert all lines in region to list items.
14419 If the first line is already an item, convert all list items in the region
14420 to normal lines."
14421 (interactive "r")
14422 (let (l2 l)
14423 (save-excursion
14424 (goto-char end)
14425 (setq l2 (org-current-line))
14426 (goto-char beg)
14427 (beginning-of-line 1)
14428 (setq l (1- (org-current-line)))
14429 (if (org-on-heading-p)
14430 ;; We already have headlines, de-star them
14431 (while (< (setq l (1+ l)) l2)
14432 (when (org-on-heading-p t)
14433 (and (looking-at outline-regexp) (replace-match "")))
14434 (beginning-of-line 2))
14435 (let* ((stars (save-excursion
14436 (re-search-backward org-complex-heading-regexp nil t)
14437 (or (match-string 1) "*")))
14438 (add-stars (if org-odd-levels-only "**" "*"))
14439 (rpl (concat stars add-stars " \\2")))
14440 (while (< (setq l (1+ l)) l2)
14441 (unless (org-on-heading-p)
14442 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
14443 (replace-match rpl)))
14444 (beginning-of-line 2)))))))
14446 (defun org-meta-return (&optional arg)
14447 "Insert a new heading or wrap a region in a table.
14448 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
14449 See the individual commands for more information."
14450 (interactive "P")
14451 (cond
14452 ((org-at-table-p)
14453 (call-interactively 'org-table-wrap-region))
14454 (t (call-interactively 'org-insert-heading))))
14456 ;;; Menu entries
14458 ;; Define the Org-mode menus
14459 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
14460 '("Tbl"
14461 ["Align" org-ctrl-c-ctrl-c (org-at-table-p)]
14462 ["Next Field" org-cycle (org-at-table-p)]
14463 ["Previous Field" org-shifttab (org-at-table-p)]
14464 ["Next Row" org-return (org-at-table-p)]
14465 "--"
14466 ["Blank Field" org-table-blank-field (org-at-table-p)]
14467 ["Edit Field" org-table-edit-field (org-at-table-p)]
14468 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
14469 "--"
14470 ("Column"
14471 ["Move Column Left" org-metaleft (org-at-table-p)]
14472 ["Move Column Right" org-metaright (org-at-table-p)]
14473 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
14474 ["Insert Column" org-shiftmetaright (org-at-table-p)])
14475 ("Row"
14476 ["Move Row Up" org-metaup (org-at-table-p)]
14477 ["Move Row Down" org-metadown (org-at-table-p)]
14478 ["Delete Row" org-shiftmetaup (org-at-table-p)]
14479 ["Insert Row" org-shiftmetadown (org-at-table-p)]
14480 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
14481 "--"
14482 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
14483 ("Rectangle"
14484 ["Copy Rectangle" org-copy-special (org-at-table-p)]
14485 ["Cut Rectangle" org-cut-special (org-at-table-p)]
14486 ["Paste Rectangle" org-paste-special (org-at-table-p)]
14487 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
14488 "--"
14489 ("Calculate"
14490 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
14491 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
14492 ["Edit Formulas" org-table-edit-formulas (org-at-table-p)]
14493 "--"
14494 ["Recalculate line" org-table-recalculate (org-at-table-p)]
14495 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
14496 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
14497 "--"
14498 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
14499 "--"
14500 ["Sum Column/Rectangle" org-table-sum
14501 (or (org-at-table-p) (org-region-active-p))]
14502 ["Which Column?" org-table-current-column (org-at-table-p)])
14503 ["Debug Formulas"
14504 org-table-toggle-formula-debugger
14505 :style toggle :selected org-table-formula-debug]
14506 ["Show Col/Row Numbers"
14507 org-table-toggle-coordinate-overlays
14508 :style toggle :selected org-table-overlay-coordinates]
14509 "--"
14510 ["Create" org-table-create (and (not (org-at-table-p))
14511 org-enable-table-editor)]
14512 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
14513 ["Import from File" org-table-import (not (org-at-table-p))]
14514 ["Export to File" org-table-export (org-at-table-p)]
14515 "--"
14516 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
14518 (easy-menu-define org-org-menu org-mode-map "Org menu"
14519 '("Org"
14520 ("Show/Hide"
14521 ["Cycle Visibility" org-cycle (or (bobp) (outline-on-heading-p))]
14522 ["Cycle Global Visibility" org-shifttab (not (org-at-table-p))]
14523 ["Sparse Tree" org-occur t]
14524 ["Reveal Context" org-reveal t]
14525 ["Show All" show-all t]
14526 "--"
14527 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
14528 "--"
14529 ["New Heading" org-insert-heading t]
14530 ("Navigate Headings"
14531 ["Up" outline-up-heading t]
14532 ["Next" outline-next-visible-heading t]
14533 ["Previous" outline-previous-visible-heading t]
14534 ["Next Same Level" outline-forward-same-level t]
14535 ["Previous Same Level" outline-backward-same-level t]
14536 "--"
14537 ["Jump" org-goto t])
14538 ("Edit Structure"
14539 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
14540 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
14541 "--"
14542 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
14543 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
14544 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
14545 "--"
14546 ["Promote Heading" org-metaleft (not (org-at-table-p))]
14547 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
14548 ["Demote Heading" org-metaright (not (org-at-table-p))]
14549 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
14550 "--"
14551 ["Sort Region/Children" org-sort (not (org-at-table-p))]
14552 "--"
14553 ["Convert to odd levels" org-convert-to-odd-levels t]
14554 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
14555 ("Editing"
14556 ["Emphasis..." org-emphasize t])
14557 ("Archive"
14558 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
14559 ; ["Check and Tag Children" (org-toggle-archive-tag (4))
14560 ; :active t :keys "C-u C-c C-x C-a"]
14561 ["Sparse trees open ARCHIVE trees"
14562 (setq org-sparse-tree-open-archived-trees
14563 (not org-sparse-tree-open-archived-trees))
14564 :style toggle :selected org-sparse-tree-open-archived-trees]
14565 ["Cycling opens ARCHIVE trees"
14566 (setq org-cycle-open-archived-trees (not org-cycle-open-archived-trees))
14567 :style toggle :selected org-cycle-open-archived-trees]
14568 ["Agenda includes ARCHIVE trees"
14569 (setq org-agenda-skip-archived-trees (not org-agenda-skip-archived-trees))
14570 :style toggle :selected (not org-agenda-skip-archived-trees)]
14571 "--"
14572 ["Move Subtree to Archive" org-advertized-archive-subtree t]
14573 ; ["Check and Move Children" (org-archive-subtree '(4))
14574 ; :active t :keys "C-u C-c C-x C-s"]
14576 "--"
14577 ("TODO Lists"
14578 ["TODO/DONE/-" org-todo t]
14579 ("Select keyword"
14580 ["Next keyword" org-shiftright (org-on-heading-p)]
14581 ["Previous keyword" org-shiftleft (org-on-heading-p)]
14582 ["Complete Keyword" org-complete (assq :todo-keyword (org-context))]
14583 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))]
14584 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))])
14585 ["Show TODO Tree" org-show-todo-tree t]
14586 ["Global TODO list" org-todo-list t]
14587 "--"
14588 ["Set Priority" org-priority t]
14589 ["Priority Up" org-shiftup t]
14590 ["Priority Down" org-shiftdown t])
14591 ("TAGS and Properties"
14592 ["Set Tags" 'org-ctrl-c-ctrl-c (org-at-heading-p)]
14593 ["Change tag in region" 'org-change-tag-in-region (org-region-active-p)]
14594 "--"
14595 ["Set property" 'org-set-property t]
14596 ["Column view of properties" org-columns t]
14597 ["Insert Column View DBlock" org-insert-columns-dblock t])
14598 ("Dates and Scheduling"
14599 ["Timestamp" org-time-stamp t]
14600 ["Timestamp (inactive)" org-time-stamp-inactive t]
14601 ("Change Date"
14602 ["1 Day Later" org-shiftright t]
14603 ["1 Day Earlier" org-shiftleft t]
14604 ["1 ... Later" org-shiftup t]
14605 ["1 ... Earlier" org-shiftdown t])
14606 ["Compute Time Range" org-evaluate-time-range t]
14607 ["Schedule Item" org-schedule t]
14608 ["Deadline" org-deadline t]
14609 "--"
14610 ["Custom time format" org-toggle-time-stamp-overlays
14611 :style radio :selected org-display-custom-times]
14612 "--"
14613 ["Goto Calendar" org-goto-calendar t]
14614 ["Date from Calendar" org-date-from-calendar t])
14615 ("Logging work"
14616 ["Clock in" org-clock-in t]
14617 ["Clock out" org-clock-out t]
14618 ["Clock cancel" org-clock-cancel t]
14619 ["Goto running clock" org-clock-goto t]
14620 ["Display times" org-clock-display t]
14621 ["Create clock table" org-clock-report t]
14622 "--"
14623 ["Record DONE time"
14624 (progn (setq org-log-done (not org-log-done))
14625 (message "Switching to %s will %s record a timestamp"
14626 (car org-done-keywords)
14627 (if org-log-done "automatically" "not")))
14628 :style toggle :selected org-log-done])
14629 "--"
14630 ["Agenda Command..." org-agenda t]
14631 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
14632 ("File List for Agenda")
14633 ("Special views current file"
14634 ["TODO Tree" org-show-todo-tree t]
14635 ["Check Deadlines" org-check-deadlines t]
14636 ["Timeline" org-timeline t]
14637 ["Tags Tree" org-tags-sparse-tree t])
14638 "--"
14639 ("Hyperlinks"
14640 ["Store Link (Global)" org-store-link t]
14641 ["Insert Link" org-insert-link t]
14642 ["Follow Link" org-open-at-point t]
14643 "--"
14644 ["Next link" org-next-link t]
14645 ["Previous link" org-previous-link t]
14646 "--"
14647 ["Descriptive Links"
14648 (progn (org-add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
14649 :style radio :selected (member '(org-link) buffer-invisibility-spec)]
14650 ["Literal Links"
14651 (progn
14652 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
14653 :style radio :selected (not (member '(org-link) buffer-invisibility-spec))])
14654 "--"
14655 ["Export/Publish..." org-export t]
14656 ("LaTeX"
14657 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
14658 :selected org-cdlatex-mode]
14659 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
14660 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
14661 ["Modify math symbol" org-cdlatex-math-modify
14662 (org-inside-LaTeX-fragment-p)]
14663 ["Export LaTeX fragments as images"
14664 (setq org-export-with-LaTeX-fragments (not org-export-with-LaTeX-fragments))
14665 :style toggle :selected org-export-with-LaTeX-fragments])
14666 "--"
14667 ("Documentation"
14668 ["Show Version" org-version t]
14669 ["Info Documentation" org-info t])
14670 ("Customize"
14671 ["Browse Org Group" org-customize t]
14672 "--"
14673 ["Expand This Menu" org-create-customize-menu
14674 (fboundp 'customize-menu-create)])
14675 "--"
14676 ["Refresh setup" org-mode-restart t]
14679 (defun org-info (&optional node)
14680 "Read documentation for Org-mode in the info system.
14681 With optional NODE, go directly to that node."
14682 (interactive)
14683 (info (format "(org)%s" (or node ""))))
14685 (defun org-install-agenda-files-menu ()
14686 (let ((bl (buffer-list)))
14687 (save-excursion
14688 (while bl
14689 (set-buffer (pop bl))
14690 (if (org-mode-p) (setq bl nil)))
14691 (when (org-mode-p)
14692 (easy-menu-change
14693 '("Org") "File List for Agenda"
14694 (append
14695 (list
14696 ["Edit File List" (org-edit-agenda-file-list) t]
14697 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
14698 ["Remove Current File from List" org-remove-file t]
14699 ["Cycle through agenda files" org-cycle-agenda-files t]
14700 ["Occur in all agenda files" org-occur-in-agenda-files t]
14701 "--")
14702 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
14704 ;;;; Documentation
14706 (defun org-customize ()
14707 "Call the customize function with org as argument."
14708 (interactive)
14709 (customize-browse 'org))
14711 (defun org-create-customize-menu ()
14712 "Create a full customization menu for Org-mode, insert it into the menu."
14713 (interactive)
14714 (if (fboundp 'customize-menu-create)
14715 (progn
14716 (easy-menu-change
14717 '("Org") "Customize"
14718 `(["Browse Org group" org-customize t]
14719 "--"
14720 ,(customize-menu-create 'org)
14721 ["Set" Custom-set t]
14722 ["Save" Custom-save t]
14723 ["Reset to Current" Custom-reset-current t]
14724 ["Reset to Saved" Custom-reset-saved t]
14725 ["Reset to Standard Settings" Custom-reset-standard t]))
14726 (message "\"Org\"-menu now contains full customization menu"))
14727 (error "Cannot expand menu (outdated version of cus-edit.el)")))
14729 ;;;; Miscellaneous stuff
14731 ;;; Generally useful functions
14733 (defun org-force-self-insert (N)
14734 "Needed to enforce self-insert under remapping."
14735 (interactive "p")
14736 (self-insert-command N))
14738 (defun org-string-width (s)
14739 "Compute width of string, ignoring invisible characters.
14740 This ignores character with invisibility property `org-link', and also
14741 characters with property `org-cwidth', because these will become invisible
14742 upon the next fontification round."
14743 (let (b l)
14744 (when (or (eq t buffer-invisibility-spec)
14745 (assq 'org-link buffer-invisibility-spec))
14746 (while (setq b (text-property-any 0 (length s)
14747 'invisible 'org-link s))
14748 (setq s (concat (substring s 0 b)
14749 (substring s (or (next-single-property-change
14750 b 'invisible s) (length s)))))))
14751 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
14752 (setq s (concat (substring s 0 b)
14753 (substring s (or (next-single-property-change
14754 b 'org-cwidth s) (length s))))))
14755 (setq l (string-width s) b -1)
14756 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
14757 (setq l (- l (get-text-property b 'org-dwidth-n s))))
14761 (defun org-trim (s)
14762 "Remove whitespace at beginning and end of string."
14763 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
14764 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
14767 (defun org-wrap (string &optional width lines)
14768 "Wrap string to either a number of lines, or a width in characters.
14769 If WIDTH is non-nil, the string is wrapped to that width, however many lines
14770 that costs. If there is a word longer than WIDTH, the text is actually
14771 wrapped to the length of that word.
14772 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
14773 many lines, whatever width that takes.
14774 The return value is a list of lines, without newlines at the end."
14775 (let* ((words (org-split-string string "[ \t\n]+"))
14776 (maxword (apply 'max (mapcar 'org-string-width words)))
14777 w ll)
14778 (cond (width
14779 (org-do-wrap words (max maxword width)))
14780 (lines
14781 (setq w maxword)
14782 (setq ll (org-do-wrap words maxword))
14783 (if (<= (length ll) lines)
14785 (setq ll words)
14786 (while (> (length ll) lines)
14787 (setq w (1+ w))
14788 (setq ll (org-do-wrap words w)))
14789 ll))
14790 (t (error "Cannot wrap this")))))
14792 (defun org-do-wrap (words width)
14793 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
14794 (let (lines line)
14795 (while words
14796 (setq line (pop words))
14797 (while (and words (< (+ (length line) (length (car words))) width))
14798 (setq line (concat line " " (pop words))))
14799 (setq lines (push line lines)))
14800 (nreverse lines)))
14802 (defun org-split-string (string &optional separators)
14803 "Splits STRING into substrings at SEPARATORS.
14804 No empty strings are returned if there are matches at the beginning
14805 and end of string."
14806 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
14807 (start 0)
14808 notfirst
14809 (list nil))
14810 (while (and (string-match rexp string
14811 (if (and notfirst
14812 (= start (match-beginning 0))
14813 (< start (length string)))
14814 (1+ start) start))
14815 (< (match-beginning 0) (length string)))
14816 (setq notfirst t)
14817 (or (eq (match-beginning 0) 0)
14818 (and (eq (match-beginning 0) (match-end 0))
14819 (eq (match-beginning 0) start))
14820 (setq list
14821 (cons (substring string start (match-beginning 0))
14822 list)))
14823 (setq start (match-end 0)))
14824 (or (eq start (length string))
14825 (setq list
14826 (cons (substring string start)
14827 list)))
14828 (nreverse list)))
14830 (defun org-context ()
14831 "Return a list of contexts of the current cursor position.
14832 If several contexts apply, all are returned.
14833 Each context entry is a list with a symbol naming the context, and
14834 two positions indicating start and end of the context. Possible
14835 contexts are:
14837 :headline anywhere in a headline
14838 :headline-stars on the leading stars in a headline
14839 :todo-keyword on a TODO keyword (including DONE) in a headline
14840 :tags on the TAGS in a headline
14841 :priority on the priority cookie in a headline
14842 :item on the first line of a plain list item
14843 :item-bullet on the bullet/number of a plain list item
14844 :checkbox on the checkbox in a plain list item
14845 :table in an org-mode table
14846 :table-special on a special filed in a table
14847 :table-table in a table.el table
14848 :link on a hyperlink
14849 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
14850 :target on a <<target>>
14851 :radio-target on a <<<radio-target>>>
14852 :latex-fragment on a LaTeX fragment
14853 :latex-preview on a LaTeX fragment with overlayed preview image
14855 This function expects the position to be visible because it uses font-lock
14856 faces as a help to recognize the following contexts: :table-special, :link,
14857 and :keyword."
14858 (let* ((f (get-text-property (point) 'face))
14859 (faces (if (listp f) f (list f)))
14860 (p (point)) clist o)
14861 ;; First the large context
14862 (cond
14863 ((org-on-heading-p t)
14864 (push (list :headline (point-at-bol) (point-at-eol)) clist)
14865 (when (progn
14866 (beginning-of-line 1)
14867 (looking-at org-todo-line-tags-regexp))
14868 (push (org-point-in-group p 1 :headline-stars) clist)
14869 (push (org-point-in-group p 2 :todo-keyword) clist)
14870 (push (org-point-in-group p 4 :tags) clist))
14871 (goto-char p)
14872 (skip-chars-backward "^[\n\r \t") (or (eobp) (backward-char 1))
14873 (if (looking-at "\\[#[A-Z0-9]\\]")
14874 (push (org-point-in-group p 0 :priority) clist)))
14876 ((org-at-item-p)
14877 (push (org-point-in-group p 2 :item-bullet) clist)
14878 (push (list :item (point-at-bol)
14879 (save-excursion (org-end-of-item) (point)))
14880 clist)
14881 (and (org-at-item-checkbox-p)
14882 (push (org-point-in-group p 0 :checkbox) clist)))
14884 ((org-at-table-p)
14885 (push (list :table (org-table-begin) (org-table-end)) clist)
14886 (if (memq 'org-formula faces)
14887 (push (list :table-special
14888 (previous-single-property-change p 'face)
14889 (next-single-property-change p 'face)) clist)))
14890 ((org-at-table-p 'any)
14891 (push (list :table-table) clist)))
14892 (goto-char p)
14894 ;; Now the small context
14895 (cond
14896 ((org-at-timestamp-p)
14897 (push (org-point-in-group p 0 :timestamp) clist))
14898 ((memq 'org-link faces)
14899 (push (list :link
14900 (previous-single-property-change p 'face)
14901 (next-single-property-change p 'face)) clist))
14902 ((memq 'org-special-keyword faces)
14903 (push (list :keyword
14904 (previous-single-property-change p 'face)
14905 (next-single-property-change p 'face)) clist))
14906 ((org-on-target-p)
14907 (push (org-point-in-group p 0 :target) clist)
14908 (goto-char (1- (match-beginning 0)))
14909 (if (looking-at org-radio-target-regexp)
14910 (push (org-point-in-group p 0 :radio-target) clist))
14911 (goto-char p))
14912 ((setq o (car (delq nil
14913 (mapcar
14914 (lambda (x)
14915 (if (memq x org-latex-fragment-image-overlays) x))
14916 (org-overlays-at (point))))))
14917 (push (list :latex-fragment
14918 (org-overlay-start o) (org-overlay-end o)) clist)
14919 (push (list :latex-preview
14920 (org-overlay-start o) (org-overlay-end o)) clist))
14921 ((org-inside-LaTeX-fragment-p)
14922 ;; FIXME: positions wrong.
14923 (push (list :latex-fragment (point) (point)) clist)))
14925 (setq clist (nreverse (delq nil clist)))
14926 clist))
14928 ;; FIXME: Compare with at-regexp-p Do we need both?
14929 (defun org-in-regexp (re &optional nlines visually)
14930 "Check if point is inside a match of regexp.
14931 Normally only the current line is checked, but you can include NLINES extra
14932 lines both before and after point into the search.
14933 If VISUALLY is set, require that the cursor is not after the match but
14934 really on, so that the block visually is on the match."
14935 (catch 'exit
14936 (let ((pos (point))
14937 (eol (point-at-eol (+ 1 (or nlines 0))))
14938 (inc (if visually 1 0)))
14939 (save-excursion
14940 (beginning-of-line (- 1 (or nlines 0)))
14941 (while (re-search-forward re eol t)
14942 (if (and (<= (match-beginning 0) pos)
14943 (>= (+ inc (match-end 0)) pos))
14944 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
14946 (defun org-at-regexp-p (regexp)
14947 "Is point inside a match of REGEXP in the current line?"
14948 (catch 'exit
14949 (save-excursion
14950 (let ((pos (point)) (end (point-at-eol)))
14951 (beginning-of-line 1)
14952 (while (re-search-forward regexp end t)
14953 (if (and (<= (match-beginning 0) pos)
14954 (>= (match-end 0) pos))
14955 (throw 'exit t)))
14956 nil))))
14958 (defun org-occur-in-agenda-files (regexp &optional nlines)
14959 "Call `multi-occur' with buffers for all agenda files."
14960 (interactive "sOrg-files matching: \np")
14961 (let* ((files (org-agenda-files))
14962 (tnames (mapcar 'file-truename files))
14963 (extra org-agenda-text-search-extra-files)
14965 (while (setq f (pop extra))
14966 (unless (member (file-truename f) tnames)
14967 (add-to-list 'files f 'append)
14968 (add-to-list 'tnames (file-truename f) 'append)))
14969 (multi-occur
14970 (mapcar (lambda (x) (or (get-file-buffer x) (find-file-noselect x))) files)
14971 regexp)))
14973 (if (boundp 'occur-mode-find-occurrence-hook)
14974 ;; Emacs 23
14975 (add-hook 'occur-mode-find-occurrence-hook
14976 (lambda ()
14977 (when (org-mode-p)
14978 (org-reveal))))
14979 ;; Emacs 22
14980 (defadvice occur-mode-goto-occurrence
14981 (after org-occur-reveal activate)
14982 (and (org-mode-p) (org-reveal)))
14983 (defadvice occur-mode-goto-occurrence-other-window
14984 (after org-occur-reveal activate)
14985 (and (org-mode-p) (org-reveal)))
14986 (defadvice occur-mode-display-occurrence
14987 (after org-occur-reveal activate)
14988 (when (org-mode-p)
14989 (let ((pos (occur-mode-find-occurrence)))
14990 (with-current-buffer (marker-buffer pos)
14991 (save-excursion
14992 (goto-char pos)
14993 (org-reveal)))))))
14995 (defun org-uniquify (list)
14996 "Remove duplicate elements from LIST."
14997 (let (res)
14998 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
14999 res))
15001 (defun org-delete-all (elts list)
15002 "Remove all elements in ELTS from LIST."
15003 (while elts
15004 (setq list (delete (pop elts) list)))
15005 list)
15007 (defun org-back-over-empty-lines ()
15008 "Move backwards over witespace, to the beginning of the first empty line.
15009 Returns the number of empty lines passed."
15010 (let ((pos (point)))
15011 (skip-chars-backward " \t\n\r")
15012 (beginning-of-line 2)
15013 (goto-char (min (point) pos))
15014 (count-lines (point) pos)))
15016 (defun org-skip-whitespace ()
15017 (skip-chars-forward " \t\n\r"))
15019 (defun org-point-in-group (point group &optional context)
15020 "Check if POINT is in match-group GROUP.
15021 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
15022 match. If the match group does ot exist or point is not inside it,
15023 return nil."
15024 (and (match-beginning group)
15025 (>= point (match-beginning group))
15026 (<= point (match-end group))
15027 (if context
15028 (list context (match-beginning group) (match-end group))
15029 t)))
15031 (defun org-switch-to-buffer-other-window (&rest args)
15032 "Switch to buffer in a second window on the current frame.
15033 In particular, do not allow pop-up frames."
15034 (let (pop-up-frames special-display-buffer-names special-display-regexps
15035 special-display-function)
15036 (apply 'switch-to-buffer-other-window args)))
15038 (defun org-combine-plists (&rest plists)
15039 "Create a single property list from all plists in PLISTS.
15040 The process starts by copying the first list, and then setting properties
15041 from the other lists. Settings in the last list are the most significant
15042 ones and overrule settings in the other lists."
15043 (let ((rtn (copy-sequence (pop plists)))
15044 p v ls)
15045 (while plists
15046 (setq ls (pop plists))
15047 (while ls
15048 (setq p (pop ls) v (pop ls))
15049 (setq rtn (plist-put rtn p v))))
15050 rtn))
15052 (defun org-move-line-down (arg)
15053 "Move the current line down. With prefix argument, move it past ARG lines."
15054 (interactive "p")
15055 (let ((col (current-column))
15056 beg end pos)
15057 (beginning-of-line 1) (setq beg (point))
15058 (beginning-of-line 2) (setq end (point))
15059 (beginning-of-line (+ 1 arg))
15060 (setq pos (move-marker (make-marker) (point)))
15061 (insert (delete-and-extract-region beg end))
15062 (goto-char pos)
15063 (move-to-column col)))
15065 (defun org-move-line-up (arg)
15066 "Move the current line up. With prefix argument, move it past ARG lines."
15067 (interactive "p")
15068 (let ((col (current-column))
15069 beg end pos)
15070 (beginning-of-line 1) (setq beg (point))
15071 (beginning-of-line 2) (setq end (point))
15072 (beginning-of-line (- arg))
15073 (setq pos (move-marker (make-marker) (point)))
15074 (insert (delete-and-extract-region beg end))
15075 (goto-char pos)
15076 (move-to-column col)))
15078 (defun org-replace-escapes (string table)
15079 "Replace %-escapes in STRING with values in TABLE.
15080 TABLE is an association list with keys like \"%a\" and string values.
15081 The sequences in STRING may contain normal field width and padding information,
15082 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
15083 so values can contain further %-escapes if they are define later in TABLE."
15084 (let ((case-fold-search nil)
15085 e re rpl)
15086 (while (setq e (pop table))
15087 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
15088 (while (string-match re string)
15089 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
15090 (cdr e)))
15091 (setq string (replace-match rpl t t string))))
15092 string))
15095 (defun org-sublist (list start end)
15096 "Return a section of LIST, from START to END.
15097 Counting starts at 1."
15098 (let (rtn (c start))
15099 (setq list (nthcdr (1- start) list))
15100 (while (and list (<= c end))
15101 (push (pop list) rtn)
15102 (setq c (1+ c)))
15103 (nreverse rtn)))
15105 (defun org-find-base-buffer-visiting (file)
15106 "Like `find-buffer-visiting' but alway return the base buffer and
15107 not an indirect buffer."
15108 (let ((buf (find-buffer-visiting file)))
15109 (if buf
15110 (or (buffer-base-buffer buf) buf)
15111 nil)))
15113 (defun org-image-file-name-regexp ()
15114 "Return regexp matching the file names of images."
15115 (if (fboundp 'image-file-name-regexp)
15116 (image-file-name-regexp)
15117 (let ((image-file-name-extensions
15118 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
15119 "xbm" "xpm" "pbm" "pgm" "ppm")))
15120 (concat "\\."
15121 (regexp-opt (nconc (mapcar 'upcase
15122 image-file-name-extensions)
15123 image-file-name-extensions)
15125 "\\'"))))
15127 (defun org-file-image-p (file)
15128 "Return non-nil if FILE is an image."
15129 (save-match-data
15130 (string-match (org-image-file-name-regexp) file)))
15132 ;;; Paragraph filling stuff.
15133 ;; We want this to be just right, so use the full arsenal.
15135 (defun org-indent-line-function ()
15136 "Indent line like previous, but further if previous was headline or item."
15137 (interactive)
15138 (let* ((pos (point))
15139 (itemp (org-at-item-p))
15140 column bpos bcol tpos tcol bullet btype bullet-type)
15141 ;; Find the previous relevant line
15142 (beginning-of-line 1)
15143 (cond
15144 ((looking-at "#") (setq column 0))
15145 ((looking-at "\\*+ ") (setq column 0))
15147 (beginning-of-line 0)
15148 (while (and (not (bobp)) (looking-at "[ \t]*[\n:#|]"))
15149 (beginning-of-line 0))
15150 (cond
15151 ((looking-at "\\*+[ \t]+")
15152 (goto-char (match-end 0))
15153 (setq column (current-column)))
15154 ((org-in-item-p)
15155 (org-beginning-of-item)
15156 ; (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
15157 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*\\(\\[[- X]\\][ \t]*\\)?")
15158 (setq bpos (match-beginning 1) tpos (match-end 0)
15159 bcol (progn (goto-char bpos) (current-column))
15160 tcol (progn (goto-char tpos) (current-column))
15161 bullet (match-string 1)
15162 bullet-type (if (string-match "[0-9]" bullet) "n" bullet))
15163 (if (not itemp)
15164 (setq column tcol)
15165 (goto-char pos)
15166 (beginning-of-line 1)
15167 (if (looking-at "\\S-")
15168 (progn
15169 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
15170 (setq bullet (match-string 1)
15171 btype (if (string-match "[0-9]" bullet) "n" bullet))
15172 (setq column (if (equal btype bullet-type) bcol tcol)))
15173 (setq column (org-get-indentation)))))
15174 (t (setq column (org-get-indentation))))))
15175 (goto-char pos)
15176 (if (<= (current-column) (current-indentation))
15177 (indent-line-to column)
15178 (save-excursion (indent-line-to column)))
15179 (setq column (current-column))
15180 (beginning-of-line 1)
15181 (if (looking-at
15182 "\\([ \t]+\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
15183 (replace-match (concat "\\1" (format org-property-format
15184 (match-string 2) (match-string 3)))
15185 t nil))
15186 (move-to-column column)))
15188 (defun org-set-autofill-regexps ()
15189 (interactive)
15190 ;; In the paragraph separator we include headlines, because filling
15191 ;; text in a line directly attached to a headline would otherwise
15192 ;; fill the headline as well.
15193 (org-set-local 'comment-start-skip "^#+[ \t]*")
15194 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|]")
15195 ;; The paragraph starter includes hand-formatted lists.
15196 (org-set-local 'paragraph-start
15197 "\f\\|[ ]*$\\|\\*+ \\|\f\\|[ \t]*\\([-+*][ \t]+\\|[0-9]+[.)][ \t]+\\)\\|[ \t]*[:|]")
15198 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
15199 ;; But only if the user has not turned off tables or fixed-width regions
15200 (org-set-local
15201 'auto-fill-inhibit-regexp
15202 (concat "\\*+ \\|#\\+"
15203 "\\|[ \t]*" org-keyword-time-regexp
15204 (if (or org-enable-table-editor org-enable-fixed-width-editor)
15205 (concat
15206 "\\|[ \t]*["
15207 (if org-enable-table-editor "|" "")
15208 (if org-enable-fixed-width-editor ":" "")
15209 "]"))))
15210 ;; We use our own fill-paragraph function, to make sure that tables
15211 ;; and fixed-width regions are not wrapped. That function will pass
15212 ;; through to `fill-paragraph' when appropriate.
15213 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
15214 ; Adaptive filling: To get full control, first make sure that
15215 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
15216 (org-set-local 'adaptive-fill-regexp "\000")
15217 (org-set-local 'adaptive-fill-function
15218 'org-adaptive-fill-function)
15219 (org-set-local
15220 'align-mode-rules-list
15221 '((org-in-buffer-settings
15222 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
15223 (modes . '(org-mode))))))
15225 (defun org-fill-paragraph (&optional justify)
15226 "Re-align a table, pass through to fill-paragraph if no table."
15227 (let ((table-p (org-at-table-p))
15228 (table.el-p (org-at-table.el-p)))
15229 (cond ((and (equal (char-after (point-at-bol)) ?*)
15230 (save-excursion (goto-char (point-at-bol))
15231 (looking-at outline-regexp)))
15232 t) ; skip headlines
15233 (table.el-p t) ; skip table.el tables
15234 (table-p (org-table-align) t) ; align org-mode tables
15235 (t nil)))) ; call paragraph-fill
15237 ;; For reference, this is the default value of adaptive-fill-regexp
15238 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
15240 (defun org-adaptive-fill-function ()
15241 "Return a fill prefix for org-mode files.
15242 In particular, this makes sure hanging paragraphs for hand-formatted lists
15243 work correctly."
15244 (cond ((looking-at "#[ \t]+")
15245 (match-string 0))
15246 ((looking-at "[ \t]*\\([-*+] \\|[0-9]+[.)] \\)?")
15247 (save-excursion
15248 (goto-char (match-end 0))
15249 (make-string (current-column) ?\ )))
15250 (t nil)))
15252 ;;; Other stuff.
15254 (defun org-toggle-fixed-width-section (arg)
15255 "Toggle the fixed-width export.
15256 If there is no active region, the QUOTE keyword at the current headline is
15257 inserted or removed. When present, it causes the text between this headline
15258 and the next to be exported as fixed-width text, and unmodified.
15259 If there is an active region, this command adds or removes a colon as the
15260 first character of this line. If the first character of a line is a colon,
15261 this line is also exported in fixed-width font."
15262 (interactive "P")
15263 (let* ((cc 0)
15264 (regionp (org-region-active-p))
15265 (beg (if regionp (region-beginning) (point)))
15266 (end (if regionp (region-end)))
15267 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
15268 (case-fold-search nil)
15269 (re "[ \t]*\\(:\\)")
15270 off)
15271 (if regionp
15272 (save-excursion
15273 (goto-char beg)
15274 (setq cc (current-column))
15275 (beginning-of-line 1)
15276 (setq off (looking-at re))
15277 (while (> nlines 0)
15278 (setq nlines (1- nlines))
15279 (beginning-of-line 1)
15280 (cond
15281 (arg
15282 (move-to-column cc t)
15283 (insert ":\n")
15284 (forward-line -1))
15285 ((and off (looking-at re))
15286 (replace-match "" t t nil 1))
15287 ((not off) (move-to-column cc t) (insert ":")))
15288 (forward-line 1)))
15289 (save-excursion
15290 (org-back-to-heading)
15291 (if (looking-at (concat outline-regexp
15292 "\\( *\\<" org-quote-string "\\>[ \t]*\\)"))
15293 (replace-match "" t t nil 1)
15294 (if (looking-at outline-regexp)
15295 (progn
15296 (goto-char (match-end 0))
15297 (insert org-quote-string " "))))))))
15299 ;;;; Functions extending outline functionality
15301 (defun org-beginning-of-line (&optional arg)
15302 "Go to the beginning of the current line. If that is invisible, continue
15303 to a visible line beginning. This makes the function of C-a more intuitive.
15304 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
15305 first attempt, and only move to after the tags when the cursor is already
15306 beyond the end of the headline."
15307 (interactive "P")
15308 (let ((pos (point)))
15309 (beginning-of-line 1)
15310 (if (bobp)
15312 (backward-char 1)
15313 (if (org-invisible-p)
15314 (while (and (not (bobp)) (org-invisible-p))
15315 (backward-char 1)
15316 (beginning-of-line 1))
15317 (forward-char 1)))
15318 (when org-special-ctrl-a/e
15319 (cond
15320 ((and (looking-at org-todo-line-regexp)
15321 (= (char-after (match-end 1)) ?\ ))
15322 (goto-char
15323 (if (eq org-special-ctrl-a/e t)
15324 (cond ((> pos (match-beginning 3)) (match-beginning 3))
15325 ((= pos (point)) (match-beginning 3))
15326 (t (point)))
15327 (cond ((> pos (point)) (point))
15328 ((not (eq last-command this-command)) (point))
15329 (t (match-beginning 3))))))
15330 ((org-at-item-p)
15331 (goto-char
15332 (if (eq org-special-ctrl-a/e t)
15333 (cond ((> pos (match-end 4)) (match-end 4))
15334 ((= pos (point)) (match-end 4))
15335 (t (point)))
15336 (cond ((> pos (point)) (point))
15337 ((not (eq last-command this-command)) (point))
15338 (t (match-end 4))))))))))
15340 (defun org-end-of-line (&optional arg)
15341 "Go to the end of the line.
15342 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
15343 first attempt, and only move to after the tags when the cursor is already
15344 beyond the end of the headline."
15345 (interactive "P")
15346 (if (or (not org-special-ctrl-a/e)
15347 (not (org-on-heading-p)))
15348 (end-of-line arg)
15349 (let ((pos (point)))
15350 (beginning-of-line 1)
15351 (if (looking-at (org-re ".*?\\([ \t]*\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
15352 (if (eq org-special-ctrl-a/e t)
15353 (if (or (< pos (match-beginning 1))
15354 (= pos (match-end 0)))
15355 (goto-char (match-beginning 1))
15356 (goto-char (match-end 0)))
15357 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
15358 (goto-char (match-end 0))
15359 (goto-char (match-beginning 1))))
15360 (end-of-line arg)))))
15362 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
15363 (define-key org-mode-map "\C-e" 'org-end-of-line)
15365 (defun org-kill-line (&optional arg)
15366 "Kill line, to tags or end of line."
15367 (interactive "P")
15368 (cond
15369 ((or (not org-special-ctrl-k)
15370 (bolp)
15371 (not (org-on-heading-p)))
15372 (call-interactively 'kill-line))
15373 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$"))
15374 (kill-region (point) (match-beginning 1))
15375 (org-set-tags nil t))
15376 (t (kill-region (point) (point-at-eol)))))
15378 (define-key org-mode-map "\C-k" 'org-kill-line)
15380 (defun org-invisible-p ()
15381 "Check if point is at a character currently not visible."
15382 ;; Early versions of noutline don't have `outline-invisible-p'.
15383 (if (fboundp 'outline-invisible-p)
15384 (outline-invisible-p)
15385 (get-char-property (point) 'invisible)))
15387 (defun org-invisible-p2 ()
15388 "Check if point is at a character currently not visible."
15389 (save-excursion
15390 (if (and (eolp) (not (bobp))) (backward-char 1))
15391 ;; Early versions of noutline don't have `outline-invisible-p'.
15392 (if (fboundp 'outline-invisible-p)
15393 (outline-invisible-p)
15394 (get-char-property (point) 'invisible))))
15396 (defalias 'org-back-to-heading 'outline-back-to-heading)
15397 (defalias 'org-on-heading-p 'outline-on-heading-p)
15398 (defalias 'org-at-heading-p 'outline-on-heading-p)
15399 (defun org-at-heading-or-item-p ()
15400 (or (org-on-heading-p) (org-at-item-p)))
15402 (defun org-on-target-p ()
15403 (or (org-in-regexp org-radio-target-regexp)
15404 (org-in-regexp org-target-regexp)))
15406 (defun org-up-heading-all (arg)
15407 "Move to the heading line of which the present line is a subheading.
15408 This function considers both visible and invisible heading lines.
15409 With argument, move up ARG levels."
15410 (if (fboundp 'outline-up-heading-all)
15411 (outline-up-heading-all arg) ; emacs 21 version of outline.el
15412 (outline-up-heading arg t))) ; emacs 22 version of outline.el
15414 (defun org-up-heading-safe ()
15415 "Move to the heading line of which the present line is a subheading.
15416 This version will not throw an error. It will return the level of the
15417 headline found, or nil if no higher level is found."
15418 (let ((pos (point)) start-level level
15419 (re (concat "^" outline-regexp)))
15420 (catch 'exit
15421 (outline-back-to-heading t)
15422 (setq start-level (funcall outline-level))
15423 (if (equal start-level 1) (throw 'exit nil))
15424 (while (re-search-backward re nil t)
15425 (setq level (funcall outline-level))
15426 (if (< level start-level) (throw 'exit level)))
15427 nil)))
15429 (defun org-first-sibling-p ()
15430 "Is this heading the first child of its parents?"
15431 (interactive)
15432 (let ((re (concat "^" outline-regexp))
15433 level l)
15434 (unless (org-at-heading-p t)
15435 (error "Not at a heading"))
15436 (setq level (funcall outline-level))
15437 (save-excursion
15438 (if (not (re-search-backward re nil t))
15440 (setq l (funcall outline-level))
15441 (< l level)))))
15443 (defun org-goto-sibling (&optional previous)
15444 "Goto the next sibling, even if it is invisible.
15445 When PREVIOUS is set, go to the previous sibling instead. Returns t
15446 when a sibling was found. When none is found, return nil and don't
15447 move point."
15448 (let ((fun (if previous 're-search-backward 're-search-forward))
15449 (pos (point))
15450 (re (concat "^" outline-regexp))
15451 level l)
15452 (when (condition-case nil (org-back-to-heading t) (error nil))
15453 (setq level (funcall outline-level))
15454 (catch 'exit
15455 (or previous (forward-char 1))
15456 (while (funcall fun re nil t)
15457 (setq l (funcall outline-level))
15458 (when (< l level) (goto-char pos) (throw 'exit nil))
15459 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
15460 (goto-char pos)
15461 nil))))
15463 (defun org-show-siblings ()
15464 "Show all siblings of the current headline."
15465 (save-excursion
15466 (while (org-goto-sibling) (org-flag-heading nil)))
15467 (save-excursion
15468 (while (org-goto-sibling 'previous)
15469 (org-flag-heading nil))))
15471 (defun org-show-hidden-entry ()
15472 "Show an entry where even the heading is hidden."
15473 (save-excursion
15474 (org-show-entry)))
15476 (defun org-flag-heading (flag &optional entry)
15477 "Flag the current heading. FLAG non-nil means make invisible.
15478 When ENTRY is non-nil, show the entire entry."
15479 (save-excursion
15480 (org-back-to-heading t)
15481 ;; Check if we should show the entire entry
15482 (if entry
15483 (progn
15484 (org-show-entry)
15485 (save-excursion
15486 (and (outline-next-heading)
15487 (org-flag-heading nil))))
15488 (outline-flag-region (max (point-min) (1- (point)))
15489 (save-excursion (outline-end-of-heading) (point))
15490 flag))))
15492 (defun org-end-of-subtree (&optional invisible-OK to-heading)
15493 ;; This is an exact copy of the original function, but it uses
15494 ;; `org-back-to-heading', to make it work also in invisible
15495 ;; trees. And is uses an invisible-OK argument.
15496 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
15497 (org-back-to-heading invisible-OK)
15498 (let ((first t)
15499 (level (funcall outline-level)))
15500 (while (and (not (eobp))
15501 (or first (> (funcall outline-level) level)))
15502 (setq first nil)
15503 (outline-next-heading))
15504 (unless to-heading
15505 (if (memq (preceding-char) '(?\n ?\^M))
15506 (progn
15507 ;; Go to end of line before heading
15508 (forward-char -1)
15509 (if (memq (preceding-char) '(?\n ?\^M))
15510 ;; leave blank line before heading
15511 (forward-char -1))))))
15512 (point))
15514 (defun org-show-subtree ()
15515 "Show everything after this heading at deeper levels."
15516 (outline-flag-region
15517 (point)
15518 (save-excursion
15519 (outline-end-of-subtree) (outline-next-heading) (point))
15520 nil))
15522 (defun org-show-entry ()
15523 "Show the body directly following this heading.
15524 Show the heading too, if it is currently invisible."
15525 (interactive)
15526 (save-excursion
15527 (condition-case nil
15528 (progn
15529 (org-back-to-heading t)
15530 (outline-flag-region
15531 (max (point-min) (1- (point)))
15532 (save-excursion
15533 (re-search-forward
15534 (concat "[\r\n]\\(" outline-regexp "\\)") nil 'move)
15535 (or (match-beginning 1) (point-max)))
15536 nil))
15537 (error nil))))
15539 (defun org-make-options-regexp (kwds)
15540 "Make a regular expression for keyword lines."
15541 (concat
15543 "#?[ \t]*\\+\\("
15544 (mapconcat 'regexp-quote kwds "\\|")
15545 "\\):[ \t]*"
15546 "\\(.+\\)"))
15548 ;; Make isearch reveal the necessary context
15549 (defun org-isearch-end ()
15550 "Reveal context after isearch exits."
15551 (when isearch-success ; only if search was successful
15552 (if (featurep 'xemacs)
15553 ;; Under XEmacs, the hook is run in the correct place,
15554 ;; we directly show the context.
15555 (org-show-context 'isearch)
15556 ;; In Emacs the hook runs *before* restoring the overlays.
15557 ;; So we have to use a one-time post-command-hook to do this.
15558 ;; (Emacs 22 has a special variable, see function `org-mode')
15559 (unless (and (boundp 'isearch-mode-end-hook-quit)
15560 isearch-mode-end-hook-quit)
15561 ;; Only when the isearch was not quitted.
15562 (org-add-hook 'post-command-hook 'org-isearch-post-command
15563 'append 'local)))))
15565 (defun org-isearch-post-command ()
15566 "Remove self from hook, and show context."
15567 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
15568 (org-show-context 'isearch))
15571 ;;;; Integration with and fixes for other packages
15573 ;;; Imenu support
15575 (defvar org-imenu-markers nil
15576 "All markers currently used by Imenu.")
15577 (make-variable-buffer-local 'org-imenu-markers)
15579 (defun org-imenu-new-marker (&optional pos)
15580 "Return a new marker for use by Imenu, and remember the marker."
15581 (let ((m (make-marker)))
15582 (move-marker m (or pos (point)))
15583 (push m org-imenu-markers)
15586 (defun org-imenu-get-tree ()
15587 "Produce the index for Imenu."
15588 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
15589 (setq org-imenu-markers nil)
15590 (let* ((n org-imenu-depth)
15591 (re (concat "^" outline-regexp))
15592 (subs (make-vector (1+ n) nil))
15593 (last-level 0)
15594 m tree level head)
15595 (save-excursion
15596 (save-restriction
15597 (widen)
15598 (goto-char (point-max))
15599 (while (re-search-backward re nil t)
15600 (setq level (org-reduced-level (funcall outline-level)))
15601 (when (<= level n)
15602 (looking-at org-complex-heading-regexp)
15603 (setq head (org-match-string-no-properties 4)
15604 m (org-imenu-new-marker))
15605 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
15606 (if (>= level last-level)
15607 (push (cons head m) (aref subs level))
15608 (push (cons head (aref subs (1+ level))) (aref subs level))
15609 (loop for i from (1+ level) to n do (aset subs i nil)))
15610 (setq last-level level)))))
15611 (aref subs 1)))
15613 (eval-after-load "imenu"
15614 '(progn
15615 (add-hook 'imenu-after-jump-hook
15616 (lambda () (org-show-context 'org-goto)))))
15618 ;; Speedbar support
15620 (defvar org-speedbar-restriction-lock-overlay (org-make-overlay 1 1)
15621 "Overlay marking the agenda restriction line in speedbar.")
15622 (org-overlay-put org-speedbar-restriction-lock-overlay
15623 'face 'org-agenda-restriction-lock)
15624 (org-overlay-put org-speedbar-restriction-lock-overlay
15625 'help-echo "Agendas are currently limited to this item.")
15626 (org-detach-overlay org-speedbar-restriction-lock-overlay)
15628 (defun org-speedbar-set-agenda-restriction ()
15629 "Restrict future agenda commands to the location at point in speedbar.
15630 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
15631 (interactive)
15632 (let (p m tp np dir txt w)
15633 (cond
15634 ((setq p (text-property-any (point-at-bol) (point-at-eol)
15635 'org-imenu t))
15636 (setq m (get-text-property p 'org-imenu-marker))
15637 (save-excursion
15638 (save-restriction
15639 (set-buffer (marker-buffer m))
15640 (goto-char m)
15641 (org-agenda-set-restriction-lock 'subtree))))
15642 ((setq p (text-property-any (point-at-bol) (point-at-eol)
15643 'speedbar-function 'speedbar-find-file))
15644 (setq tp (previous-single-property-change
15645 (1+ p) 'speedbar-function)
15646 np (next-single-property-change
15647 tp 'speedbar-function)
15648 dir (speedbar-line-directory)
15649 txt (buffer-substring-no-properties (or tp (point-min))
15650 (or np (point-max))))
15651 (save-excursion
15652 (save-restriction
15653 (set-buffer (find-file-noselect
15654 (let ((default-directory dir))
15655 (expand-file-name txt))))
15656 (unless (org-mode-p)
15657 (error "Cannot restrict to non-Org-mode file"))
15658 (org-agenda-set-restriction-lock 'file))))
15659 (t (error "Don't know how to restrict Org-mode's agenda")))
15660 (org-move-overlay org-speedbar-restriction-lock-overlay
15661 (point-at-bol) (point-at-eol))
15662 (setq current-prefix-arg nil)
15663 (org-agenda-maybe-redo)))
15665 (eval-after-load "speedbar"
15666 '(progn
15667 (speedbar-add-supported-extension ".org")
15668 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
15669 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
15670 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
15671 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
15672 (add-hook 'speedbar-visiting-tag-hook
15673 (lambda () (org-show-context 'org-goto)))))
15676 ;;; Fixes and Hacks
15678 ;; Make flyspell not check words in links, to not mess up our keymap
15679 (defun org-mode-flyspell-verify ()
15680 "Don't let flyspell put overlays at active buttons."
15681 (not (get-text-property (point) 'keymap)))
15683 ;; Make `bookmark-jump' show the jump location if it was hidden.
15684 (eval-after-load "bookmark"
15685 '(if (boundp 'bookmark-after-jump-hook)
15686 ;; We can use the hook
15687 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
15688 ;; Hook not available, use advice
15689 (defadvice bookmark-jump (after org-make-visible activate)
15690 "Make the position visible."
15691 (org-bookmark-jump-unhide))))
15693 (defun org-bookmark-jump-unhide ()
15694 "Unhide the current position, to show the bookmark location."
15695 (and (org-mode-p)
15696 (or (org-invisible-p)
15697 (save-excursion (goto-char (max (point-min) (1- (point))))
15698 (org-invisible-p)))
15699 (org-show-context 'bookmark-jump)))
15701 ;; Make session.el ignore our circular variable
15702 (eval-after-load "session"
15703 '(add-to-list 'session-globals-exclude 'org-mark-ring))
15705 ;;;; Experimental code
15707 (defun org-closed-in-range ()
15708 "Sparse tree of items closed in a certain time range.
15709 Still experimental, may disappear in the future."
15710 (interactive)
15711 ;; Get the time interval from the user.
15712 (let* ((time1 (time-to-seconds
15713 (org-read-date nil 'to-time nil "Starting date: ")))
15714 (time2 (time-to-seconds
15715 (org-read-date nil 'to-time nil "End date:")))
15716 ;; callback function
15717 (callback (lambda ()
15718 (let ((time
15719 (time-to-seconds
15720 (apply 'encode-time
15721 (org-parse-time-string
15722 (match-string 1))))))
15723 ;; check if time in interval
15724 (and (>= time time1) (<= time time2))))))
15725 ;; make tree, check each match with the callback
15726 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
15729 ;;;; Finish up
15731 (provide 'org)
15733 (run-hooks 'org-load-hook)
15735 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
15736 ;;; org.el ends here
15739 (defun org-get-heading (&optional no-tags)
15740 "Return the heading of the current entry, without the stars."
15741 (save-excursion
15742 (org-back-to-heading t)
15743 (if (looking-at
15744 (if no-tags
15745 (org-re "\\*+[ \t]+\\([^\n\r]*?\\)\\([ \t]+:[[:alnum:]:_@]+:[ \t]*\\)?$")
15746 "\\*+[ \t]+\\([^\r\n]*\\)"))
15747 (match-string 1) "")))
15749 (defun org-get-category (&optional pos)
15750 "Get the category applying to position POS."
15751 (get-text-property (or pos (point)) 'org-category))
15753 (defun org-get-tags-at (&optional pos)
15754 "Get a list of all headline tags applicable at POS.
15755 POS defaults to point. If tags are inherited, the list contains
15756 the targets in the same sequence as the headlines appear, i.e.
15757 sthe tags of the current headline come last."
15758 (interactive)
15759 (let (tags ltags lastpos parent)
15760 (save-excursion
15761 (save-restriction
15762 (widen)
15763 (goto-char (or pos (point)))
15764 (save-match-data
15765 (condition-case nil
15766 (progn
15767 (org-back-to-heading t)
15768 (while (not (equal lastpos (point)))
15769 (setq lastpos (point))
15770 (when (looking-at (org-re "[^\r\n]+?:\\([[:alnum:]_@:]+\\):[ \t]*$"))
15771 (setq ltags (org-split-string
15772 (org-match-string-no-properties 1) ":"))
15773 (setq tags (append (org-remove-uniherited-tags ltags)
15774 tags)))
15775 (or org-use-tag-inheritance (error ""))
15776 (org-up-heading-all 1)
15777 (setq parent t)))
15778 (error nil))))
15779 tags)))
15781 (defun org-days-to-iso-week (days)
15782 "Return the iso week number."
15783 (require 'cal-iso)
15784 (car (calendar-iso-from-absolute days)))
15786 (defun org-small-year-to-year (year)
15787 "Convert 2-digit years into 4-digit years.
15788 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
15789 The year 2000 cannot be abbreviated. Any year lager than 99
15790 is retrned unchanged."
15791 (if (< year 38)
15792 (setq year (+ 2000 year))
15793 (if (< year 100)
15794 (setq year (+ 1900 year))))
15795 year)