Moved the command org-iswitchb into the core.
[org-mode.git] / lisp / org.el
blobe20027ddbce6e64dd8356bd5a1f0aca4b517d0bf
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-3
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-3"
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-bibtex org-gnus org-info org-infojs org-irc org-mhe org-rmail org-vm org-wl)
143 "Modules that should always be loaded together with org.el.
144 If a description starts with <C>, the file is not part of emacs
145 and loading it will require that you have downloaded and properly installed
146 the org-mode distribution.
148 You can also use this system to load external packages (i.e. neither Org
149 core modules, not modules from the CONTRIB directory). Just add symbols
150 to the end of the list. If the package is called org-xyz.e, then you need
151 to add the symbol `xyz', and the package must have a call to
153 (provide 'org-xyz)"
154 :group 'org
155 :set 'org-set-modules
156 :type
157 '(set :greedy t
158 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
159 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
160 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
161 (const :tag " info: Links to Info nodes" org-info)
162 (const :tag " infojs: Set up Sebastian Rose's JavaScript org-info.js" org-infojs)
163 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
164 (const :tag " mac-message: Links to messages in Apple Mail" org-mac-message)
165 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
166 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
167 (const :tag " vm: Links to VM folders/messages" org-vm)
168 (const :tag " wl: Links to Wanderlust folders/messages" org-wl)
169 (const :tag " mouse: Additional mouse support" org-mouse)
171 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
172 (const :tag "C bookmark: Org links to bookmarks" org-bookmark)
173 (const :tag "C depend: TODO dependencies for Org-mode" org-depend)
174 (const :tag "C elisp-symbol: Org links to emacs-lisp symbols" org-elisp-symbol)
175 (const :tag "C expiry: Expiry mechanism for Org entries" org-expiry)
176 (const :tag "C id: Global id's for identifying entries" org-id)
177 (const :tag "C interactive-query: Interactive modification of tags query" org-interactive-query)
178 (const :tag "C mairix: Hook mairix search into Org for different MUAs" org-mairix)
179 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
180 (const :tag "C mew: Support for links to messages in Mew" org-mew)
181 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
182 (const :tag "C registry: A registry for Org links" org-registry)
183 (const :tag "C org2rem: Convert org appointments into reminders" org2rem)
184 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
185 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)
186 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
189 (defgroup org-startup nil
190 "Options concerning startup of Org-mode."
191 :tag "Org Startup"
192 :group 'org)
194 (defcustom org-startup-folded t
195 "Non-nil means, entering Org-mode will switch to OVERVIEW.
196 This can also be configured on a per-file basis by adding one of
197 the following lines anywhere in the buffer:
199 #+STARTUP: fold
200 #+STARTUP: nofold
201 #+STARTUP: content"
202 :group 'org-startup
203 :type '(choice
204 (const :tag "nofold: show all" nil)
205 (const :tag "fold: overview" t)
206 (const :tag "content: all headlines" content)))
208 (defcustom org-startup-truncated t
209 "Non-nil means, entering Org-mode will set `truncate-lines'.
210 This is useful since some lines containing links can be very long and
211 uninteresting. Also tables look terrible when wrapped."
212 :group 'org-startup
213 :type 'boolean)
215 (defcustom org-startup-align-all-tables nil
216 "Non-nil means, align all tables when visiting a file.
217 This is useful when the column width in tables is forced with <N> cookies
218 in table fields. Such tables will look correct only after the first re-align.
219 This can also be configured on a per-file basis by adding one of
220 the following lines anywhere in the buffer:
221 #+STARTUP: align
222 #+STARTUP: noalign"
223 :group 'org-startup
224 :type 'boolean)
226 (defcustom org-insert-mode-line-in-empty-file nil
227 "Non-nil means insert the first line setting Org-mode in empty files.
228 When the function `org-mode' is called interactively in an empty file, this
229 normally means that the file name does not automatically trigger Org-mode.
230 To ensure that the file will always be in Org-mode in the future, a
231 line enforcing Org-mode will be inserted into the buffer, if this option
232 has been set."
233 :group 'org-startup
234 :type 'boolean)
236 (defcustom org-replace-disputed-keys nil
237 "Non-nil means use alternative key bindings for some keys.
238 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
239 These keys are also used by other packages like `CUA-mode' or `windmove.el'.
240 If you want to use Org-mode together with one of these other modes,
241 or more generally if you would like to move some Org-mode commands to
242 other keys, set this variable and configure the keys with the variable
243 `org-disputed-keys'.
245 This option is only relevant at load-time of Org-mode, and must be set
246 *before* org.el is loaded. Changing it requires a restart of Emacs to
247 become effective."
248 :group 'org-startup
249 :type 'boolean)
251 (if (fboundp 'defvaralias)
252 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys))
254 (defcustom org-disputed-keys
255 '(([(shift up)] . [(meta p)])
256 ([(shift down)] . [(meta n)])
257 ([(shift left)] . [(meta -)])
258 ([(shift right)] . [(meta +)])
259 ([(control shift right)] . [(meta shift +)])
260 ([(control shift left)] . [(meta shift -)]))
261 "Keys for which Org-mode and other modes compete.
262 This is an alist, cars are the default keys, second element specifies
263 the alternative to use when `org-replace-disputed-keys' is t.
265 Keys can be specified in any syntax supported by `define-key'.
266 The value of this option takes effect only at Org-mode's startup,
267 therefore you'll have to restart Emacs to apply it after changing."
268 :group 'org-startup
269 :type 'alist)
271 (defun org-key (key)
272 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
273 Or return the original if not disputed."
274 (if org-replace-disputed-keys
275 (let* ((nkey (key-description key))
276 (x (org-find-if (lambda (x)
277 (equal (key-description (car x)) nkey))
278 org-disputed-keys)))
279 (if x (cdr x) key))
280 key))
282 (defun org-find-if (predicate seq)
283 (catch 'exit
284 (while seq
285 (if (funcall predicate (car seq))
286 (throw 'exit (car seq))
287 (pop seq)))))
289 (defun org-defkey (keymap key def)
290 "Define a key, possibly translated, as returned by `org-key'."
291 (define-key keymap (org-key key) def))
293 (defcustom org-ellipsis nil
294 "The ellipsis to use in the Org-mode outline.
295 When nil, just use the standard three dots. When a string, use that instead,
296 When a face, use the standart 3 dots, but with the specified face.
297 The change affects only Org-mode (which will then use its own display table).
298 Changing this requires executing `M-x org-mode' in a buffer to become
299 effective."
300 :group 'org-startup
301 :type '(choice (const :tag "Default" nil)
302 (face :tag "Face" :value org-warning)
303 (string :tag "String" :value "...#")))
305 (defvar org-display-table nil
306 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
308 (defgroup org-keywords nil
309 "Keywords in Org-mode."
310 :tag "Org Keywords"
311 :group 'org)
313 (defcustom org-deadline-string "DEADLINE:"
314 "String to mark deadline entries.
315 A deadline is this string, followed by a time stamp. Should be a word,
316 terminated by a colon. You can insert a schedule keyword and
317 a timestamp with \\[org-deadline].
318 Changes become only effective after restarting Emacs."
319 :group 'org-keywords
320 :type 'string)
322 (defcustom org-scheduled-string "SCHEDULED:"
323 "String to mark scheduled TODO entries.
324 A schedule is this string, followed by a time stamp. Should be a word,
325 terminated by a colon. You can insert a schedule keyword and
326 a timestamp with \\[org-schedule].
327 Changes become only effective after restarting Emacs."
328 :group 'org-keywords
329 :type 'string)
331 (defcustom org-closed-string "CLOSED:"
332 "String used as the prefix for timestamps logging closing a TODO entry."
333 :group 'org-keywords
334 :type 'string)
336 (defcustom org-clock-string "CLOCK:"
337 "String used as prefix for timestamps clocking work hours on an item."
338 :group 'org-keywords
339 :type 'string)
341 (defcustom org-comment-string "COMMENT"
342 "Entries starting with this keyword will never be exported.
343 An entry can be toggled between COMMENT and normal with
344 \\[org-toggle-comment].
345 Changes become only effective after restarting Emacs."
346 :group 'org-keywords
347 :type 'string)
349 (defcustom org-quote-string "QUOTE"
350 "Entries starting with this keyword will be exported in fixed-width font.
351 Quoting applies only to the text in the entry following the headline, and does
352 not extend beyond the next headline, even if that is lower level.
353 An entry can be toggled between QUOTE and normal with
354 \\[org-toggle-fixed-width-section]."
355 :group 'org-keywords
356 :type 'string)
358 (defconst org-repeat-re
359 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*\\([.+]?\\+[0-9]+[dwmy]\\)"
360 "Regular expression for specifying repeated events.
361 After a match, group 1 contains the repeat expression.")
363 (defgroup org-structure nil
364 "Options concerning the general structure of Org-mode files."
365 :tag "Org Structure"
366 :group 'org)
368 (defgroup org-reveal-location nil
369 "Options about how to make context of a location visible."
370 :tag "Org Reveal Location"
371 :group 'org-structure)
373 (defconst org-context-choice
374 '(choice
375 (const :tag "Always" t)
376 (const :tag "Never" nil)
377 (repeat :greedy t :tag "Individual contexts"
378 (cons
379 (choice :tag "Context"
380 (const agenda)
381 (const org-goto)
382 (const occur-tree)
383 (const tags-tree)
384 (const link-search)
385 (const mark-goto)
386 (const bookmark-jump)
387 (const isearch)
388 (const default))
389 (boolean))))
390 "Contexts for the reveal options.")
392 (defcustom org-show-hierarchy-above '((default . t))
393 "Non-nil means, show full hierarchy when revealing a location.
394 Org-mode often shows locations in an org-mode file which might have
395 been invisible before. When this is set, the hierarchy of headings
396 above the exposed location is shown.
397 Turning this off for example for sparse trees makes them very compact.
398 Instead of t, this can also be an alist specifying this option for different
399 contexts. Valid contexts are
400 agenda when exposing an entry from the agenda
401 org-goto when using the command `org-goto' on key C-c C-j
402 occur-tree when using the command `org-occur' on key C-c /
403 tags-tree when constructing a sparse tree based on tags matches
404 link-search when exposing search matches associated with a link
405 mark-goto when exposing the jump goal of a mark
406 bookmark-jump when exposing a bookmark location
407 isearch when exiting from an incremental search
408 default default for all contexts not set explicitly"
409 :group 'org-reveal-location
410 :type org-context-choice)
412 (defcustom org-show-following-heading '((default . nil))
413 "Non-nil means, show following heading when revealing a location.
414 Org-mode often shows locations in an org-mode file which might have
415 been invisible before. When this is set, the heading following the
416 match is shown.
417 Turning this off for example for sparse trees makes them very compact,
418 but makes it harder to edit the location of the match. In such a case,
419 use the command \\[org-reveal] to show more context.
420 Instead of t, this can also be an alist specifying this option for different
421 contexts. See `org-show-hierarchy-above' for valid contexts."
422 :group 'org-reveal-location
423 :type org-context-choice)
425 (defcustom org-show-siblings '((default . nil) (isearch t))
426 "Non-nil means, show all sibling heading when revealing a location.
427 Org-mode often shows locations in an org-mode file which might have
428 been invisible before. When this is set, the sibling of the current entry
429 heading are all made visible. If `org-show-hierarchy-above' is t,
430 the same happens on each level of the hierarchy above the current entry.
432 By default this is on for the isearch context, off for all other contexts.
433 Turning this off for example for sparse trees makes them very compact,
434 but makes it harder to edit the location of the match. In such a case,
435 use the command \\[org-reveal] to show more context.
436 Instead of t, this can also be an alist specifying this option for different
437 contexts. See `org-show-hierarchy-above' for valid contexts."
438 :group 'org-reveal-location
439 :type org-context-choice)
441 (defcustom org-show-entry-below '((default . nil))
442 "Non-nil means, show the entry below a headline when revealing a location.
443 Org-mode often shows locations in an org-mode file which might have
444 been invisible before. When this is set, the text below the headline that is
445 exposed is also shown.
447 By default this is off for all contexts.
448 Instead of t, this can also be an alist specifying this option for different
449 contexts. See `org-show-hierarchy-above' for valid contexts."
450 :group 'org-reveal-location
451 :type org-context-choice)
453 (defcustom org-indirect-buffer-display 'other-window
454 "How should indirect tree buffers be displayed?
455 This applies to indirect buffers created with the commands
456 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
457 Valid values are:
458 current-window Display in the current window
459 other-window Just display in another window.
460 dedicated-frame Create one new frame, and re-use it each time.
461 new-frame Make a new frame each time. Note that in this case
462 previously-made indirect buffers are kept, and you need to
463 kill these buffers yourself."
464 :group 'org-structure
465 :group 'org-agenda-windows
466 :type '(choice
467 (const :tag "In current window" current-window)
468 (const :tag "In current frame, other window" other-window)
469 (const :tag "Each time a new frame" new-frame)
470 (const :tag "One dedicated frame" dedicated-frame)))
472 (defgroup org-cycle nil
473 "Options concerning visibility cycling in Org-mode."
474 :tag "Org Cycle"
475 :group 'org-structure)
477 (defcustom org-drawers '("PROPERTIES" "CLOCK")
478 "Names of drawers. Drawers are not opened by cycling on the headline above.
479 Drawers only open with a TAB on the drawer line itself. A drawer looks like
480 this:
481 :DRAWERNAME:
482 .....
483 :END:
484 The drawer \"PROPERTIES\" is special for capturing properties through
485 the property API.
487 Drawers can be defined on the per-file basis with a line like:
489 #+DRAWERS: HIDDEN STATE PROPERTIES"
490 :group 'org-structure
491 :type '(repeat (string :tag "Drawer Name")))
493 (defcustom org-cycle-global-at-bob nil
494 "Cycle globally if cursor is at beginning of buffer and not at a headline.
495 This makes it possible to do global cycling without having to use S-TAB or
496 C-u TAB. For this special case to work, the first line of the buffer
497 must not be a headline - it may be empty ot some other text. When used in
498 this way, `org-cycle-hook' is disables temporarily, to make sure the
499 cursor stays at the beginning of the buffer.
500 When this option is nil, don't do anything special at the beginning
501 of the buffer."
502 :group 'org-cycle
503 :type 'boolean)
505 (defcustom org-cycle-emulate-tab t
506 "Where should `org-cycle' emulate TAB.
507 nil Never
508 white Only in completely white lines
509 whitestart Only at the beginning of lines, before the first non-white char
510 t Everywhere except in headlines
511 exc-hl-bol Everywhere except at the start of a headline
512 If TAB is used in a place where it does not emulate TAB, the current subtree
513 visibility is cycled."
514 :group 'org-cycle
515 :type '(choice (const :tag "Never" nil)
516 (const :tag "Only in completely white lines" white)
517 (const :tag "Before first char in a line" whitestart)
518 (const :tag "Everywhere except in headlines" t)
519 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)
522 (defcustom org-cycle-separator-lines 2
523 "Number of empty lines needed to keep an empty line between collapsed trees.
524 If you leave an empty line between the end of a subtree and the following
525 headline, this empty line is hidden when the subtree is folded.
526 Org-mode will leave (exactly) one empty line visible if the number of
527 empty lines is equal or larger to the number given in this variable.
528 So the default 2 means, at least 2 empty lines after the end of a subtree
529 are needed to produce free space between a collapsed subtree and the
530 following headline.
532 Special case: when 0, never leave empty lines in collapsed view."
533 :group 'org-cycle
534 :type 'integer)
536 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
537 org-cycle-hide-drawers
538 org-cycle-show-empty-lines
539 org-optimize-window-after-visibility-change)
540 "Hook that is run after `org-cycle' has changed the buffer visibility.
541 The function(s) in this hook must accept a single argument which indicates
542 the new state that was set by the most recent `org-cycle' command. The
543 argument is a symbol. After a global state change, it can have the values
544 `overview', `content', or `all'. After a local state change, it can have
545 the values `folded', `children', or `subtree'."
546 :group 'org-cycle
547 :type 'hook)
549 (defgroup org-edit-structure nil
550 "Options concerning structure editing in Org-mode."
551 :tag "Org Edit Structure"
552 :group 'org-structure)
554 (defcustom org-odd-levels-only nil
555 "Non-nil means, skip even levels and only use odd levels for the outline.
556 This has the effect that two stars are being added/taken away in
557 promotion/demotion commands. It also influences how levels are
558 handled by the exporters.
559 Changing it requires restart of `font-lock-mode' to become effective
560 for fontification also in regions already fontified.
561 You may also set this on a per-file basis by adding one of the following
562 lines to the buffer:
564 #+STARTUP: odd
565 #+STARTUP: oddeven"
566 :group 'org-edit-structure
567 :group 'org-font-lock
568 :type 'boolean)
570 (defcustom org-adapt-indentation t
571 "Non-nil means, adapt indentation when promoting and demoting.
572 When this is set and the *entire* text in an entry is indented, the
573 indentation is increased by one space in a demotion command, and
574 decreased by one in a promotion command. If any line in the entry
575 body starts at column 0, indentation is not changed at all."
576 :group 'org-edit-structure
577 :type 'boolean)
579 (defcustom org-special-ctrl-a/e nil
580 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
581 When t, `C-a' will bring back the cursor to the beginning of the
582 headline text, i.e. after the stars and after a possible TODO keyword.
583 In an item, this will be the position after the bullet.
584 When the cursor is already at that position, another `C-a' will bring
585 it to the beginning of the line.
586 `C-e' will jump to the end of the headline, ignoring the presence of tags
587 in the headline. A second `C-e' will then jump to the true end of the
588 line, after any tags.
589 When set to the symbol `reversed', the first `C-a' or `C-e' works normally,
590 and only a directly following, identical keypress will bring the cursor
591 to the special positions."
592 :group 'org-edit-structure
593 :type '(choice
594 (const :tag "off" nil)
595 (const :tag "after bullet first" t)
596 (const :tag "border first" reversed)))
598 (if (fboundp 'defvaralias)
599 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e))
601 (defcustom org-special-ctrl-k nil
602 "Non-nil means `C-k' will behave specially in headlines.
603 When nil, `C-k' will call the default `kill-line' command.
604 When t, the following will happen while the cursor is in the headline:
606 - When the cursor is at the beginning of a headline, kill the entire
607 line and possible the folded subtree below the line.
608 - When in the middle of the headline text, kill the headline up to the tags.
609 - When after the headline text, kill the tags."
610 :group 'org-edit-structure
611 :type 'boolean)
613 (defcustom org-M-RET-may-split-line '((default . t))
614 "Non-nil means, M-RET will split the line at the cursor position.
615 When nil, it will go to the end of the line before making a
616 new line.
617 You may also set this option in a different way for different
618 contexts. Valid contexts are:
620 headline when creating a new headline
621 item when creating a new item
622 table in a table field
623 default the value to be used for all contexts not explicitly
624 customized"
625 :group 'org-structure
626 :group 'org-table
627 :type '(choice
628 (const :tag "Always" t)
629 (const :tag "Never" nil)
630 (repeat :greedy t :tag "Individual contexts"
631 (cons
632 (choice :tag "Context"
633 (const headline)
634 (const item)
635 (const table)
636 (const default))
637 (boolean)))))
640 (defcustom org-blank-before-new-entry '((heading . nil)
641 (plain-list-item . nil))
642 "Should `org-insert-heading' leave a blank line before new heading/item?
643 The value is an alist, with `heading' and `plain-list-item' as car,
644 and a boolean flag as cdr."
645 :group 'org-edit-structure
646 :type '(list
647 (cons (const heading) (boolean))
648 (cons (const plain-list-item) (boolean))))
650 (defcustom org-insert-heading-hook nil
651 "Hook being run after inserting a new heading."
652 :group 'org-edit-structure
653 :type 'hook)
655 (defcustom org-enable-fixed-width-editor t
656 "Non-nil means, lines starting with \":\" are treated as fixed-width.
657 This currently only means, they are never auto-wrapped.
658 When nil, such lines will be treated like ordinary lines.
659 See also the QUOTE keyword."
660 :group 'org-edit-structure
661 :type 'boolean)
663 (defcustom org-goto-auto-isearch t
664 "Non-nil means, typing characters in org-goto starts incremental search."
665 :group 'org-edit-structure
666 :type 'boolean)
668 (defgroup org-sparse-trees nil
669 "Options concerning sparse trees in Org-mode."
670 :tag "Org Sparse Trees"
671 :group 'org-structure)
673 (defcustom org-highlight-sparse-tree-matches t
674 "Non-nil means, highlight all matches that define a sparse tree.
675 The highlights will automatically disappear the next time the buffer is
676 changed by an edit command."
677 :group 'org-sparse-trees
678 :type 'boolean)
680 (defcustom org-remove-highlights-with-change t
681 "Non-nil means, any change to the buffer will remove temporary highlights.
682 Such highlights are created by `org-occur' and `org-clock-display'.
683 When nil, `C-c C-c needs to be used to get rid of the highlights.
684 The highlights created by `org-preview-latex-fragment' always need
685 `C-c C-c' to be removed."
686 :group 'org-sparse-trees
687 :group 'org-time
688 :type 'boolean)
691 (defcustom org-occur-hook '(org-first-headline-recenter)
692 "Hook that is run after `org-occur' has constructed a sparse tree.
693 This can be used to recenter the window to show as much of the structure
694 as possible."
695 :group 'org-sparse-trees
696 :type 'hook)
698 (defgroup org-plain-lists nil
699 "Options concerning plain lists in Org-mode."
700 :tag "Org Plain lists"
701 :group 'org-structure)
703 (defcustom org-cycle-include-plain-lists nil
704 "Non-nil means, include plain lists into visibility cycling.
705 This means that during cycling, plain list items will *temporarily* be
706 interpreted as outline headlines with a level given by 1000+i where i is the
707 indentation of the bullet. In all other operations, plain list items are
708 not seen as headlines. For example, you cannot assign a TODO keyword to
709 such an item."
710 :group 'org-plain-lists
711 :type 'boolean)
713 (defcustom org-plain-list-ordered-item-terminator t
714 "The character that makes a line with leading number an ordered list item.
715 Valid values are ?. and ?\). To get both terminators, use t. While
716 ?. may look nicer, it creates the danger that a line with leading
717 number may be incorrectly interpreted as an item. ?\) therefore is
718 the safe choice."
719 :group 'org-plain-lists
720 :type '(choice (const :tag "dot like in \"2.\"" ?.)
721 (const :tag "paren like in \"2)\"" ?\))
722 (const :tab "both" t)))
724 (defcustom org-auto-renumber-ordered-lists t
725 "Non-nil means, automatically renumber ordered plain lists.
726 Renumbering happens when the sequence have been changed with
727 \\[org-shiftmetaup] or \\[org-shiftmetadown]. After other editing commands,
728 use \\[org-ctrl-c-ctrl-c] to trigger renumbering."
729 :group 'org-plain-lists
730 :type 'boolean)
732 (defcustom org-provide-checkbox-statistics t
733 "Non-nil means, update checkbox statistics after insert and toggle.
734 When this is set, checkbox statistics is updated each time you either insert
735 a new checkbox with \\[org-insert-todo-heading] or toggle a checkbox
736 with \\[org-ctrl-c-ctrl-c\\]."
737 :group 'org-plain-lists
738 :type 'boolean)
740 (defgroup org-archive nil
741 "Options concerning archiving in Org-mode."
742 :tag "Org Archive"
743 :group 'org-structure)
745 (defcustom org-archive-tag "ARCHIVE"
746 "The tag that marks a subtree as archived.
747 An archived subtree does not open during visibility cycling, and does
748 not contribute to the agenda listings.
749 After changing this, font-lock must be restarted in the relevant buffers to
750 get the proper fontification."
751 :group 'org-archive
752 :group 'org-keywords
753 :type 'string)
755 (defcustom org-agenda-skip-archived-trees t
756 "Non-nil means, the agenda will skip any items located in archived trees.
757 An archived tree is a tree marked with the tag ARCHIVE."
758 :group 'org-archive
759 :group 'org-agenda-skip
760 :type 'boolean)
762 (defcustom org-cycle-open-archived-trees nil
763 "Non-nil means, `org-cycle' will open archived trees.
764 An archived tree is a tree marked with the tag ARCHIVE.
765 When nil, archived trees will stay folded. You can still open them with
766 normal outline commands like `show-all', but not with the cycling commands."
767 :group 'org-archive
768 :group 'org-cycle
769 :type 'boolean)
771 (defcustom org-sparse-tree-open-archived-trees nil
772 "Non-nil means sparse tree construction shows matches in archived trees.
773 When nil, matches in these trees are highlighted, but the trees are kept in
774 collapsed state."
775 :group 'org-archive
776 :group 'org-sparse-trees
777 :type 'boolean)
779 (defcustom org-archive-location "%s_archive::"
780 "The location where subtrees should be archived.
781 This string consists of two parts, separated by a double-colon.
783 The first part is a file name - when omitted, archiving happens in the same
784 file. %s will be replaced by the current file name (without directory part).
785 Archiving to a different file is useful to keep archived entries from
786 contributing to the Org-mode Agenda.
788 The part after the double colon is a headline. The archived entries will be
789 filed under that headline. When omitted, the subtrees are simply filed away
790 at the end of the file, as top-level entries.
792 Here are a few examples:
793 \"%s_archive::\"
794 If the current file is Projects.org, archive in file
795 Projects.org_archive, as top-level trees. This is the default.
797 \"::* Archived Tasks\"
798 Archive in the current file, under the top-level headline
799 \"* Archived Tasks\".
801 \"~/org/archive.org::\"
802 Archive in file ~/org/archive.org (absolute path), as top-level trees.
804 \"basement::** Finished Tasks\"
805 Archive in file ./basement (relative path), as level 3 trees
806 below the level 2 heading \"** Finished Tasks\".
808 You may set this option on a per-file basis by adding to the buffer a
809 line like
811 #+ARCHIVE: basement::** Finished Tasks"
812 :group 'org-archive
813 :type 'string)
815 (defcustom org-archive-mark-done t
816 "Non-nil means, mark entries as DONE when they are moved to the archive file.
817 This can be a string to set the keyword to use. When t, Org-mode will
818 use the first keyword in its list that means done."
819 :group 'org-archive
820 :type '(choice
821 (const :tag "No" nil)
822 (const :tag "Yes" t)
823 (string :tag "Use this keyword")))
825 (defcustom org-archive-stamp-time t
826 "Non-nil means, add a time stamp to entries moved to an archive file.
827 This variable is obsolete and has no effect anymore, instead add ot remove
828 `time' from the variablle `org-archive-save-context-info'."
829 :group 'org-archive
830 :type 'boolean)
832 (defcustom org-archive-save-context-info '(time file olpath category todo itags)
833 "Parts of context info that should be stored as properties when archiving.
834 When a subtree is moved to an archive file, it looses information given by
835 context, like inherited tags, the category, and possibly also the TODO
836 state (depending on the variable `org-archive-mark-done').
837 This variable can be a list of any of the following symbols:
839 time The time of archiving.
840 file The file where the entry originates.
841 itags The local tags, in the headline of the subtree.
842 ltags The tags the subtree inherits from further up the hierarchy.
843 todo The pre-archive TODO state.
844 category The category, taken from file name or #+CATEGORY lines.
845 olpath The outline path to the item. These are all headlines above
846 the current item, separated by /, like a file path.
848 For each symbol present in the list, a property will be created in
849 the archived entry, with a prefix \"PRE_ARCHIVE_\", to remember this
850 information."
851 :group 'org-archive
852 :type '(set :greedy t
853 (const :tag "Time" time)
854 (const :tag "File" file)
855 (const :tag "Category" category)
856 (const :tag "TODO state" todo)
857 (const :tag "TODO state" priority)
858 (const :tag "Inherited tags" itags)
859 (const :tag "Outline path" olpath)
860 (const :tag "Local tags" ltags)))
862 (defgroup org-imenu-and-speedbar nil
863 "Options concerning imenu and speedbar in Org-mode."
864 :tag "Org Imenu and Speedbar"
865 :group 'org-structure)
867 (defcustom org-imenu-depth 2
868 "The maximum level for Imenu access to Org-mode headlines.
869 This also applied for speedbar access."
870 :group 'org-imenu-and-speedbar
871 :type 'number)
873 (defgroup org-table nil
874 "Options concerning tables in Org-mode."
875 :tag "Org Table"
876 :group 'org)
878 (defcustom org-enable-table-editor 'optimized
879 "Non-nil means, lines starting with \"|\" are handled by the table editor.
880 When nil, such lines will be treated like ordinary lines.
882 When equal to the symbol `optimized', the table editor will be optimized to
883 do the following:
884 - Automatic overwrite mode in front of whitespace in table fields.
885 This makes the structure of the table stay in tact as long as the edited
886 field does not exceed the column width.
887 - Minimize the number of realigns. Normally, the table is aligned each time
888 TAB or RET are pressed to move to another field. With optimization this
889 happens only if changes to a field might have changed the column width.
890 Optimization requires replacing the functions `self-insert-command',
891 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
892 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
893 very good at guessing when a re-align will be necessary, but you can always
894 force one with \\[org-ctrl-c-ctrl-c].
896 If you would like to use the optimized version in Org-mode, but the
897 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
899 This variable can be used to turn on and off the table editor during a session,
900 but in order to toggle optimization, a restart is required.
902 See also the variable `org-table-auto-blank-field'."
903 :group 'org-table
904 :type '(choice
905 (const :tag "off" nil)
906 (const :tag "on" t)
907 (const :tag "on, optimized" optimized)))
909 (defcustom org-table-tab-recognizes-table.el t
910 "Non-nil means, TAB will automatically notice a table.el table.
911 When it sees such a table, it moves point into it and - if necessary -
912 calls `table-recognize-table'."
913 :group 'org-table-editing
914 :type 'boolean)
916 (defgroup org-link nil
917 "Options concerning links in Org-mode."
918 :tag "Org Link"
919 :group 'org)
921 (defvar org-link-abbrev-alist-local nil
922 "Buffer-local version of `org-link-abbrev-alist', which see.
923 The value of this is taken from the #+LINK lines.")
924 (make-variable-buffer-local 'org-link-abbrev-alist-local)
926 (defcustom org-link-abbrev-alist nil
927 "Alist of link abbreviations.
928 The car of each element is a string, to be replaced at the start of a link.
929 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
930 links in Org-mode buffers can have an optional tag after a double colon, e.g.
932 [[linkkey:tag][description]]
934 If REPLACE is a string, the tag will simply be appended to create the link.
935 If the string contains \"%s\", the tag will be inserted there.
937 REPLACE may also be a function that will be called with the tag as the
938 only argument to create the link, which should be returned as a string.
940 See the manual for examples."
941 :group 'org-link
942 :type 'alist)
944 (defcustom org-descriptive-links t
945 "Non-nil means, hide link part and only show description of bracket links.
946 Bracket links are like [[link][descritpion]]. This variable sets the initial
947 state in new org-mode buffers. The setting can then be toggled on a
948 per-buffer basis from the Org->Hyperlinks menu."
949 :group 'org-link
950 :type 'boolean)
952 (defcustom org-link-file-path-type 'adaptive
953 "How the path name in file links should be stored.
954 Valid values are:
956 relative Relative to the current directory, i.e. the directory of the file
957 into which the link is being inserted.
958 absolute Absolute path, if possible with ~ for home directory.
959 noabbrev Absolute path, no abbreviation of home directory.
960 adaptive Use relative path for files in the current directory and sub-
961 directories of it. For other files, use an absolute path."
962 :group 'org-link
963 :type '(choice
964 (const relative)
965 (const absolute)
966 (const noabbrev)
967 (const adaptive)))
969 (defcustom org-activate-links '(bracket angle plain radio tag date)
970 "Types of links that should be activated in Org-mode files.
971 This is a list of symbols, each leading to the activation of a certain link
972 type. In principle, it does not hurt to turn on most link types - there may
973 be a small gain when turning off unused link types. The types are:
975 bracket The recommended [[link][description]] or [[link]] links with hiding.
976 angular Links in angular brackes that may contain whitespace like
977 <bbdb:Carsten Dominik>.
978 plain Plain links in normal text, no whitespace, like http://google.com.
979 radio Text that is matched by a radio target, see manual for details.
980 tag Tag settings in a headline (link to tag search).
981 date Time stamps (link to calendar).
983 Changing this variable requires a restart of Emacs to become effective."
984 :group 'org-link
985 :type '(set (const :tag "Double bracket links (new style)" bracket)
986 (const :tag "Angular bracket links (old style)" angular)
987 (const :tag "Plain text links" plain)
988 (const :tag "Radio target matches" radio)
989 (const :tag "Tags" tag)
990 (const :tag "Timestamps" date)))
992 (defgroup org-link-store nil
993 "Options concerning storing links in Org-mode."
994 :tag "Org Store Link"
995 :group 'org-link)
997 (defcustom org-email-link-description-format "Email %c: %.30s"
998 "Format of the description part of a link to an email or usenet message.
999 The following %-excapes will be replaced by corresponding information:
1001 %F full \"From\" field
1002 %f name, taken from \"From\" field, address if no name
1003 %T full \"To\" field
1004 %t first name in \"To\" field, address if no name
1005 %c correspondent. Unually \"from NAME\", but if you sent it yourself, it
1006 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1007 %s subject
1008 %m message-id.
1010 You may use normal field width specification between the % and the letter.
1011 This is for example useful to limit the length of the subject.
1013 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1014 :group 'org-link-store
1015 :type 'string)
1017 (defcustom org-from-is-user-regexp
1018 (let (r1 r2)
1019 (when (and user-mail-address (not (string= user-mail-address "")))
1020 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1021 (when (and user-full-name (not (string= user-full-name "")))
1022 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1023 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1024 "Regexp mached against the \"From:\" header of an email or usenet message.
1025 It should match if the message is from the user him/herself."
1026 :group 'org-link-store
1027 :type 'regexp)
1029 (defcustom org-context-in-file-links t
1030 "Non-nil means, file links from `org-store-link' contain context.
1031 A search string will be added to the file name with :: as separator and
1032 used to find the context when the link is activated by the command
1033 `org-open-at-point'.
1034 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1035 negates this setting for the duration of the command."
1036 :group 'org-link-store
1037 :type 'boolean)
1039 (defcustom org-keep-stored-link-after-insertion nil
1040 "Non-nil means, keep link in list for entire session.
1042 The command `org-store-link' adds a link pointing to the current
1043 location to an internal list. These links accumulate during a session.
1044 The command `org-insert-link' can be used to insert links into any
1045 Org-mode file (offering completion for all stored links). When this
1046 option is nil, every link which has been inserted once using \\[org-insert-link]
1047 will be removed from the list, to make completing the unused links
1048 more efficient."
1049 :group 'org-link-store
1050 :type 'boolean)
1052 (defgroup org-link-follow nil
1053 "Options concerning following links in Org-mode."
1054 :tag "Org Follow Link"
1055 :group 'org-link)
1057 (defcustom org-follow-link-hook nil
1058 "Hook that is run after a link has been followed."
1059 :group 'org-link-follow
1060 :type 'hook)
1062 (defcustom org-tab-follows-link nil
1063 "Non-nil means, on links TAB will follow the link.
1064 Needs to be set before org.el is loaded."
1065 :group 'org-link-follow
1066 :type 'boolean)
1068 (defcustom org-return-follows-link nil
1069 "Non-nil means, on links RET will follow the link.
1070 Needs to be set before org.el is loaded."
1071 :group 'org-link-follow
1072 :type 'boolean)
1074 (defcustom org-mouse-1-follows-link
1075 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1076 "Non-nil means, mouse-1 on a link will follow the link.
1077 A longer mouse click will still set point. Does not work on XEmacs.
1078 Needs to be set before org.el is loaded."
1079 :group 'org-link-follow
1080 :type 'boolean)
1082 (defcustom org-mark-ring-length 4
1083 "Number of different positions to be recorded in the ring
1084 Changing this requires a restart of Emacs to work correctly."
1085 :group 'org-link-follow
1086 :type 'interger)
1088 (defcustom org-link-frame-setup
1089 '((vm . vm-visit-folder-other-frame)
1090 (gnus . gnus-other-frame)
1091 (file . find-file-other-window))
1092 "Setup the frame configuration for following links.
1093 When following a link with Emacs, it may often be useful to display
1094 this link in another window or frame. This variable can be used to
1095 set this up for the different types of links.
1096 For VM, use any of
1097 `vm-visit-folder'
1098 `vm-visit-folder-other-frame'
1099 For Gnus, use any of
1100 `gnus'
1101 `gnus-other-frame'
1102 For FILE, use any of
1103 `find-file'
1104 `find-file-other-window'
1105 `find-file-other-frame'
1106 For the calendar, use the variable `calendar-setup'.
1107 For BBDB, it is currently only possible to display the matches in
1108 another window."
1109 :group 'org-link-follow
1110 :type '(list
1111 (cons (const vm)
1112 (choice
1113 (const vm-visit-folder)
1114 (const vm-visit-folder-other-window)
1115 (const vm-visit-folder-other-frame)))
1116 (cons (const gnus)
1117 (choice
1118 (const gnus)
1119 (const gnus-other-frame)))
1120 (cons (const file)
1121 (choice
1122 (const find-file)
1123 (const find-file-other-window)
1124 (const find-file-other-frame)))))
1126 (defcustom org-display-internal-link-with-indirect-buffer nil
1127 "Non-nil means, use indirect buffer to display infile links.
1128 Activating internal links (from one location in a file to another location
1129 in the same file) normally just jumps to the location. When the link is
1130 activated with a C-u prefix (or with mouse-3), the link is displayed in
1131 another window. When this option is set, the other window actually displays
1132 an indirect buffer clone of the current buffer, to avoid any visibility
1133 changes to the current buffer."
1134 :group 'org-link-follow
1135 :type 'boolean)
1137 (defcustom org-open-non-existing-files nil
1138 "Non-nil means, `org-open-file' will open non-existing files.
1139 When nil, an error will be generated."
1140 :group 'org-link-follow
1141 :type 'boolean)
1143 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1144 "Function and arguments to call for following mailto links.
1145 This is a list with the first element being a lisp function, and the
1146 remaining elements being arguments to the function. In string arguments,
1147 %a will be replaced by the address, and %s will be replaced by the subject
1148 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1149 :group 'org-link-follow
1150 :type '(choice
1151 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1152 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1153 (const :tag "message-mail" (message-mail "%a" "%s"))
1154 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1156 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1157 "Non-nil means, ask for confirmation before executing shell links.
1158 Shell links can be dangerous: just think about a link
1160 [[shell:rm -rf ~/*][Google Search]]
1162 This link would show up in your Org-mode document as \"Google Search\",
1163 but really it would remove your entire home directory.
1164 Therefore we advise against setting this variable to nil.
1165 Just change it to `y-or-n-p' of you want to confirm with a
1166 single keystroke rather than having to type \"yes\"."
1167 :group 'org-link-follow
1168 :type '(choice
1169 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1170 (const :tag "with y-or-n (faster)" y-or-n-p)
1171 (const :tag "no confirmation (dangerous)" nil)))
1173 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1174 "Non-nil means, ask for confirmation before executing Emacs Lisp links.
1175 Elisp links can be dangerous: just think about a link
1177 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1179 This link would show up in your Org-mode document as \"Google Search\",
1180 but really it would remove your entire home directory.
1181 Therefore we advise against setting this variable to nil.
1182 Just change it to `y-or-n-p' of you want to confirm with a
1183 single keystroke rather than having to type \"yes\"."
1184 :group 'org-link-follow
1185 :type '(choice
1186 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1187 (const :tag "with y-or-n (faster)" y-or-n-p)
1188 (const :tag "no confirmation (dangerous)" nil)))
1190 (defconst org-file-apps-defaults-gnu
1191 '((remote . emacs)
1192 (t . mailcap))
1193 "Default file applications on a UNIX or GNU/Linux system.
1194 See `org-file-apps'.")
1196 (defconst org-file-apps-defaults-macosx
1197 '((remote . emacs)
1198 (t . "open %s")
1199 ("ps" . "gv %s")
1200 ("ps.gz" . "gv %s")
1201 ("eps" . "gv %s")
1202 ("eps.gz" . "gv %s")
1203 ("dvi" . "xdvi %s")
1204 ("fig" . "xfig %s"))
1205 "Default file applications on a MacOS X system.
1206 The system \"open\" is known as a default, but we use X11 applications
1207 for some files for which the OS does not have a good default.
1208 See `org-file-apps'.")
1210 (defconst org-file-apps-defaults-windowsnt
1211 (list
1212 '(remote . emacs)
1213 (cons t
1214 (list (if (featurep 'xemacs)
1215 'mswindows-shell-execute
1216 'w32-shell-execute)
1217 "open" 'file)))
1218 "Default file applications on a Windows NT system.
1219 The system \"open\" is used for most files.
1220 See `org-file-apps'.")
1222 (defcustom org-file-apps
1224 ("txt" . emacs)
1225 ("tex" . emacs)
1226 ("ltx" . emacs)
1227 ("org" . emacs)
1228 ("el" . emacs)
1229 ("bib" . emacs)
1231 "External applications for opening `file:path' items in a document.
1232 Org-mode uses system defaults for different file types, but
1233 you can use this variable to set the application for a given file
1234 extension. The entries in this list are cons cells where the car identifies
1235 files and the cdr the corresponding command. Possible values for the
1236 file identifier are
1237 \"ext\" A string identifying an extension
1238 `directory' Matches a directory
1239 `remote' Matches a remote file, accessible through tramp or efs.
1240 Remote files most likely should be visited through Emacs
1241 because external applications cannot handle such paths.
1242 t Default for all remaining files
1244 Possible values for the command are:
1245 `emacs' The file will be visited by the current Emacs process.
1246 `default' Use the default application for this file type.
1247 string A command to be executed by a shell; %s will be replaced
1248 by the path to the file.
1249 sexp A Lisp form which will be evaluated. The file path will
1250 be available in the Lisp variable `file'.
1251 For more examples, see the system specific constants
1252 `org-file-apps-defaults-macosx'
1253 `org-file-apps-defaults-windowsnt'
1254 `org-file-apps-defaults-gnu'."
1255 :group 'org-link-follow
1256 :type '(repeat
1257 (cons (choice :value ""
1258 (string :tag "Extension")
1259 (const :tag "Default for unrecognized files" t)
1260 (const :tag "Remote file" remote)
1261 (const :tag "Links to a directory" directory))
1262 (choice :value ""
1263 (const :tag "Visit with Emacs" emacs)
1264 (const :tag "Use system default" default)
1265 (string :tag "Command")
1266 (sexp :tag "Lisp form")))))
1268 (defgroup org-refile nil
1269 "Options concerning refiling entries in Org-mode."
1270 :tag "Org Remember"
1271 :group 'org)
1273 (defcustom org-directory "~/org"
1274 "Directory with org files.
1275 This directory will be used as default to prompt for org files.
1276 Used by the hooks for remember.el."
1277 :group 'org-refile
1278 :group 'org-remember
1279 :type 'directory)
1281 (defcustom org-default-notes-file "~/.notes"
1282 "Default target for storing notes.
1283 Used by the hooks for remember.el. This can be a string, or nil to mean
1284 the value of `remember-data-file'.
1285 You can set this on a per-template basis with the variable
1286 `org-remember-templates'."
1287 :group 'org-refile
1288 :group 'org-remember
1289 :type '(choice
1290 (const :tag "Default from remember-data-file" nil)
1291 file))
1293 (defcustom org-goto-interface 'outline
1294 "The default interface to be used for `org-goto'.
1295 Allowed vaues are:
1296 outline The interface shows an outline of the relevant file
1297 and the correct heading is found by moving through
1298 the outline or by searching with incremental search.
1299 outline-path-completion Headlines in the current buffer are offered via
1300 completion."
1301 :group 'org-refile
1302 :type '(choice
1303 (const :tag "Outline" outline)
1304 (const :tag "Outline-path-completion" outline-path-completion)))
1306 (defcustom org-reverse-note-order nil
1307 "Non-nil means, store new notes at the beginning of a file or entry.
1308 When nil, new notes will be filed to the end of a file or entry.
1309 This can also be a list with cons cells of regular expressions that
1310 are matched against file names, and values."
1311 :group 'org-remember
1312 :type '(choice
1313 (const :tag "Reverse always" t)
1314 (const :tag "Reverse never" nil)
1315 (repeat :tag "By file name regexp"
1316 (cons regexp boolean))))
1318 (defcustom org-refile-targets nil
1319 "Targets for refiling entries with \\[org-refile].
1320 This is list of cons cells. Each cell contains:
1321 - a specification of the files to be considered, either a list of files,
1322 or a symbol whose function or variable value will be used to retrieve
1323 a file name or a list of file names. Nil means, refile to a different
1324 heading in the current buffer.
1325 - A specification of how to find candidate refile targets. This may be
1326 any of
1327 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
1328 This tag has to be present in all target headlines, inheritance will
1329 not be considered.
1330 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
1331 todo keyword.
1332 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1333 headlines that are refiling targets.
1334 - a cons cell (:level . N). Any headline of level N is considered a target.
1335 - a cons cell (:maxlevel . N). Any headline with level <= N is a target."
1336 :group 'org-remember
1337 :type '(repeat
1338 (cons
1339 (choice :value org-agenda-files
1340 (const :tag "All agenda files" org-agenda-files)
1341 (const :tag "Current buffer" nil)
1342 (function) (variable) (file))
1343 (choice :tag "Identify target headline by"
1344 (cons :tag "Specific tag" (const :tag) (string))
1345 (cons :tag "TODO keyword" (const :todo) (string))
1346 (cons :tag "Regular expression" (const :regexp) (regexp))
1347 (cons :tag "Level number" (const :level) (integer))
1348 (cons :tag "Max Level number" (const :maxlevel) (integer))))))
1350 (defcustom org-refile-use-outline-path nil
1351 "Non-nil means, provide refile targets as paths.
1352 So a level 3 headline will be available as level1/level2/level3.
1353 When the value is `file', also include the file name (without directory)
1354 into the path. When `full-file-path', include the full file path."
1355 :group 'org-remember
1356 :type '(choice
1357 (const :tag "Not" nil)
1358 (const :tag "Yes" t)
1359 (const :tag "Start with file name" file)
1360 (const :tag "Start with full file path" full-file-path)))
1362 (defgroup org-todo nil
1363 "Options concerning TODO items in Org-mode."
1364 :tag "Org TODO"
1365 :group 'org)
1367 (defgroup org-progress nil
1368 "Options concerning Progress logging in Org-mode."
1369 :tag "Org Progress"
1370 :group 'org-time)
1372 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
1373 "List of TODO entry keyword sequences and their interpretation.
1374 \\<org-mode-map>This is a list of sequences.
1376 Each sequence starts with a symbol, either `sequence' or `type',
1377 indicating if the keywords should be interpreted as a sequence of
1378 action steps, or as different types of TODO items. The first
1379 keywords are states requiring action - these states will select a headline
1380 for inclusion into the global TODO list Org-mode produces. If one of
1381 the \"keywords\" is the vertical bat \"|\" the remaining keywords
1382 signify that no further action is necessary. If \"|\" is not found,
1383 the last keyword is treated as the only DONE state of the sequence.
1385 The command \\[org-todo] cycles an entry through these states, and one
1386 additional state where no keyword is present. For details about this
1387 cycling, see the manual.
1389 TODO keywords and interpretation can also be set on a per-file basis with
1390 the special #+SEQ_TODO and #+TYP_TODO lines.
1392 Each keyword can optionally specify a character for fast state selection
1393 \(in combination with the variable `org-use-fast-todo-selection')
1394 and specifiers for state change logging, using the same syntax
1395 that is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says
1396 that the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
1397 indicates to record a time stamp each time this state is selected.
1399 Each keyword may also specify if a timestamp or a note should be
1400 recorded when entering or leaving the state, by adding additional
1401 characters in the parenthesis after the keyword. This looks like this:
1402 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
1403 record only the time of the state change. With X and Y being either
1404 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
1405 Y when leaving the state if and only if the *target* state does not
1406 define X. You may omit any of the fast-selection key or X or /Y,
1407 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
1409 For backward compatibility, this variable may also be just a list
1410 of keywords - in this case the interptetation (sequence or type) will be
1411 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
1412 :group 'org-todo
1413 :group 'org-keywords
1414 :type '(choice
1415 (repeat :tag "Old syntax, just keywords"
1416 (string :tag "Keyword"))
1417 (repeat :tag "New syntax"
1418 (cons
1419 (choice
1420 :tag "Interpretation"
1421 (const :tag "Sequence (cycling hits every state)" sequence)
1422 (const :tag "Type (cycling directly to DONE)" type))
1423 (repeat
1424 (string :tag "Keyword"))))))
1426 (defvar org-todo-keywords-1 nil
1427 "All TODO and DONE keywords active in a buffer.")
1428 (make-variable-buffer-local 'org-todo-keywords-1)
1429 (defvar org-todo-keywords-for-agenda nil)
1430 (defvar org-done-keywords-for-agenda nil)
1431 (defvar org-not-done-keywords nil)
1432 (make-variable-buffer-local 'org-not-done-keywords)
1433 (defvar org-done-keywords nil)
1434 (make-variable-buffer-local 'org-done-keywords)
1435 (defvar org-todo-heads nil)
1436 (make-variable-buffer-local 'org-todo-heads)
1437 (defvar org-todo-sets nil)
1438 (make-variable-buffer-local 'org-todo-sets)
1439 (defvar org-todo-log-states nil)
1440 (make-variable-buffer-local 'org-todo-log-states)
1441 (defvar org-todo-kwd-alist nil)
1442 (make-variable-buffer-local 'org-todo-kwd-alist)
1443 (defvar org-todo-key-alist nil)
1444 (make-variable-buffer-local 'org-todo-key-alist)
1445 (defvar org-todo-key-trigger nil)
1446 (make-variable-buffer-local 'org-todo-key-trigger)
1448 (defcustom org-todo-interpretation 'sequence
1449 "Controls how TODO keywords are interpreted.
1450 This variable is in principle obsolete and is only used for
1451 backward compatibility, if the interpretation of todo keywords is
1452 not given already in `org-todo-keywords'. See that variable for
1453 more information."
1454 :group 'org-todo
1455 :group 'org-keywords
1456 :type '(choice (const sequence)
1457 (const type)))
1459 (defcustom org-use-fast-todo-selection 'prefix
1460 "Non-nil means, use the fast todo selection scheme with C-c C-t.
1461 This variable describes if and under what circumstances the cycling
1462 mechanism for TODO keywords will be replaced by a single-key, direct
1463 selection scheme.
1465 When nil, fast selection is never used.
1467 When the symbol `prefix', it will be used when `org-todo' is called with
1468 a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and `C-u t'
1469 in an agenda buffer.
1471 When t, fast selection is used by default. In this case, the prefix
1472 argument forces cycling instead.
1474 In all cases, the special interface is only used if access keys have actually
1475 been assigned by the user, i.e. if keywords in the configuration are followed
1476 by a letter in parenthesis, like TODO(t)."
1477 :group 'org-todo
1478 :type '(choice
1479 (const :tag "Never" nil)
1480 (const :tag "By default" t)
1481 (const :tag "Only with C-u C-c C-t" prefix)))
1483 (defcustom org-after-todo-state-change-hook nil
1484 "Hook which is run after the state of a TODO item was changed.
1485 The new state (a string with a TODO keyword, or nil) is available in the
1486 Lisp variable `state'."
1487 :group 'org-todo
1488 :type 'hook)
1490 (defcustom org-log-done nil
1491 "Non-nil means, record a CLOSED timestamp when moving an entry to DONE.
1492 When equal to the list (done), also prompt for a closing note.
1493 This can also be configured on a per-file basis by adding one of
1494 the following lines anywhere in the buffer:
1496 #+STARTUP: logdone
1497 #+STARTUP: lognotedone
1498 #+STARTUP: nologdone"
1499 :group 'org-todo
1500 :group 'org-progress
1501 :type '(choice
1502 (const :tag "No logging" nil)
1503 (const :tag "Record CLOSED timestamp" time)
1504 (const :tag "Record CLOSED timestamp with closing note." note)))
1506 ;; Normalize old uses of org-log-done.
1507 (cond
1508 ((eq org-log-done t) (setq org-log-done 'time))
1509 ((and (listp org-log-done) (memq 'done org-log-done))
1510 (setq org-log-done 'note)))
1512 (defcustom org-log-note-clock-out nil
1513 "Non-nil means, recored a note when clocking out of an item.
1514 This can also be configured on a per-file basis by adding one of
1515 the following lines anywhere in the buffer:
1517 #+STARTUP: lognoteclock-out
1518 #+STARTUP: nolognoteclock-out"
1519 :group 'org-todo
1520 :group 'org-progress
1521 :type 'boolean)
1523 (defcustom org-log-done-with-time t
1524 "Non-nil means, the CLOSED time stamp will contain date and time.
1525 When nil, only the date will be recorded."
1526 :group 'org-progress
1527 :type 'boolean)
1529 (defcustom org-log-note-headings
1530 '((done . "CLOSING NOTE %t")
1531 (state . "State %-12s %t")
1532 (note . "Note taken on %t")
1533 (clock-out . ""))
1534 "Headings for notes added to entries.
1535 The value is an alist, with the car being a symbol indicating the note
1536 context, and the cdr is the heading to be used. The heading may also be the
1537 empty string.
1538 %t in the heading will be replaced by a time stamp.
1539 %s will be replaced by the new TODO state, in double quotes.
1540 %u will be replaced by the user name.
1541 %U will be replaced by the full user name."
1542 :group 'org-todo
1543 :group 'org-progress
1544 :type '(list :greedy t
1545 (cons (const :tag "Heading when closing an item" done) string)
1546 (cons (const :tag
1547 "Heading when changing todo state (todo sequence only)"
1548 state) string)
1549 (cons (const :tag "Heading when just taking a note" note) string)
1550 (cons (const :tag "Heading when clocking out" clock-out) string)))
1552 (unless (assq 'note org-log-note-headings)
1553 (push '(note . "%t") org-log-note-headings))
1555 (defcustom org-log-states-order-reversed t
1556 "Non-nil means, the latest state change note will be directly after heading.
1557 When nil, the notes will be orderer according to time."
1558 :group 'org-todo
1559 :group 'org-progress
1560 :type 'boolean)
1562 (defcustom org-log-repeat 'time
1563 "Non-nil means, record moving through the DONE state when triggering repeat.
1564 An auto-repeating tasks is immediately switched back to TODO when marked
1565 done. If you are not logging state changes (by adding \"@\" or \"!\" to
1566 the TODO keyword definition, or recording a cloing note by setting
1567 `org-log-done', there will be no record of the task moving trhough DONE.
1568 This variable forces taking a note anyway. Possible values are:
1570 nil Don't force a record
1571 time Record a time stamp
1572 note Record a note
1574 This option can also be set with on a per-file-basis with
1576 #+STARTUP: logrepeat
1577 #+STARTUP: lognoterepeat
1578 #+STARTUP: nologrepeat
1580 You can have local logging settings for a subtree by setting the LOGGING
1581 property to one or more of these keywords."
1582 :group 'org-todo
1583 :group 'org-progress
1584 :type '(choice
1585 (const :tag "Don't force a record" nil)
1586 (const :tag "Force recording the DONE state" time)
1587 (const :tag "Force recording a note with the DONE state" note)))
1590 (defgroup org-priorities nil
1591 "Priorities in Org-mode."
1592 :tag "Org Priorities"
1593 :group 'org-todo)
1595 (defcustom org-highest-priority ?A
1596 "The highest priority of TODO items. A character like ?A, ?B etc.
1597 Must have a smaller ASCII number than `org-lowest-priority'."
1598 :group 'org-priorities
1599 :type 'character)
1601 (defcustom org-lowest-priority ?C
1602 "The lowest priority of TODO items. A character like ?A, ?B etc.
1603 Must have a larger ASCII number than `org-highest-priority'."
1604 :group 'org-priorities
1605 :type 'character)
1607 (defcustom org-default-priority ?B
1608 "The default priority of TODO items.
1609 This is the priority an item get if no explicit priority is given."
1610 :group 'org-priorities
1611 :type 'character)
1613 (defcustom org-priority-start-cycle-with-default t
1614 "Non-nil means, start with default priority when starting to cycle.
1615 When this is nil, the first step in the cycle will be (depending on the
1616 command used) one higher or lower that the default priority."
1617 :group 'org-priorities
1618 :type 'boolean)
1620 (defgroup org-time nil
1621 "Options concerning time stamps and deadlines in Org-mode."
1622 :tag "Org Time"
1623 :group 'org)
1625 (defcustom org-insert-labeled-timestamps-at-point nil
1626 "Non-nil means, SCHEDULED and DEADLINE timestamps are inserted at point.
1627 When nil, these labeled time stamps are forces into the second line of an
1628 entry, just after the headline. When scheduling from the global TODO list,
1629 the time stamp will always be forced into the second line."
1630 :group 'org-time
1631 :type 'boolean)
1633 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
1634 "Formats for `format-time-string' which are used for time stamps.
1635 It is not recommended to change this constant.")
1637 (defcustom org-time-stamp-rounding-minutes '(0 5)
1638 "Number of minutes to round time stamps to.
1639 These are two values, the first applies when first creating a time stamp.
1640 The second applies when changing it with the commands `S-up' and `S-down'.
1641 When changing the time stamp, this means that it will change in steps
1642 of N minutes, as given by the second value.
1644 When a setting is 0 or 1, insert the time unmodified. Useful rounding
1645 numbers should be factors of 60, so for example 5, 10, 15.
1647 When this is larger than 1, you can still force an exact time-stamp by using
1648 a double prefix argument to a time-stamp command like `C-c .' or `C-c !',
1649 and by using a prefix arg to `S-up/down' to specify the exact number
1650 of minutes to shift."
1651 :group 'org-time
1652 :get '(lambda (var) ; Make sure all entries have 5 elements
1653 (if (integerp (default-value var))
1654 (list (default-value var) 5)
1655 (default-value var)))
1656 :type '(list
1657 (integer :tag "when inserting times")
1658 (integer :tag "when modifying times")))
1660 ;; Normalize old customizations of this variable.
1661 (when (integerp org-time-stamp-rounding-minutes)
1662 (setq org-time-stamp-rounding-minutes
1663 (list org-time-stamp-rounding-minutes
1664 org-time-stamp-rounding-minutes)))
1666 (defcustom org-display-custom-times nil
1667 "Non-nil means, overlay custom formats over all time stamps.
1668 The formats are defined through the variable `org-time-stamp-custom-formats'.
1669 To turn this on on a per-file basis, insert anywhere in the file:
1670 #+STARTUP: customtime"
1671 :group 'org-time
1672 :set 'set-default
1673 :type 'sexp)
1674 (make-variable-buffer-local 'org-display-custom-times)
1676 (defcustom org-time-stamp-custom-formats
1677 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
1678 "Custom formats for time stamps. See `format-time-string' for the syntax.
1679 These are overlayed over the default ISO format if the variable
1680 `org-display-custom-times' is set. Time like %H:%M should be at the
1681 end of the second format."
1682 :group 'org-time
1683 :type 'sexp)
1685 (defun org-time-stamp-format (&optional long inactive)
1686 "Get the right format for a time string."
1687 (let ((f (if long (cdr org-time-stamp-formats)
1688 (car org-time-stamp-formats))))
1689 (if inactive
1690 (concat "[" (substring f 1 -1) "]")
1691 f)))
1693 (defcustom org-deadline-warning-days 14
1694 "No. of days before expiration during which a deadline becomes active.
1695 This variable governs the display in sparse trees and in the agenda.
1696 When 0 or negative, it means use this number (the absolute value of it)
1697 even if a deadline has a different individual lead time specified."
1698 :group 'org-time
1699 :group 'org-agenda-daily/weekly
1700 :type 'number)
1702 (defcustom org-read-date-prefer-future t
1703 "Non-nil means, assume future for incomplete date input from user.
1704 This affects the following situations:
1705 1. The user gives a day, but no month.
1706 For example, if today is the 15th, and you enter \"3\", Org-mode will
1707 read this as the third of *next* month. However, if you enter \"17\",
1708 it will be considered as *this* month.
1709 2. The user gives a month but not a year.
1710 For example, if it is april and you enter \"feb 2\", this will be read
1711 as feb 2, *next* year. \"May 5\", however, will be this year.
1713 Currently this does not work for ISO week specifications.
1715 When this option is nil, the current month and year will always be used
1716 as defaults."
1717 :group 'org-time
1718 :type 'boolean)
1720 (defcustom org-read-date-display-live t
1721 "Non-nil means, display current interpretation of date prompt live.
1722 This display will be in an overlay, in the minibuffer."
1723 :group 'org-time
1724 :type 'boolean)
1726 (defcustom org-read-date-popup-calendar t
1727 "Non-nil means, pop up a calendar when prompting for a date.
1728 In the calendar, the date can be selected with mouse-1. However, the
1729 minibuffer will also be active, and you can simply enter the date as well.
1730 When nil, only the minibuffer will be available."
1731 :group 'org-time
1732 :type 'boolean)
1733 (if (fboundp 'defvaralias)
1734 (defvaralias 'org-popup-calendar-for-date-prompt
1735 'org-read-date-popup-calendar))
1737 (defcustom org-extend-today-until 0
1738 "The hour when your day really ends.
1739 This has influence for the following applications:
1740 - When switching the agenda to \"today\". It it is still earlier than
1741 the time given here, the day recognized as TODAY is actually yesterday.
1742 - When a date is read from the user and it is still before the time given
1743 here, the current date and time will be assumed to be yesterday, 23:59.
1745 FIXME:
1746 IMPORTANT: This is still a very experimental feature, it may disappear
1747 again or it may be extended to mean more things."
1748 :group 'org-time
1749 :type 'number)
1751 (defcustom org-edit-timestamp-down-means-later nil
1752 "Non-nil means, S-down will increase the time in a time stamp.
1753 When nil, S-up will increase."
1754 :group 'org-time
1755 :type 'boolean)
1757 (defcustom org-calendar-follow-timestamp-change t
1758 "Non-nil means, make the calendar window follow timestamp changes.
1759 When a timestamp is modified and the calendar window is visible, it will be
1760 moved to the new date."
1761 :group 'org-time
1762 :type 'boolean)
1764 (defgroup org-tags nil
1765 "Options concerning tags in Org-mode."
1766 :tag "Org Tags"
1767 :group 'org)
1769 (defcustom org-tag-alist nil
1770 "List of tags allowed in Org-mode files.
1771 When this list is nil, Org-mode will base TAG input on what is already in the
1772 buffer.
1773 The value of this variable is an alist, the car of each entry must be a
1774 keyword as a string, the cdr may be a character that is used to select
1775 that tag through the fast-tag-selection interface.
1776 See the manual for details."
1777 :group 'org-tags
1778 :type '(repeat
1779 (choice
1780 (cons (string :tag "Tag name")
1781 (character :tag "Access char"))
1782 (const :tag "Start radio group" (:startgroup))
1783 (const :tag "End radio group" (:endgroup)))))
1785 (defcustom org-use-fast-tag-selection 'auto
1786 "Non-nil means, use fast tag selection scheme.
1787 This is a special interface to select and deselect tags with single keys.
1788 When nil, fast selection is never used.
1789 When the symbol `auto', fast selection is used if and only if selection
1790 characters for tags have been configured, either through the variable
1791 `org-tag-alist' or through a #+TAGS line in the buffer.
1792 When t, fast selection is always used and selection keys are assigned
1793 automatically if necessary."
1794 :group 'org-tags
1795 :type '(choice
1796 (const :tag "Always" t)
1797 (const :tag "Never" nil)
1798 (const :tag "When selection characters are configured" 'auto)))
1800 (defcustom org-fast-tag-selection-single-key nil
1801 "Non-nil means, fast tag selection exits after first change.
1802 When nil, you have to press RET to exit it.
1803 During fast tag selection, you can toggle this flag with `C-c'.
1804 This variable can also have the value `expert'. In this case, the window
1805 displaying the tags menu is not even shown, until you press C-c again."
1806 :group 'org-tags
1807 :type '(choice
1808 (const :tag "No" nil)
1809 (const :tag "Yes" t)
1810 (const :tag "Expert" expert)))
1812 (defvar org-fast-tag-selection-include-todo nil
1813 "Non-nil means, fast tags selection interface will also offer TODO states.
1814 This is an undocumented feature, you should not rely on it.")
1816 (defcustom org-tags-column -80
1817 "The column to which tags should be indented in a headline.
1818 If this number is positive, it specifies the column. If it is negative,
1819 it means that the tags should be flushright to that column. For example,
1820 -80 works well for a normal 80 character screen."
1821 :group 'org-tags
1822 :type 'integer)
1824 (defcustom org-auto-align-tags t
1825 "Non-nil means, realign tags after pro/demotion of TODO state change.
1826 These operations change the length of a headline and therefore shift
1827 the tags around. With this options turned on, after each such operation
1828 the tags are again aligned to `org-tags-column'."
1829 :group 'org-tags
1830 :type 'boolean)
1832 (defcustom org-use-tag-inheritance t
1833 "Non-nil means, tags in levels apply also for sublevels.
1834 When nil, only the tags directly given in a specific line apply there.
1835 If you turn off this option, you very likely want to turn on the
1836 companion option `org-tags-match-list-sublevels'.
1838 This may also be a list of tags that should be inherited, or a regexp that
1839 matches tags that should be inherited."
1840 :group 'org-tags
1841 :type '(choice
1842 (const :tag "Not" nil)
1843 (const :tag "Always" t)
1844 (repeat :tag "Specific tags" (string :tag "Tag"))
1845 (regexp :tag "Tags matched by regexp")))
1847 (defun org-tag-inherit-p (tag)
1848 "Check if TAG is one that should be inherited."
1849 (cond
1850 ((eq org-use-tag-inheritance t) t)
1851 ((not org-use-tag-inheritance) nil)
1852 ((stringp org-use-tag-inheritance)
1853 (string-match org-use-tag-inheritance tag))
1854 ((listp org-use-tag-inheritance)
1855 (member tag org-use-tag-inheritance))
1856 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
1858 (defcustom org-tags-match-list-sublevels nil
1859 "Non-nil means list also sublevels of headlines matching tag search.
1860 Because of tag inheritance (see variable `org-use-tag-inheritance'),
1861 the sublevels of a headline matching a tag search often also match
1862 the same search. Listing all of them can create very long lists.
1863 Setting this variable to nil causes subtrees of a match to be skipped.
1864 This option is off by default, because inheritance in on. If you turn
1865 inheritance off, you very likely want to turn this option on.
1867 As a special case, if the tag search is restricted to TODO items, the
1868 value of this variable is ignored and sublevels are always checked, to
1869 make sure all corresponding TODO items find their way into the list."
1870 :group 'org-tags
1871 :type 'boolean)
1873 (defvar org-tags-history nil
1874 "History of minibuffer reads for tags.")
1875 (defvar org-last-tags-completion-table nil
1876 "The last used completion table for tags.")
1877 (defvar org-after-tags-change-hook nil
1878 "Hook that is run after the tags in a line have changed.")
1880 (defgroup org-properties nil
1881 "Options concerning properties in Org-mode."
1882 :tag "Org Properties"
1883 :group 'org)
1885 (defcustom org-property-format "%-10s %s"
1886 "How property key/value pairs should be formatted by `indent-line'.
1887 When `indent-line' hits a property definition, it will format the line
1888 according to this format, mainly to make sure that the values are
1889 lined-up with respect to each other."
1890 :group 'org-properties
1891 :type 'string)
1893 (defcustom org-use-property-inheritance nil
1894 "Non-nil means, properties apply also for sublevels.
1896 This setting is chiefly used during property searches. Turning it on can
1897 cause significant overhead when doing a search, which is why it is not
1898 on by default.
1900 When nil, only the properties directly given in the current entry count.
1901 When t, every property is inherited. The value may also be a list of
1902 properties that should have inheritance, or a regular expression matching
1903 properties that should be inherited.
1905 However, note that some special properties use inheritance under special
1906 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
1907 and the properties ending in \"_ALL\" when they are used as descriptor
1908 for valid values of a property.
1910 Note for programmers:
1911 When querying an entry with `org-entry-get', you can control if inheritance
1912 should be used. By default, `org-entry-get' looks only at the local
1913 properties. You can request inheritance by setting the inherit argument
1914 to t (to force inheritance) or to `selective' (to respect the setting
1915 in this variable)."
1916 :group 'org-properties
1917 :type '(choice
1918 (const :tag "Not" nil)
1919 (const :tag "Always" t)
1920 (repeat :tag "Specific properties" (string :tag "Property"))
1921 (regexp :tag "Properties matched by regexp")))
1923 (defun org-property-inherit-p (property)
1924 "Check if PROPERTY is one that should be inherited."
1925 (cond
1926 ((eq org-use-property-inheritance t) t)
1927 ((not org-use-property-inheritance) nil)
1928 ((stringp org-use-property-inheritance)
1929 (string-match org-use-property-inheritance property))
1930 ((listp org-use-property-inheritance)
1931 (member property org-use-property-inheritance))
1932 (t (error "Invalid setting of `org-use-property-inheritance'"))))
1934 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
1935 "The default column format, if no other format has been defined.
1936 This variable can be set on the per-file basis by inserting a line
1938 #+COLUMNS: %25ITEM ....."
1939 :group 'org-properties
1940 :type 'string)
1942 (defcustom org-global-properties nil
1943 "List of property/value pairs that can be inherited by any entry.
1944 You can set buffer-local values for this by adding lines like
1946 #+PROPERTY: NAME VALUE"
1947 :group 'org-properties
1948 :type '(repeat
1949 (cons (string :tag "Property")
1950 (string :tag "Value"))))
1952 (defvar org-local-properties nil
1953 "List of property/value pairs that can be inherited by any entry.
1954 Valid for the current buffer.
1955 This variable is populated from #+PROPERTY lines.")
1957 (defgroup org-agenda nil
1958 "Options concerning agenda views in Org-mode."
1959 :tag "Org Agenda"
1960 :group 'org)
1962 (defvar org-category nil
1963 "Variable used by org files to set a category for agenda display.
1964 Such files should use a file variable to set it, for example
1966 # -*- mode: org; org-category: \"ELisp\"
1968 or contain a special line
1970 #+CATEGORY: ELisp
1972 If the file does not specify a category, then file's base name
1973 is used instead.")
1974 (make-variable-buffer-local 'org-category)
1976 (defcustom org-agenda-files nil
1977 "The files to be used for agenda display.
1978 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
1979 \\[org-remove-file]. You can also use customize to edit the list.
1981 If an entry is a directory, all files in that directory that are matched by
1982 `org-agenda-file-regexp' will be part of the file list.
1984 If the value of the variable is not a list but a single file name, then
1985 the list of agenda files is actually stored and maintained in that file, one
1986 agenda file per line."
1987 :group 'org-agenda
1988 :type '(choice
1989 (repeat :tag "List of files and directories" file)
1990 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
1992 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
1993 "Regular expression to match files for `org-agenda-files'.
1994 If any element in the list in that variable contains a directory instead
1995 of a normal file, all files in that directory that are matched by this
1996 regular expression will be included."
1997 :group 'org-agenda
1998 :type 'regexp)
2000 (defcustom org-agenda-text-search-extra-files nil
2001 "List of extra files to be searched by text search commands.
2002 These files will be search in addition to the agenda files bu the
2003 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
2004 Note that these files will only be searched for text search commands,
2005 not for the other agenda views like todo lists, tag earches or the weekly
2006 agenda. This variable is intended to list notes and possibly archive files
2007 that should also be searched by these two commands."
2008 :group 'org-agenda
2009 :type '(repeat file))
2011 (if (fboundp 'defvaralias)
2012 (defvaralias 'org-agenda-multi-occur-extra-files
2013 'org-agenda-text-search-extra-files))
2015 (defcustom org-agenda-skip-unavailable-files nil
2016 "t means to just skip non-reachable files in `org-agenda-files'.
2017 Nil means to remove them, after a query, from the list."
2018 :group 'org-agenda
2019 :type 'boolean)
2021 (defcustom org-calendar-to-agenda-key [?c]
2022 "The key to be installed in `calendar-mode-map' for switching to the agenda.
2023 The command `org-calendar-goto-agenda' will be bound to this key. The
2024 default is the character `c' because then `c' can be used to switch back and
2025 forth between agenda and calendar."
2026 :group 'org-agenda
2027 :type 'sexp)
2029 (eval-after-load "calendar"
2030 '(org-defkey calendar-mode-map org-calendar-to-agenda-key
2031 'org-calendar-goto-agenda))
2033 (defgroup org-latex nil
2034 "Options for embedding LaTeX code into Org-mode."
2035 :tag "Org LaTeX"
2036 :group 'org)
2038 (defcustom org-format-latex-options
2039 '(:foreground default :background default :scale 1.0
2040 :html-foreground "Black" :html-background "Transparent" :html-scale 1.0
2041 :matchers ("begin" "$" "$$" "\\(" "\\["))
2042 "Options for creating images from LaTeX fragments.
2043 This is a property list with the following properties:
2044 :foreground the foreground color for images embedded in emacs, e.g. \"Black\".
2045 `default' means use the forground of the default face.
2046 :background the background color, or \"Transparent\".
2047 `default' means use the background of the default face.
2048 :scale a scaling factor for the size of the images
2049 :html-foreground, :html-background, :html-scale
2050 The same numbers for HTML export.
2051 :matchers a list indicating which matchers should be used to
2052 find LaTeX fragments. Valid members of this list are:
2053 \"begin\" find environments
2054 \"$\" find math expressions surrounded by $...$
2055 \"$$\" find math expressions surrounded by $$....$$
2056 \"\\(\" find math expressions surrounded by \\(...\\)
2057 \"\\ [\" find math expressions surrounded by \\ [...\\]"
2058 :group 'org-latex
2059 :type 'plist)
2061 (defcustom org-format-latex-header "\\documentclass{article}
2062 \\usepackage{fullpage} % do not remove
2063 \\usepackage{amssymb}
2064 \\usepackage[usenames]{color}
2065 \\usepackage{amsmath}
2066 \\usepackage{latexsym}
2067 \\usepackage[mathscr]{eucal}
2068 \\pagestyle{empty} % do not remove"
2069 "The document header used for processing LaTeX fragments."
2070 :group 'org-latex
2071 :type 'string)
2074 (defgroup org-font-lock nil
2075 "Font-lock settings for highlighting in Org-mode."
2076 :tag "Org Font Lock"
2077 :group 'org)
2079 (defcustom org-level-color-stars-only nil
2080 "Non-nil means fontify only the stars in each headline.
2081 When nil, the entire headline is fontified.
2082 Changing it requires restart of `font-lock-mode' to become effective
2083 also in regions already fontified."
2084 :group 'org-font-lock
2085 :type 'boolean)
2087 (defcustom org-hide-leading-stars nil
2088 "Non-nil means, hide the first N-1 stars in a headline.
2089 This works by using the face `org-hide' for these stars. This
2090 face is white for a light background, and black for a dark
2091 background. You may have to customize the face `org-hide' to
2092 make this work.
2093 Changing it requires restart of `font-lock-mode' to become effective
2094 also in regions already fontified.
2095 You may also set this on a per-file basis by adding one of the following
2096 lines to the buffer:
2098 #+STARTUP: hidestars
2099 #+STARTUP: showstars"
2100 :group 'org-font-lock
2101 :type 'boolean)
2103 (defcustom org-fontify-done-headline nil
2104 "Non-nil means, change the face of a headline if it is marked DONE.
2105 Normally, only the TODO/DONE keyword indicates the state of a headline.
2106 When this is non-nil, the headline after the keyword is set to the
2107 `org-headline-done' as an additional indication."
2108 :group 'org-font-lock
2109 :type 'boolean)
2111 (defcustom org-fontify-emphasized-text t
2112 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
2113 Changing this variable requires a restart of Emacs to take effect."
2114 :group 'org-font-lock
2115 :type 'boolean)
2117 (defcustom org-highlight-latex-fragments-and-specials nil
2118 "Non-nil means, fontify what is treated specially by the exporters."
2119 :group 'org-font-lock
2120 :type 'boolean)
2122 (defcustom org-hide-emphasis-markers nil
2123 "Non-nil mean font-lock should hide the emphasis marker characters."
2124 :group 'org-font-lock
2125 :type 'boolean)
2127 (defvar org-emph-re nil
2128 "Regular expression for matching emphasis.")
2129 (defvar org-verbatim-re nil
2130 "Regular expression for matching verbatim text.")
2131 (defvar org-emphasis-regexp-components) ; defined just below
2132 (defvar org-emphasis-alist) ; defined just below
2133 (defun org-set-emph-re (var val)
2134 "Set variable and compute the emphasis regular expression."
2135 (set var val)
2136 (when (and (boundp 'org-emphasis-alist)
2137 (boundp 'org-emphasis-regexp-components)
2138 org-emphasis-alist org-emphasis-regexp-components)
2139 (let* ((e org-emphasis-regexp-components)
2140 (pre (car e))
2141 (post (nth 1 e))
2142 (border (nth 2 e))
2143 (body (nth 3 e))
2144 (nl (nth 4 e))
2145 (stacked (and nil (nth 5 e))) ; stacked is no longer allowed, forced to nil
2146 (body1 (concat body "*?"))
2147 (markers (mapconcat 'car org-emphasis-alist ""))
2148 (vmarkers (mapconcat
2149 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
2150 org-emphasis-alist "")))
2151 ;; make sure special characters appear at the right position in the class
2152 (if (string-match "\\^" markers)
2153 (setq markers (concat (replace-match "" t t markers) "^")))
2154 (if (string-match "-" markers)
2155 (setq markers (concat (replace-match "" t t markers) "-")))
2156 (if (string-match "\\^" vmarkers)
2157 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
2158 (if (string-match "-" vmarkers)
2159 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
2160 (if (> nl 0)
2161 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
2162 (int-to-string nl) "\\}")))
2163 ;; Make the regexp
2164 (setq org-emph-re
2165 (concat "\\([" pre (if (and nil stacked) markers) "]\\|^\\)"
2166 "\\("
2167 "\\([" markers "]\\)"
2168 "\\("
2169 "[^" border "]\\|"
2170 "[^" border (if (and nil stacked) markers) "]"
2171 body1
2172 "[^" border (if (and nil stacked) markers) "]"
2173 "\\)"
2174 "\\3\\)"
2175 "\\([" post (if (and nil stacked) markers) "]\\|$\\)"))
2176 (setq org-verbatim-re
2177 (concat "\\([" pre "]\\|^\\)"
2178 "\\("
2179 "\\([" vmarkers "]\\)"
2180 "\\("
2181 "[^" border "]\\|"
2182 "[^" border "]"
2183 body1
2184 "[^" border "]"
2185 "\\)"
2186 "\\3\\)"
2187 "\\([" post "]\\|$\\)")))))
2189 (defcustom org-emphasis-regexp-components
2190 '(" \t('\"" "- \t.,:?;'\")" " \t\r\n,\"'" "." 1)
2191 "Components used to build the regular expression for emphasis.
2192 This is a list with 6 entries. Terminology: In an emphasis string
2193 like \" *strong word* \", we call the initial space PREMATCH, the final
2194 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
2195 and \"trong wor\" is the body. The different components in this variable
2196 specify what is allowed/forbidden in each part:
2198 pre Chars allowed as prematch. Beginning of line will be allowed too.
2199 post Chars allowed as postmatch. End of line will be allowed too.
2200 border The chars *forbidden* as border characters.
2201 body-regexp A regexp like \".\" to match a body character. Don't use
2202 non-shy groups here, and don't allow newline here.
2203 newline The maximum number of newlines allowed in an emphasis exp.
2205 Use customize to modify this, or restart Emacs after changing it."
2206 :group 'org-font-lock
2207 :set 'org-set-emph-re
2208 :type '(list
2209 (sexp :tag "Allowed chars in pre ")
2210 (sexp :tag "Allowed chars in post ")
2211 (sexp :tag "Forbidden chars in border ")
2212 (sexp :tag "Regexp for body ")
2213 (integer :tag "number of newlines allowed")
2214 (option (boolean :tag "Stacking (DISABLED) "))))
2216 (defcustom org-emphasis-alist
2217 '(("*" bold "<b>" "</b>")
2218 ("/" italic "<i>" "</i>")
2219 ("_" underline "<u>" "</u>")
2220 ("=" org-code "<code>" "</code>" verbatim)
2221 ("~" org-verbatim "" "" verbatim)
2222 ("+" (:strike-through t) "<del>" "</del>")
2224 "Special syntax for emphasized text.
2225 Text starting and ending with a special character will be emphasized, for
2226 example *bold*, _underlined_ and /italic/. This variable sets the marker
2227 characters, the face to be used by font-lock for highlighting in Org-mode
2228 Emacs buffers, and the HTML tags to be used for this.
2229 Use customize to modify this, or restart Emacs after changing it."
2230 :group 'org-font-lock
2231 :set 'org-set-emph-re
2232 :type '(repeat
2233 (list
2234 (string :tag "Marker character")
2235 (choice
2236 (face :tag "Font-lock-face")
2237 (plist :tag "Face property list"))
2238 (string :tag "HTML start tag")
2239 (string :tag "HTML end tag")
2240 (option (const verbatim)))))
2242 ;;; Miscellaneous options
2244 (defgroup org-completion nil
2245 "Completion in Org-mode."
2246 :tag "Org Completion"
2247 :group 'org)
2249 (defcustom org-completion-fallback-command 'hippie-expand
2250 "The expansion command called by \\[org-complete] in normal context.
2251 Normal means, no org-mode-specific context."
2252 :group 'org-completion
2253 :type 'function)
2255 ;;; The faces
2257 (defgroup org-faces nil
2258 "Faces in Org-mode."
2259 :tag "Org Faces"
2260 :group 'org-font-lock)
2262 (defface org-hide
2263 '((((background light)) (:foreground "white"))
2264 (((background dark)) (:foreground "black")))
2265 "Face used to hide leading stars in headlines.
2266 The forground color of this face should be equal to the background
2267 color of the frame."
2268 :group 'org-faces)
2270 (defface org-level-1 ;; font-lock-function-name-face
2271 (org-compatible-face 'outline-1
2272 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
2273 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
2274 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
2275 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
2276 (((class color) (min-colors 8)) (:foreground "blue" :bold t))
2277 (t (:bold t))))
2278 "Face used for level 1 headlines."
2279 :group 'org-faces)
2281 (defface org-level-2 ;; font-lock-variable-name-face
2282 (org-compatible-face 'outline-2
2283 '((((class color) (min-colors 16) (background light)) (:foreground "DarkGoldenrod"))
2284 (((class color) (min-colors 16) (background dark)) (:foreground "LightGoldenrod"))
2285 (((class color) (min-colors 8) (background light)) (:foreground "yellow"))
2286 (((class color) (min-colors 8) (background dark)) (:foreground "yellow" :bold t))
2287 (t (:bold t))))
2288 "Face used for level 2 headlines."
2289 :group 'org-faces)
2291 (defface org-level-3 ;; font-lock-keyword-face
2292 (org-compatible-face 'outline-3
2293 '((((class color) (min-colors 88) (background light)) (:foreground "Purple"))
2294 (((class color) (min-colors 88) (background dark)) (:foreground "Cyan1"))
2295 (((class color) (min-colors 16) (background light)) (:foreground "Purple"))
2296 (((class color) (min-colors 16) (background dark)) (:foreground "Cyan"))
2297 (((class color) (min-colors 8) (background light)) (:foreground "purple" :bold t))
2298 (((class color) (min-colors 8) (background dark)) (:foreground "cyan" :bold t))
2299 (t (:bold t))))
2300 "Face used for level 3 headlines."
2301 :group 'org-faces)
2303 (defface org-level-4 ;; font-lock-comment-face
2304 (org-compatible-face 'outline-4
2305 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
2306 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
2307 (((class color) (min-colors 16) (background light)) (:foreground "red"))
2308 (((class color) (min-colors 16) (background dark)) (:foreground "red1"))
2309 (((class color) (min-colors 8) (background light)) (:foreground "red" :bold t))
2310 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
2311 (t (:bold t))))
2312 "Face used for level 4 headlines."
2313 :group 'org-faces)
2315 (defface org-level-5 ;; font-lock-type-face
2316 (org-compatible-face 'outline-5
2317 '((((class color) (min-colors 16) (background light)) (:foreground "ForestGreen"))
2318 (((class color) (min-colors 16) (background dark)) (:foreground "PaleGreen"))
2319 (((class color) (min-colors 8)) (:foreground "green"))))
2320 "Face used for level 5 headlines."
2321 :group 'org-faces)
2323 (defface org-level-6 ;; font-lock-constant-face
2324 (org-compatible-face 'outline-6
2325 '((((class color) (min-colors 16) (background light)) (:foreground "CadetBlue"))
2326 (((class color) (min-colors 16) (background dark)) (:foreground "Aquamarine"))
2327 (((class color) (min-colors 8)) (:foreground "magenta"))))
2328 "Face used for level 6 headlines."
2329 :group 'org-faces)
2331 (defface org-level-7 ;; font-lock-builtin-face
2332 (org-compatible-face 'outline-7
2333 '((((class color) (min-colors 16) (background light)) (:foreground "Orchid"))
2334 (((class color) (min-colors 16) (background dark)) (:foreground "LightSteelBlue"))
2335 (((class color) (min-colors 8)) (:foreground "blue"))))
2336 "Face used for level 7 headlines."
2337 :group 'org-faces)
2339 (defface org-level-8 ;; font-lock-string-face
2340 (org-compatible-face 'outline-8
2341 '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
2342 (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
2343 (((class color) (min-colors 8)) (:foreground "green"))))
2344 "Face used for level 8 headlines."
2345 :group 'org-faces)
2347 (defface org-special-keyword ;; font-lock-string-face
2348 (org-compatible-face nil
2349 '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
2350 (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
2351 (t (:italic t))))
2352 "Face used for special keywords."
2353 :group 'org-faces)
2355 (defface org-drawer ;; font-lock-function-name-face
2356 (org-compatible-face nil
2357 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
2358 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
2359 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
2360 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
2361 (((class color) (min-colors 8)) (:foreground "blue" :bold t))
2362 (t (:bold t))))
2363 "Face used for drawers."
2364 :group 'org-faces)
2366 (defface org-property-value nil
2367 "Face used for the value of a property."
2368 :group 'org-faces)
2370 (defface org-column
2371 (org-compatible-face nil
2372 '((((class color) (min-colors 16) (background light))
2373 (:background "grey90"))
2374 (((class color) (min-colors 16) (background dark))
2375 (:background "grey30"))
2376 (((class color) (min-colors 8))
2377 (:background "cyan" :foreground "black"))
2378 (t (:inverse-video t))))
2379 "Face for column display of entry properties."
2380 :group 'org-faces)
2382 (when (fboundp 'set-face-attribute)
2383 ;; Make sure that a fixed-width face is used when we have a column table.
2384 (set-face-attribute 'org-column nil
2385 :height (face-attribute 'default :height)
2386 :family (face-attribute 'default :family)))
2388 (defface org-warning
2389 (org-compatible-face 'font-lock-warning-face
2390 '((((class color) (min-colors 16) (background light)) (:foreground "Red1" :bold t))
2391 (((class color) (min-colors 16) (background dark)) (:foreground "Pink" :bold t))
2392 (((class color) (min-colors 8) (background light)) (:foreground "red" :bold t))
2393 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
2394 (t (:bold t))))
2395 "Face for deadlines and TODO keywords."
2396 :group 'org-faces)
2398 (defface org-archived ; similar to shadow
2399 (org-compatible-face 'shadow
2400 '((((class color grayscale) (min-colors 88) (background light))
2401 (:foreground "grey50"))
2402 (((class color grayscale) (min-colors 88) (background dark))
2403 (:foreground "grey70"))
2404 (((class color) (min-colors 8) (background light))
2405 (:foreground "green"))
2406 (((class color) (min-colors 8) (background dark))
2407 (:foreground "yellow"))))
2408 "Face for headline with the ARCHIVE tag."
2409 :group 'org-faces)
2411 (defface org-link
2412 '((((class color) (background light)) (:foreground "Purple" :underline t))
2413 (((class color) (background dark)) (:foreground "Cyan" :underline t))
2414 (t (:underline t)))
2415 "Face for links."
2416 :group 'org-faces)
2418 (defface org-ellipsis
2419 '((((class color) (background light)) (:foreground "DarkGoldenrod" :underline t))
2420 (((class color) (background dark)) (:foreground "LightGoldenrod" :underline t))
2421 (t (:strike-through t)))
2422 "Face for the ellipsis in folded text."
2423 :group 'org-faces)
2425 (defface org-target
2426 '((((class color) (background light)) (:underline t))
2427 (((class color) (background dark)) (:underline t))
2428 (t (:underline t)))
2429 "Face for links."
2430 :group 'org-faces)
2432 (defface org-date
2433 '((((class color) (background light)) (:foreground "Purple" :underline t))
2434 (((class color) (background dark)) (:foreground "Cyan" :underline t))
2435 (t (:underline t)))
2436 "Face for links."
2437 :group 'org-faces)
2439 (defface org-sexp-date
2440 '((((class color) (background light)) (:foreground "Purple"))
2441 (((class color) (background dark)) (:foreground "Cyan"))
2442 (t (:underline t)))
2443 "Face for links."
2444 :group 'org-faces)
2446 (defface org-tag
2447 '((t (:bold t)))
2448 "Face for tags."
2449 :group 'org-faces)
2451 (defface org-todo ; font-lock-warning-face
2452 (org-compatible-face nil
2453 '((((class color) (min-colors 16) (background light)) (:foreground "Red1" :bold t))
2454 (((class color) (min-colors 16) (background dark)) (:foreground "Pink" :bold t))
2455 (((class color) (min-colors 8) (background light)) (:foreground "red" :bold t))
2456 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
2457 (t (:inverse-video t :bold t))))
2458 "Face for TODO keywords."
2459 :group 'org-faces)
2461 (defface org-done ;; font-lock-type-face
2462 (org-compatible-face nil
2463 '((((class color) (min-colors 16) (background light)) (:foreground "ForestGreen" :bold t))
2464 (((class color) (min-colors 16) (background dark)) (:foreground "PaleGreen" :bold t))
2465 (((class color) (min-colors 8)) (:foreground "green"))
2466 (t (:bold t))))
2467 "Face used for todo keywords that indicate DONE items."
2468 :group 'org-faces)
2470 (defface org-headline-done ;; font-lock-string-face
2471 (org-compatible-face nil
2472 '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
2473 (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
2474 (((class color) (min-colors 8) (background light)) (:bold nil))))
2475 "Face used to indicate that a headline is DONE.
2476 This face is only used if `org-fontify-done-headline' is set. If applies
2477 to the part of the headline after the DONE keyword."
2478 :group 'org-faces)
2480 (defcustom org-todo-keyword-faces nil
2481 "Faces for specific TODO keywords.
2482 This is a list of cons cells, with TODO keywords in the car
2483 and faces in the cdr. The face can be a symbol, or a property
2484 list of attributes, like (:foreground \"blue\" :weight bold :underline t)."
2485 :group 'org-faces
2486 :group 'org-todo
2487 :type '(repeat
2488 (cons
2489 (string :tag "keyword")
2490 (sexp :tag "face"))))
2492 (defface org-table ;; font-lock-function-name-face
2493 (org-compatible-face nil
2494 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
2495 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
2496 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
2497 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
2498 (((class color) (min-colors 8) (background light)) (:foreground "blue"))
2499 (((class color) (min-colors 8) (background dark)))))
2500 "Face used for tables."
2501 :group 'org-faces)
2503 (defface org-formula
2504 (org-compatible-face nil
2505 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
2506 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
2507 (((class color) (min-colors 8) (background light)) (:foreground "red"))
2508 (((class color) (min-colors 8) (background dark)) (:foreground "red"))
2509 (t (:bold t :italic t))))
2510 "Face for formulas."
2511 :group 'org-faces)
2513 (defface org-code
2514 (org-compatible-face nil
2515 '((((class color grayscale) (min-colors 88) (background light))
2516 (:foreground "grey50"))
2517 (((class color grayscale) (min-colors 88) (background dark))
2518 (:foreground "grey70"))
2519 (((class color) (min-colors 8) (background light))
2520 (:foreground "green"))
2521 (((class color) (min-colors 8) (background dark))
2522 (:foreground "yellow"))))
2523 "Face for fixed-with text like code snippets."
2524 :group 'org-faces
2525 :version "22.1")
2527 (defface org-verbatim
2528 (org-compatible-face nil
2529 '((((class color grayscale) (min-colors 88) (background light))
2530 (:foreground "grey50" :underline t))
2531 (((class color grayscale) (min-colors 88) (background dark))
2532 (:foreground "grey70" :underline t))
2533 (((class color) (min-colors 8) (background light))
2534 (:foreground "green" :underline t))
2535 (((class color) (min-colors 8) (background dark))
2536 (:foreground "yellow" :underline t))))
2537 "Face for fixed-with text like code snippets."
2538 :group 'org-faces
2539 :version "22.1")
2541 (defface org-agenda-structure ;; font-lock-function-name-face
2542 (org-compatible-face nil
2543 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
2544 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
2545 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
2546 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
2547 (((class color) (min-colors 8)) (:foreground "blue" :bold t))
2548 (t (:bold t))))
2549 "Face used in agenda for captions and dates."
2550 :group 'org-faces)
2552 (defface org-scheduled-today
2553 (org-compatible-face nil
2554 '((((class color) (min-colors 88) (background light)) (:foreground "DarkGreen"))
2555 (((class color) (min-colors 88) (background dark)) (:foreground "PaleGreen"))
2556 (((class color) (min-colors 8)) (:foreground "green"))
2557 (t (:bold t :italic t))))
2558 "Face for items scheduled for a certain day."
2559 :group 'org-faces)
2561 (defface org-scheduled-previously
2562 (org-compatible-face nil
2563 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
2564 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
2565 (((class color) (min-colors 8) (background light)) (:foreground "red"))
2566 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
2567 (t (:bold t))))
2568 "Face for items scheduled previously, and not yet done."
2569 :group 'org-faces)
2571 (defface org-upcoming-deadline
2572 (org-compatible-face nil
2573 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
2574 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
2575 (((class color) (min-colors 8) (background light)) (:foreground "red"))
2576 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
2577 (t (:bold t))))
2578 "Face for items scheduled previously, and not yet done."
2579 :group 'org-faces)
2581 (defcustom org-agenda-deadline-faces
2582 '((1.0 . org-warning)
2583 (0.5 . org-upcoming-deadline)
2584 (0.0 . default))
2585 "Faces for showing deadlines in the agenda.
2586 This is a list of cons cells. The cdr of each cell is a face to be used,
2587 and it can also just be like '(:foreground \"yellow\").
2588 Each car is a fraction of the head-warning time that must have passed for
2589 this the face in the cdr to be used for display. The numbers must be
2590 given in descending order. The head-warning time is normally taken
2591 from `org-deadline-warning-days', but can also be specified in the deadline
2592 timestamp itself, like this:
2594 DEADLINE: <2007-08-13 Mon -8d>
2596 You may use d for days, w for weeks, m for months and y for years. Months
2597 and years will only be treated in an approximate fashion (30.4 days for a
2598 month and 365.24 days for a year)."
2599 :group 'org-faces
2600 :group 'org-agenda-daily/weekly
2601 :type '(repeat
2602 (cons
2603 (number :tag "Fraction of head-warning time passed")
2604 (sexp :tag "Face"))))
2606 (defface org-agenda-restriction-lock
2607 (org-compatible-face nil
2608 '((((class color) (min-colors 88) (background light)) (:background "yellow1"))
2609 (((class color) (min-colors 88) (background dark)) (:background "skyblue4"))
2610 (((class color) (min-colors 16) (background light)) (:background "yellow1"))
2611 (((class color) (min-colors 16) (background dark)) (:background "skyblue4"))
2612 (((class color) (min-colors 8)) (:background "cyan" :foreground "black"))
2613 (t (:inverse-video t))))
2614 "Face for showing the agenda restriction lock."
2615 :group 'org-faces)
2617 (defface org-time-grid ;; font-lock-variable-name-face
2618 (org-compatible-face nil
2619 '((((class color) (min-colors 16) (background light)) (:foreground "DarkGoldenrod"))
2620 (((class color) (min-colors 16) (background dark)) (:foreground "LightGoldenrod"))
2621 (((class color) (min-colors 8)) (:foreground "yellow" :weight light))))
2622 "Face used for time grids."
2623 :group 'org-faces)
2625 (defconst org-level-faces
2626 '(org-level-1 org-level-2 org-level-3 org-level-4
2627 org-level-5 org-level-6 org-level-7 org-level-8
2630 (defcustom org-n-level-faces (length org-level-faces)
2631 "The number of different faces to be used for headlines.
2632 Org-mode defines 8 different headline faces, so this can be at most 8.
2633 If it is less than 8, the level-1 face gets re-used for level N+1 etc."
2634 :type 'number
2635 :group 'org-faces)
2637 ;;; Functions and variables from ther packages
2638 ;; Declared here to avoid compiler warnings
2640 ;; XEmacs only
2641 (defvar outline-mode-menu-heading)
2642 (defvar outline-mode-menu-show)
2643 (defvar outline-mode-menu-hide)
2644 (defvar zmacs-regions) ; XEmacs regions
2646 ;; Emacs only
2647 (defvar mark-active)
2649 ;; Various packages
2650 (declare-function calendar-absolute-from-iso "cal-iso" (&optional date))
2651 (declare-function calendar-forward-day "cal-move" (arg))
2652 (declare-function calendar-goto-date "cal-move" (date))
2653 (declare-function calendar-goto-today "cal-move" ())
2654 (declare-function calendar-iso-from-absolute "cal-iso" (&optional date))
2655 (defvar calc-embedded-close-formula)
2656 (defvar calc-embedded-open-formula)
2657 (declare-function cdlatex-tab "ext:cdlatex" ())
2658 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
2659 (defvar font-lock-unfontify-region-function)
2660 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
2661 (declare-function org-agenda-skip "org-agenda" ())
2662 (declare-function org-format-agenda-item "org-agenda"
2663 (extra txt &optional category tags dotime noprefix remove-re))
2664 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
2665 (declare-function org-agenda-change-all-lines "org-agenda"
2666 (newhead hdmarker &optional fixface))
2667 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
2668 (declare-function org-agenda-maybe-redo "org-agenda" ())
2669 (declare-function parse-time-string "parse-time" (string))
2670 (declare-function remember "remember" (&optional initial))
2671 (declare-function remember-buffer-desc "remember" ())
2672 (declare-function remember-finalize "remember" ())
2673 (defvar remember-save-after-remembering)
2674 (defvar remember-data-file)
2675 (defvar remember-register)
2676 (defvar remember-buffer)
2677 (defvar remember-handler-functions)
2678 (defvar remember-annotation-functions)
2679 (defvar texmathp-why)
2680 (declare-function speedbar-line-directory "speedbar" (&optional depth))
2681 (declare-function table--at-cell-p "table" (position &optional object at-column))
2683 (defvar w3m-current-url)
2684 (defvar w3m-current-title)
2686 (defvar org-latex-regexps)
2688 ;;; Autoload and prepare some org modules
2690 ;; Some table stuff that needs to be defined here, because it is used
2691 ;; by the functions setting up org-mode or checking for table context.
2693 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
2694 "Detects an org-type or table-type table.")
2695 (defconst org-table-line-regexp "^[ \t]*|"
2696 "Detects an org-type table line.")
2697 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
2698 "Detects an org-type table line.")
2699 (defconst org-table-hline-regexp "^[ \t]*|-"
2700 "Detects an org-type table hline.")
2701 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
2702 "Detects a table-type table hline.")
2703 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
2704 "Searching from within a table (any type) this finds the first line
2705 outside the table.")
2707 ;; Autoload the functions in org-table.el that are needed by functions here.
2709 (eval-and-compile
2710 (org-autoload "org-table"
2711 '(org-table-align org-table-begin org-table-blank-field
2712 org-table-convert org-table-convert-region org-table-copy-down
2713 org-table-copy-region org-table-create
2714 org-table-create-or-convert-from-region
2715 org-table-create-with-table.el org-table-current-dline
2716 org-table-cut-region org-table-delete-column org-table-edit-field
2717 org-table-edit-formulas org-table-end org-table-eval-formula
2718 org-table-export org-table-field-info
2719 org-table-get-stored-formulas org-table-goto-column
2720 org-table-hline-and-move org-table-import org-table-insert-column
2721 org-table-insert-hline org-table-insert-row org-table-iterate
2722 org-table-justify-field-maybe org-table-kill-row
2723 org-table-maybe-eval-formula org-table-maybe-recalculate-line
2724 org-table-move-column org-table-move-column-left
2725 org-table-move-column-right org-table-move-row
2726 org-table-move-row-down org-table-move-row-up
2727 org-table-next-field org-table-next-row org-table-paste-rectangle
2728 org-table-previous-field org-table-recalculate
2729 org-table-rotate-recalc-marks org-table-sort-lines org-table-sum
2730 org-table-toggle-coordinate-overlays
2731 org-table-toggle-formula-debugger org-table-wrap-region
2732 orgtbl-mode turn-on-orgtbl)))
2734 (defun org-at-table-p (&optional table-type)
2735 "Return t if the cursor is inside an org-type table.
2736 If TABLE-TYPE is non-nil, also check for table.el-type tables."
2737 (if org-enable-table-editor
2738 (save-excursion
2739 (beginning-of-line 1)
2740 (looking-at (if table-type org-table-any-line-regexp
2741 org-table-line-regexp)))
2742 nil))
2743 (defsubst org-table-p () (org-at-table-p))
2745 (defun org-at-table.el-p ()
2746 "Return t if and only if we are at a table.el table."
2747 (and (org-at-table-p 'any)
2748 (save-excursion
2749 (goto-char (org-table-begin 'any))
2750 (looking-at org-table1-hline-regexp))))
2751 (defun org-table-recognize-table.el ()
2752 "If there is a table.el table nearby, recognize it and move into it."
2753 (if org-table-tab-recognizes-table.el
2754 (if (org-at-table.el-p)
2755 (progn
2756 (beginning-of-line 1)
2757 (if (looking-at org-table-dataline-regexp)
2759 (if (looking-at org-table1-hline-regexp)
2760 (progn
2761 (beginning-of-line 2)
2762 (if (looking-at org-table-any-border-regexp)
2763 (beginning-of-line -1)))))
2764 (if (re-search-forward "|" (org-table-end t) t)
2765 (progn
2766 (require 'table)
2767 (if (table--at-cell-p (point))
2769 (message "recognizing table.el table...")
2770 (table-recognize-table)
2771 (message "recognizing table.el table...done")))
2772 (error "This should not happen..."))
2774 nil)
2775 nil))
2777 (defun org-at-table-hline-p ()
2778 "Return t if the cursor is inside a hline in a table."
2779 (if org-enable-table-editor
2780 (save-excursion
2781 (beginning-of-line 1)
2782 (looking-at org-table-hline-regexp))
2783 nil))
2785 (defvar org-table-clean-did-remove-column nil)
2787 (defun org-table-map-tables (function)
2788 "Apply FUNCTION to the start of all tables in the buffer."
2789 (save-excursion
2790 (save-restriction
2791 (widen)
2792 (goto-char (point-min))
2793 (while (re-search-forward org-table-any-line-regexp nil t)
2794 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
2795 (beginning-of-line 1)
2796 (if (looking-at org-table-line-regexp)
2797 (save-excursion (funcall function)))
2798 (re-search-forward org-table-any-border-regexp nil 1))))
2799 (message "Mapping tables: done"))
2801 ;; Declare and autoload functions from org-exp.el
2803 (declare-function org-default-export-plist "org-exp")
2804 (declare-function org-infile-export-plist "org-exp")
2805 (declare-function org-get-current-options "org-exp")
2806 (eval-and-compile
2807 (org-autoload "org-exp"
2808 '(org-export org-export-as-ascii org-export-visible
2809 org-insert-export-options-template org-export-as-html-and-open
2810 org-export-as-html-batch org-export-as-html-to-buffer
2811 org-replace-region-by-html org-export-region-as-html
2812 org-export-as-html org-export-icalendar-this-file
2813 org-export-icalendar-all-agenda-files
2814 org-export-icalendar-combine-agenda-files org-export-as-xoxo)))
2816 ;; Autoload org-remember
2818 (eval-and-compile
2819 (org-autoload "org-remember"
2820 '(org-remember-insinuate org-remember-annotation
2821 org-remember-apply-template org-remember org-remember-handler)))
2823 ;; Autoload org-clock.el
2825 (defvar org-clock-marker (make-marker)
2826 "Marker recording the last clock-in.")
2828 (eval-and-compile
2829 (org-autoload
2830 "org-clock"
2831 '(org-clock-in org-clock-out org-clock-cancel
2832 org-clock-goto org-clock-sum org-clock-display
2833 org-remove-clock-overlays org-clock-report
2834 org-clocktable-shift org-dblock-write:clocktable
2835 org-get-clocktable)))
2837 (defun org-clock-update-time-maybe ()
2838 "If this is a CLOCK line, update it and return t.
2839 Otherwise, return nil."
2840 (interactive)
2841 (save-excursion
2842 (beginning-of-line 1)
2843 (skip-chars-forward " \t")
2844 (when (looking-at org-clock-string)
2845 (let ((re (concat "[ \t]*" org-clock-string
2846 " *[[<]\\([^]>]+\\)[]>]-+[[<]\\([^]>]+\\)[]>]"
2847 "\\([ \t]*=>.*\\)?"))
2848 ts te h m s)
2849 (if (not (looking-at re))
2851 (and (match-end 3) (delete-region (match-beginning 3) (match-end 3)))
2852 (end-of-line 1)
2853 (setq ts (match-string 1)
2854 te (match-string 2))
2855 (setq s (- (time-to-seconds
2856 (apply 'encode-time (org-parse-time-string te)))
2857 (time-to-seconds
2858 (apply 'encode-time (org-parse-time-string ts))))
2859 h (floor (/ s 3600))
2860 s (- s (* 3600 h))
2861 m (floor (/ s 60))
2862 s (- s (* 60 s)))
2863 (insert " => " (format "%2d:%02d" h m))
2864 t)))))
2866 (defun org-check-running-clock ()
2867 "Check if the current buffer contains the running clock.
2868 If yes, offer to stop it and to save the buffer with the changes."
2869 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
2870 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
2871 (buffer-name))))
2872 (org-clock-out)
2873 (when (y-or-n-p "Save changed buffer?")
2874 (save-buffer))))
2876 (defun org-clocktable-try-shift (dir n)
2877 "Check if this line starts a clock table, if yes, shift the time block."
2878 (when (org-match-line "#\\+BEGIN: clocktable\\>")
2879 (org-clocktable-shift dir n)))
2881 ;;; Variables for pre-computed regular expressions, all buffer local
2883 (defvar org-drawer-regexp nil
2884 "Matches first line of a hidden block.")
2885 (make-variable-buffer-local 'org-drawer-regexp)
2886 (defvar org-todo-regexp nil
2887 "Matches any of the TODO state keywords.")
2888 (make-variable-buffer-local 'org-todo-regexp)
2889 (defvar org-not-done-regexp nil
2890 "Matches any of the TODO state keywords except the last one.")
2891 (make-variable-buffer-local 'org-not-done-regexp)
2892 (defvar org-todo-line-regexp nil
2893 "Matches a headline and puts TODO state into group 2 if present.")
2894 (make-variable-buffer-local 'org-todo-line-regexp)
2895 (defvar org-complex-heading-regexp nil
2896 "Matches a headline and puts everything into groups:
2897 group 1: the stars
2898 group 2: The todo keyword, maybe
2899 group 3: Priority cookie
2900 group 4: True headline
2901 group 5: Tags")
2902 (make-variable-buffer-local 'org-complex-heading-regexp)
2903 (defvar org-todo-line-tags-regexp nil
2904 "Matches a headline and puts TODO state into group 2 if present.
2905 Also put tags into group 4 if tags are present.")
2906 (make-variable-buffer-local 'org-todo-line-tags-regexp)
2907 (defvar org-nl-done-regexp nil
2908 "Matches newline followed by a headline with the DONE keyword.")
2909 (make-variable-buffer-local 'org-nl-done-regexp)
2910 (defvar org-looking-at-done-regexp nil
2911 "Matches the DONE keyword a point.")
2912 (make-variable-buffer-local 'org-looking-at-done-regexp)
2913 (defvar org-ds-keyword-length 12
2914 "Maximum length of the Deadline and SCHEDULED keywords.")
2915 (make-variable-buffer-local 'org-ds-keyword-length)
2916 (defvar org-deadline-regexp nil
2917 "Matches the DEADLINE keyword.")
2918 (make-variable-buffer-local 'org-deadline-regexp)
2919 (defvar org-deadline-time-regexp nil
2920 "Matches the DEADLINE keyword together with a time stamp.")
2921 (make-variable-buffer-local 'org-deadline-time-regexp)
2922 (defvar org-deadline-line-regexp nil
2923 "Matches the DEADLINE keyword and the rest of the line.")
2924 (make-variable-buffer-local 'org-deadline-line-regexp)
2925 (defvar org-scheduled-regexp nil
2926 "Matches the SCHEDULED keyword.")
2927 (make-variable-buffer-local 'org-scheduled-regexp)
2928 (defvar org-scheduled-time-regexp nil
2929 "Matches the SCHEDULED keyword together with a time stamp.")
2930 (make-variable-buffer-local 'org-scheduled-time-regexp)
2931 (defvar org-closed-time-regexp nil
2932 "Matches the CLOSED keyword together with a time stamp.")
2933 (make-variable-buffer-local 'org-closed-time-regexp)
2935 (defvar org-keyword-time-regexp nil
2936 "Matches any of the 4 keywords, together with the time stamp.")
2937 (make-variable-buffer-local 'org-keyword-time-regexp)
2938 (defvar org-keyword-time-not-clock-regexp nil
2939 "Matches any of the 3 keywords, together with the time stamp.")
2940 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
2941 (defvar org-maybe-keyword-time-regexp nil
2942 "Matches a timestamp, possibly preceeded by a keyword.")
2943 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
2944 (defvar org-planning-or-clock-line-re nil
2945 "Matches a line with planning or clock info.")
2946 (make-variable-buffer-local 'org-planning-or-clock-line-re)
2948 (defconst org-plain-time-of-day-regexp
2949 (concat
2950 "\\(\\<[012]?[0-9]"
2951 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
2952 "\\(--?"
2953 "\\(\\<[012]?[0-9]"
2954 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
2955 "\\)?")
2956 "Regular expression to match a plain time or time range.
2957 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
2958 groups carry important information:
2959 0 the full match
2960 1 the first time, range or not
2961 8 the second time, if it is a range.")
2963 (defconst org-plain-time-extension-regexp
2964 (concat
2965 "\\(\\<[012]?[0-9]"
2966 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
2967 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
2968 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
2969 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
2970 groups carry important information:
2971 0 the full match
2972 7 hours of duration
2973 9 minutes of duration")
2975 (defconst org-stamp-time-of-day-regexp
2976 (concat
2977 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
2978 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
2979 "\\(--?"
2980 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
2981 "Regular expression to match a timestamp time or time range.
2982 After a match, the following groups carry important information:
2983 0 the full match
2984 1 date plus weekday, for backreferencing to make sure both times on same day
2985 2 the first time, range or not
2986 4 the second time, if it is a range.")
2988 (defconst org-startup-options
2989 '(("fold" org-startup-folded t)
2990 ("overview" org-startup-folded t)
2991 ("nofold" org-startup-folded nil)
2992 ("showall" org-startup-folded nil)
2993 ("content" org-startup-folded content)
2994 ("hidestars" org-hide-leading-stars t)
2995 ("showstars" org-hide-leading-stars nil)
2996 ("odd" org-odd-levels-only t)
2997 ("oddeven" org-odd-levels-only nil)
2998 ("align" org-startup-align-all-tables t)
2999 ("noalign" org-startup-align-all-tables nil)
3000 ("customtime" org-display-custom-times t)
3001 ("logdone" org-log-done time)
3002 ("lognotedone" org-log-done note)
3003 ("nologdone" org-log-done nil)
3004 ("lognoteclock-out" org-log-note-clock-out t)
3005 ("nolognoteclock-out" org-log-note-clock-out nil)
3006 ("logrepeat" org-log-repeat state)
3007 ("lognoterepeat" org-log-repeat note)
3008 ("nologrepeat" org-log-repeat nil)
3009 ("constcgs" constants-unit-system cgs)
3010 ("constSI" constants-unit-system SI))
3011 "Variable associated with STARTUP options for org-mode.
3012 Each element is a list of three items: The startup options as written
3013 in the #+STARTUP line, the corresponding variable, and the value to
3014 set this variable to if the option is found. An optional forth element PUSH
3015 means to push this value onto the list in the variable.")
3017 (defun org-set-regexps-and-options ()
3018 "Precompute regular expressions for current buffer."
3019 (when (org-mode-p)
3020 (org-set-local 'org-todo-kwd-alist nil)
3021 (org-set-local 'org-todo-key-alist nil)
3022 (org-set-local 'org-todo-key-trigger nil)
3023 (org-set-local 'org-todo-keywords-1 nil)
3024 (org-set-local 'org-done-keywords nil)
3025 (org-set-local 'org-todo-heads nil)
3026 (org-set-local 'org-todo-sets nil)
3027 (org-set-local 'org-todo-log-states nil)
3028 (let ((re (org-make-options-regexp
3029 '("CATEGORY" "SEQ_TODO" "TYP_TODO" "TODO" "COLUMNS"
3030 "STARTUP" "ARCHIVE" "TAGS" "LINK" "PRIORITIES"
3031 "CONSTANTS" "PROPERTY" "DRAWERS")))
3032 (splitre "[ \t]+")
3033 kwds kws0 kwsa key log value cat arch tags const links hw dws
3034 tail sep kws1 prio props drawers)
3035 (save-excursion
3036 (save-restriction
3037 (widen)
3038 (goto-char (point-min))
3039 (while (re-search-forward re nil t)
3040 (setq key (match-string 1) value (org-match-string-no-properties 2))
3041 (cond
3042 ((equal key "CATEGORY")
3043 (if (string-match "[ \t]+$" value)
3044 (setq value (replace-match "" t t value)))
3045 (setq cat value))
3046 ((member key '("SEQ_TODO" "TODO"))
3047 (push (cons 'sequence (org-split-string value splitre)) kwds))
3048 ((equal key "TYP_TODO")
3049 (push (cons 'type (org-split-string value splitre)) kwds))
3050 ((equal key "TAGS")
3051 (setq tags (append tags (org-split-string value splitre))))
3052 ((equal key "COLUMNS")
3053 (org-set-local 'org-columns-default-format value))
3054 ((equal key "LINK")
3055 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
3056 (push (cons (match-string 1 value)
3057 (org-trim (match-string 2 value)))
3058 links)))
3059 ((equal key "PRIORITIES")
3060 (setq prio (org-split-string value " +")))
3061 ((equal key "PROPERTY")
3062 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
3063 (push (cons (match-string 1 value) (match-string 2 value))
3064 props)))
3065 ((equal key "DRAWERS")
3066 (setq drawers (org-split-string value splitre)))
3067 ((equal key "CONSTANTS")
3068 (setq const (append const (org-split-string value splitre))))
3069 ((equal key "STARTUP")
3070 (let ((opts (org-split-string value splitre))
3071 l var val)
3072 (while (setq l (pop opts))
3073 (when (setq l (assoc l org-startup-options))
3074 (setq var (nth 1 l) val (nth 2 l))
3075 (if (not (nth 3 l))
3076 (set (make-local-variable var) val)
3077 (if (not (listp (symbol-value var)))
3078 (set (make-local-variable var) nil))
3079 (set (make-local-variable var) (symbol-value var))
3080 (add-to-list var val))))))
3081 ((equal key "ARCHIVE")
3082 (string-match " *$" value)
3083 (setq arch (replace-match "" t t value))
3084 (remove-text-properties 0 (length arch)
3085 '(face t fontified t) arch)))
3087 (when cat
3088 (org-set-local 'org-category (intern cat))
3089 (push (cons "CATEGORY" cat) props))
3090 (when prio
3091 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
3092 (setq prio (mapcar 'string-to-char prio))
3093 (org-set-local 'org-highest-priority (nth 0 prio))
3094 (org-set-local 'org-lowest-priority (nth 1 prio))
3095 (org-set-local 'org-default-priority (nth 2 prio)))
3096 (and props (org-set-local 'org-local-properties (nreverse props)))
3097 (and drawers (org-set-local 'org-drawers drawers))
3098 (and arch (org-set-local 'org-archive-location arch))
3099 (and links (setq org-link-abbrev-alist-local (nreverse links)))
3100 ;; Process the TODO keywords
3101 (unless kwds
3102 ;; Use the global values as if they had been given locally.
3103 (setq kwds (default-value 'org-todo-keywords))
3104 (if (stringp (car kwds))
3105 (setq kwds (list (cons org-todo-interpretation
3106 (default-value 'org-todo-keywords)))))
3107 (setq kwds (reverse kwds)))
3108 (setq kwds (nreverse kwds))
3109 (let (inter kws kw)
3110 (while (setq kws (pop kwds))
3111 (setq inter (pop kws) sep (member "|" kws)
3112 kws0 (delete "|" (copy-sequence kws))
3113 kwsa nil
3114 kws1 (mapcar
3115 (lambda (x)
3116 ;; 1 2
3117 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
3118 (progn
3119 (setq kw (match-string 1 x)
3120 key (and (match-end 2) (match-string 2 x))
3121 log (org-extract-log-state-settings x))
3122 (push (cons kw (and key (string-to-char key))) kwsa)
3123 (and log (push log org-todo-log-states))
3125 (error "Invalid TODO keyword %s" x)))
3126 kws0)
3127 kwsa (if kwsa (append '((:startgroup))
3128 (nreverse kwsa)
3129 '((:endgroup))))
3130 hw (car kws1)
3131 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
3132 tail (list inter hw (car dws) (org-last dws)))
3133 (add-to-list 'org-todo-heads hw 'append)
3134 (push kws1 org-todo-sets)
3135 (setq org-done-keywords (append org-done-keywords dws nil))
3136 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
3137 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
3138 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
3139 (setq org-todo-sets (nreverse org-todo-sets)
3140 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
3141 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
3142 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
3143 ;; Process the constants
3144 (when const
3145 (let (e cst)
3146 (while (setq e (pop const))
3147 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
3148 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
3149 (setq org-table-formula-constants-local cst)))
3151 ;; Process the tags.
3152 (when tags
3153 (let (e tgs)
3154 (while (setq e (pop tags))
3155 (cond
3156 ((equal e "{") (push '(:startgroup) tgs))
3157 ((equal e "}") (push '(:endgroup) tgs))
3158 ((string-match (org-re "^\\([[:alnum:]_@]+\\)(\\(.\\))$") e)
3159 (push (cons (match-string 1 e)
3160 (string-to-char (match-string 2 e)))
3161 tgs))
3162 (t (push (list e) tgs))))
3163 (org-set-local 'org-tag-alist nil)
3164 (while (setq e (pop tgs))
3165 (or (and (stringp (car e))
3166 (assoc (car e) org-tag-alist))
3167 (push e org-tag-alist))))))
3169 ;; Compute the regular expressions and other local variables
3170 (if (not org-done-keywords)
3171 (setq org-done-keywords (list (org-last org-todo-keywords-1))))
3172 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
3173 (length org-scheduled-string)))
3174 org-drawer-regexp
3175 (concat "^[ \t]*:\\("
3176 (mapconcat 'regexp-quote org-drawers "\\|")
3177 "\\):[ \t]*$")
3178 org-not-done-keywords
3179 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
3180 org-todo-regexp
3181 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords-1
3182 "\\|") "\\)\\>")
3183 org-not-done-regexp
3184 (concat "\\<\\("
3185 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
3186 "\\)\\>")
3187 org-todo-line-regexp
3188 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3189 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3190 "\\)\\>\\)?[ \t]*\\(.*\\)")
3191 org-complex-heading-regexp
3192 (concat "^\\(\\*+\\)\\(?:[ \t]+\\("
3193 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3194 "\\)\\>\\)?\\(?:[ \t]*\\(\\[#.\\]\\)\\)?[ \t]*\\(.*?\\)"
3195 "\\(?:[ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
3196 org-nl-done-regexp
3197 (concat "\n\\*+[ \t]+"
3198 "\\(?:" (mapconcat 'regexp-quote org-done-keywords "\\|")
3199 "\\)" "\\>")
3200 org-todo-line-tags-regexp
3201 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3202 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3203 (org-re
3204 "\\)\\>\\)? *\\(.*?\\([ \t]:[[:alnum:]:_@]+:[ \t]*\\)?$\\)"))
3205 org-looking-at-done-regexp
3206 (concat "^" "\\(?:"
3207 (mapconcat 'regexp-quote org-done-keywords "\\|") "\\)"
3208 "\\>")
3209 org-deadline-regexp (concat "\\<" org-deadline-string)
3210 org-deadline-time-regexp
3211 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
3212 org-deadline-line-regexp
3213 (concat "\\<\\(" org-deadline-string "\\).*")
3214 org-scheduled-regexp
3215 (concat "\\<" org-scheduled-string)
3216 org-scheduled-time-regexp
3217 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
3218 org-closed-time-regexp
3219 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
3220 org-keyword-time-regexp
3221 (concat "\\<\\(" org-scheduled-string
3222 "\\|" org-deadline-string
3223 "\\|" org-closed-string
3224 "\\|" org-clock-string "\\)"
3225 " *[[<]\\([^]>]+\\)[]>]")
3226 org-keyword-time-not-clock-regexp
3227 (concat "\\<\\(" org-scheduled-string
3228 "\\|" org-deadline-string
3229 "\\|" org-closed-string
3230 "\\)"
3231 " *[[<]\\([^]>]+\\)[]>]")
3232 org-maybe-keyword-time-regexp
3233 (concat "\\(\\<\\(" org-scheduled-string
3234 "\\|" org-deadline-string
3235 "\\|" org-closed-string
3236 "\\|" org-clock-string "\\)\\)?"
3237 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
3238 org-planning-or-clock-line-re
3239 (concat "\\(?:^[ \t]*\\(" org-scheduled-string
3240 "\\|" org-deadline-string
3241 "\\|" org-closed-string "\\|" org-clock-string
3242 "\\)\\>\\)")
3244 (org-compute-latex-and-specials-regexp)
3245 (org-set-font-lock-defaults)))
3247 (defun org-extract-log-state-settings (x)
3248 "Extract the log state setting from a TODO keyword string.
3249 This will extract info from a string like \"WAIT(w@/!)\"."
3250 (let (kw key log1 log2)
3251 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
3252 (setq kw (match-string 1 x)
3253 key (and (match-end 2) (match-string 2 x))
3254 log1 (and (match-end 3) (match-string 3 x))
3255 log2 (and (match-end 4) (match-string 4 x)))
3256 (and (or log1 log2)
3257 (list kw
3258 (and log1 (if (equal log1 "!") 'time 'note))
3259 (and log2 (if (equal log2 "!") 'time 'note)))))))
3261 (defun org-remove-keyword-keys (list)
3262 "Remove a pair of parenthesis at the end of each string in LIST."
3263 (mapcar (lambda (x)
3264 (if (string-match "(.*)$" x)
3265 (substring x 0 (match-beginning 0))
3267 list))
3269 ;; FIXME: this could be done much better, using second characters etc.
3270 (defun org-assign-fast-keys (alist)
3271 "Assign fast keys to a keyword-key alist.
3272 Respect keys that are already there."
3273 (let (new e k c c1 c2 (char ?a))
3274 (while (setq e (pop alist))
3275 (cond
3276 ((equal e '(:startgroup)) (push e new))
3277 ((equal e '(:endgroup)) (push e new))
3279 (setq k (car e) c2 nil)
3280 (if (cdr e)
3281 (setq c (cdr e))
3282 ;; automatically assign a character.
3283 (setq c1 (string-to-char
3284 (downcase (substring
3285 k (if (= (string-to-char k) ?@) 1 0)))))
3286 (if (or (rassoc c1 new) (rassoc c1 alist))
3287 (while (or (rassoc char new) (rassoc char alist))
3288 (setq char (1+ char)))
3289 (setq c2 c1))
3290 (setq c (or c2 char)))
3291 (push (cons k c) new))))
3292 (nreverse new)))
3294 ;;; Some variables used in various places
3296 (defvar org-window-configuration nil
3297 "Used in various places to store a window configuration.")
3298 (defvar org-finish-function nil
3299 "Function to be called when `C-c C-c' is used.
3300 This is for getting out of special buffers like remember.")
3303 ;; FIXME: Occasionally check by commenting these, to make sure
3304 ;; no other functions uses these, forgetting to let-bind them.
3305 (defvar entry)
3306 (defvar state)
3307 (defvar last-state)
3308 (defvar date)
3309 (defvar description)
3311 ;; Defined somewhere in this file, but used before definition.
3312 (defvar org-html-entities)
3313 (defvar org-struct-menu)
3314 (defvar org-org-menu)
3315 (defvar org-tbl-menu)
3316 (defvar org-agenda-keymap)
3318 ;;;; Define the Org-mode
3320 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
3321 (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."))
3324 ;; We use a before-change function to check if a table might need
3325 ;; an update.
3326 (defvar org-table-may-need-update t
3327 "Indicates that a table might need an update.
3328 This variable is set by `org-before-change-function'.
3329 `org-table-align' sets it back to nil.")
3330 (defun org-before-change-function (beg end)
3331 "Every change indicates that a table might need an update."
3332 (setq org-table-may-need-update t))
3333 (defvar org-mode-map)
3334 (defvar org-mode-hook nil)
3335 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
3336 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
3337 (defvar org-table-buffer-is-an nil)
3338 (defconst org-outline-regexp "\\*+ ")
3340 ;;;###autoload
3341 (define-derived-mode org-mode outline-mode "Org"
3342 "Outline-based notes management and organizer, alias
3343 \"Carsten's outline-mode for keeping track of everything.\"
3345 Org-mode develops organizational tasks around a NOTES file which
3346 contains information about projects as plain text. Org-mode is
3347 implemented on top of outline-mode, which is ideal to keep the content
3348 of large files well structured. It supports ToDo items, deadlines and
3349 time stamps, which magically appear in the diary listing of the Emacs
3350 calendar. Tables are easily created with a built-in table editor.
3351 Plain text URL-like links connect to websites, emails (VM), Usenet
3352 messages (Gnus), BBDB entries, and any files related to the project.
3353 For printing and sharing of notes, an Org-mode file (or a part of it)
3354 can be exported as a structured ASCII or HTML file.
3356 The following commands are available:
3358 \\{org-mode-map}"
3360 ;; Get rid of Outline menus, they are not needed
3361 ;; Need to do this here because define-derived-mode sets up
3362 ;; the keymap so late. Still, it is a waste to call this each time
3363 ;; we switch another buffer into org-mode.
3364 (if (featurep 'xemacs)
3365 (when (boundp 'outline-mode-menu-heading)
3366 ;; Assume this is Greg's port, it used easymenu
3367 (easy-menu-remove outline-mode-menu-heading)
3368 (easy-menu-remove outline-mode-menu-show)
3369 (easy-menu-remove outline-mode-menu-hide))
3370 (define-key org-mode-map [menu-bar headings] 'undefined)
3371 (define-key org-mode-map [menu-bar hide] 'undefined)
3372 (define-key org-mode-map [menu-bar show] 'undefined))
3374 (org-load-modules-maybe)
3375 (easy-menu-add org-org-menu)
3376 (easy-menu-add org-tbl-menu)
3377 (org-install-agenda-files-menu)
3378 (if org-descriptive-links (org-add-to-invisibility-spec '(org-link)))
3379 (org-add-to-invisibility-spec '(org-cwidth))
3380 (when (featurep 'xemacs)
3381 (org-set-local 'line-move-ignore-invisible t))
3382 (org-set-local 'outline-regexp org-outline-regexp)
3383 (org-set-local 'outline-level 'org-outline-level)
3384 (when (and org-ellipsis
3385 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
3386 (fboundp 'make-glyph-code))
3387 (unless org-display-table
3388 (setq org-display-table (make-display-table)))
3389 (set-display-table-slot
3390 org-display-table 4
3391 (vconcat (mapcar
3392 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
3393 org-ellipsis)))
3394 (if (stringp org-ellipsis) org-ellipsis "..."))))
3395 (setq buffer-display-table org-display-table))
3396 (org-set-regexps-and-options)
3397 ;; Calc embedded
3398 (org-set-local 'calc-embedded-open-mode "# ")
3399 (modify-syntax-entry ?# "<")
3400 (modify-syntax-entry ?@ "w")
3401 (if org-startup-truncated (setq truncate-lines t))
3402 (org-set-local 'font-lock-unfontify-region-function
3403 'org-unfontify-region)
3404 ;; Activate before-change-function
3405 (org-set-local 'org-table-may-need-update t)
3406 (org-add-hook 'before-change-functions 'org-before-change-function nil
3407 'local)
3408 ;; Check for running clock before killing a buffer
3409 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
3410 ;; Paragraphs and auto-filling
3411 (org-set-autofill-regexps)
3412 (setq indent-line-function 'org-indent-line-function)
3413 (org-update-radio-target-regexp)
3415 ;; Comment characters
3416 ; (org-set-local 'comment-start "#") ;; FIXME: this breaks wrapping
3417 (org-set-local 'comment-padding " ")
3419 ;; Align options lines
3420 (org-set-local
3421 'align-mode-rules-list
3422 '((org-in-buffer-settings
3423 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
3424 (modes . '(org-mode)))))
3426 ;; Imenu
3427 (org-set-local 'imenu-create-index-function
3428 'org-imenu-get-tree)
3430 ;; Make isearch reveal context
3431 (if (or (featurep 'xemacs)
3432 (not (boundp 'outline-isearch-open-invisible-function)))
3433 ;; Emacs 21 and XEmacs make use of the hook
3434 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
3435 ;; Emacs 22 deals with this through a special variable
3436 (org-set-local 'outline-isearch-open-invisible-function
3437 (lambda (&rest ignore) (org-show-context 'isearch))))
3439 ;; If empty file that did not turn on org-mode automatically, make it to.
3440 (if (and org-insert-mode-line-in-empty-file
3441 (interactive-p)
3442 (= (point-min) (point-max)))
3443 (insert "# -*- mode: org -*-\n\n"))
3445 (unless org-inhibit-startup
3446 (when org-startup-align-all-tables
3447 (let ((bmp (buffer-modified-p)))
3448 (org-table-map-tables 'org-table-align)
3449 (set-buffer-modified-p bmp)))
3450 (org-cycle-hide-drawers 'all)
3451 (cond
3452 ((eq org-startup-folded t)
3453 (org-cycle '(4)))
3454 ((eq org-startup-folded 'content)
3455 (let ((this-command 'org-cycle) (last-command 'org-cycle))
3456 (org-cycle '(4)) (org-cycle '(4)))))))
3458 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
3460 (defun org-current-time ()
3461 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
3462 (if (> (car org-time-stamp-rounding-minutes) 1)
3463 (let ((r (car org-time-stamp-rounding-minutes))
3464 (time (decode-time)))
3465 (apply 'encode-time
3466 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
3467 (nthcdr 2 time))))
3468 (current-time)))
3470 ;;;; Font-Lock stuff, including the activators
3472 (defvar org-mouse-map (make-sparse-keymap))
3473 (org-defkey org-mouse-map
3474 (if (featurep 'xemacs) [button2] [mouse-2]) 'org-open-at-mouse)
3475 (org-defkey org-mouse-map
3476 (if (featurep 'xemacs) [button3] [mouse-3]) 'org-find-file-at-mouse)
3477 (when org-mouse-1-follows-link
3478 (org-defkey org-mouse-map [follow-link] 'mouse-face))
3479 (when org-tab-follows-link
3480 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
3481 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
3482 (when org-return-follows-link
3483 (org-defkey org-mouse-map [(return)] 'org-open-at-point)
3484 (org-defkey org-mouse-map "\C-m" 'org-open-at-point))
3486 (require 'font-lock)
3488 (defconst org-non-link-chars "]\t\n\r<>")
3489 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
3490 "shell" "elisp"))
3491 (defvar org-link-re-with-space nil
3492 "Matches a link with spaces, optional angular brackets around it.")
3493 (defvar org-link-re-with-space2 nil
3494 "Matches a link with spaces, optional angular brackets around it.")
3495 (defvar org-angle-link-re nil
3496 "Matches link with angular brackets, spaces are allowed.")
3497 (defvar org-plain-link-re nil
3498 "Matches plain link, without spaces.")
3499 (defvar org-bracket-link-regexp nil
3500 "Matches a link in double brackets.")
3501 (defvar org-bracket-link-analytic-regexp nil
3502 "Regular expression used to analyze links.
3503 Here is what the match groups contain after a match:
3504 1: http:
3505 2: http
3506 3: path
3507 4: [desc]
3508 5: desc")
3509 (defvar org-any-link-re nil
3510 "Regular expression matching any link.")
3512 (defun org-make-link-regexps ()
3513 "Update the link regular expressions.
3514 This should be called after the variable `org-link-types' has changed."
3515 (setq org-link-re-with-space
3516 (concat
3517 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3518 "\\([^" org-non-link-chars " ]"
3519 "[^" org-non-link-chars "]*"
3520 "[^" org-non-link-chars " ]\\)>?")
3521 org-link-re-with-space2
3522 (concat
3523 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3524 "\\([^" org-non-link-chars " ]"
3525 "[^]\t\n\r]*"
3526 "[^" org-non-link-chars " ]\\)>?")
3527 org-angle-link-re
3528 (concat
3529 "<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3530 "\\([^" org-non-link-chars " ]"
3531 "[^" org-non-link-chars "]*"
3532 "\\)>")
3533 org-plain-link-re
3534 (concat
3535 "\\<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3536 "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
3537 org-bracket-link-regexp
3538 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
3539 org-bracket-link-analytic-regexp
3540 (concat
3541 "\\[\\["
3542 "\\(\\(" (mapconcat 'identity org-link-types "\\|") "\\):\\)?"
3543 "\\([^]]+\\)"
3544 "\\]"
3545 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
3546 "\\]")
3547 org-any-link-re
3548 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
3549 org-angle-link-re "\\)\\|\\("
3550 org-plain-link-re "\\)")))
3552 (org-make-link-regexps)
3554 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)>"
3555 "Regular expression for fast time stamp matching.")
3556 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)[]>]"
3557 "Regular expression for fast time stamp matching.")
3558 (defconst org-ts-regexp0 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
3559 "Regular expression matching time strings for analysis.
3560 This one does not require the space after the date, so it can be used
3561 on a string that terminates immediately after the date.")
3562 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) +\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
3563 "Regular expression matching time strings for analysis.")
3564 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
3565 "Regular expression matching time stamps, with groups.")
3566 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
3567 "Regular expression matching time stamps (also [..]), with groups.")
3568 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
3569 "Regular expression matching a time stamp range.")
3570 (defconst org-tr-regexp-both
3571 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
3572 "Regular expression matching a time stamp range.")
3573 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
3574 org-ts-regexp "\\)?")
3575 "Regular expression matching a time stamp or time stamp range.")
3576 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
3577 org-ts-regexp-both "\\)?")
3578 "Regular expression matching a time stamp or time stamp range.
3579 The time stamps may be either active or inactive.")
3581 (defvar org-emph-face nil)
3583 (defun org-do-emphasis-faces (limit)
3584 "Run through the buffer and add overlays to links."
3585 (let (rtn)
3586 (while (and (not rtn) (re-search-forward org-emph-re limit t))
3587 (if (not (= (char-after (match-beginning 3))
3588 (char-after (match-beginning 4))))
3589 (progn
3590 (setq rtn t)
3591 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
3592 'face
3593 (nth 1 (assoc (match-string 3)
3594 org-emphasis-alist)))
3595 (add-text-properties (match-beginning 2) (match-end 2)
3596 '(font-lock-multiline t))
3597 (when org-hide-emphasis-markers
3598 (add-text-properties (match-end 4) (match-beginning 5)
3599 '(invisible org-link))
3600 (add-text-properties (match-beginning 3) (match-end 3)
3601 '(invisible org-link)))))
3602 (backward-char 1))
3603 rtn))
3605 (defun org-emphasize (&optional char)
3606 "Insert or change an emphasis, i.e. a font like bold or italic.
3607 If there is an active region, change that region to a new emphasis.
3608 If there is no region, just insert the marker characters and position
3609 the cursor between them.
3610 CHAR should be either the marker character, or the first character of the
3611 HTML tag associated with that emphasis. If CHAR is a space, the means
3612 to remove the emphasis of the selected region.
3613 If char is not given (for example in an interactive call) it
3614 will be prompted for."
3615 (interactive)
3616 (let ((eal org-emphasis-alist) e det
3617 (erc org-emphasis-regexp-components)
3618 (prompt "")
3619 (string "") beg end move tag c s)
3620 (if (org-region-active-p)
3621 (setq beg (region-beginning) end (region-end)
3622 string (buffer-substring beg end))
3623 (setq move t))
3625 (while (setq e (pop eal))
3626 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
3627 c (aref tag 0))
3628 (push (cons c (string-to-char (car e))) det)
3629 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
3630 (substring tag 1)))))
3631 (unless char
3632 (message "%s" (concat "Emphasis marker or tag:" prompt))
3633 (setq char (read-char-exclusive)))
3634 (setq char (or (cdr (assoc char det)) char))
3635 (if (equal char ?\ )
3636 (setq s "" move nil)
3637 (unless (assoc (char-to-string char) org-emphasis-alist)
3638 (error "No such emphasis marker: \"%c\"" char))
3639 (setq s (char-to-string char)))
3640 (while (and (> (length string) 1)
3641 (equal (substring string 0 1) (substring string -1))
3642 (assoc (substring string 0 1) org-emphasis-alist))
3643 (setq string (substring string 1 -1)))
3644 (setq string (concat s string s))
3645 (if beg (delete-region beg end))
3646 (unless (or (bolp)
3647 (string-match (concat "[" (nth 0 erc) "\n]")
3648 (char-to-string (char-before (point)))))
3649 (insert " "))
3650 (unless (string-match (concat "[" (nth 1 erc) "\n]")
3651 (char-to-string (char-after (point))))
3652 (insert " ") (backward-char 1))
3653 (insert string)
3654 (and move (backward-char 1))))
3656 (defconst org-nonsticky-props
3657 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
3660 (defun org-activate-plain-links (limit)
3661 "Run through the buffer and add overlays to links."
3662 (catch 'exit
3663 (let (f)
3664 (while (re-search-forward org-plain-link-re limit t)
3665 (setq f (get-text-property (match-beginning 0) 'face))
3666 (if (or (eq f 'org-tag)
3667 (and (listp f) (memq 'org-tag f)))
3669 (add-text-properties (match-beginning 0) (match-end 0)
3670 (list 'mouse-face 'highlight
3671 'rear-nonsticky org-nonsticky-props
3672 'keymap org-mouse-map
3674 (throw 'exit t))))))
3676 (defun org-activate-code (limit)
3677 (if (re-search-forward "^[ \t]*\\(:.*\\)" limit t)
3678 (unless (get-text-property (match-beginning 1) 'face)
3679 (remove-text-properties (match-beginning 0) (match-end 0)
3680 '(display t invisible t intangible t))
3681 t)))
3683 (defun org-activate-angle-links (limit)
3684 "Run through the buffer and add overlays to links."
3685 (if (re-search-forward org-angle-link-re limit t)
3686 (progn
3687 (add-text-properties (match-beginning 0) (match-end 0)
3688 (list 'mouse-face 'highlight
3689 'rear-nonsticky org-nonsticky-props
3690 'keymap org-mouse-map
3692 t)))
3694 (defun org-activate-bracket-links (limit)
3695 "Run through the buffer and add overlays to bracketed links."
3696 (if (re-search-forward org-bracket-link-regexp limit t)
3697 (let* ((help (concat "LINK: "
3698 (org-match-string-no-properties 1)))
3699 ;; FIXME: above we should remove the escapes.
3700 ;; but that requires another match, protecting match data,
3701 ;; a lot of overhead for font-lock.
3702 (ip (org-maybe-intangible
3703 (list 'invisible 'org-link 'rear-nonsticky org-nonsticky-props
3704 'keymap org-mouse-map 'mouse-face 'highlight
3705 'font-lock-multiline t 'help-echo help)))
3706 (vp (list 'rear-nonsticky org-nonsticky-props
3707 'keymap org-mouse-map 'mouse-face 'highlight
3708 ' font-lock-multiline t 'help-echo help)))
3709 ;; We need to remove the invisible property here. Table narrowing
3710 ;; may have made some of this invisible.
3711 (remove-text-properties (match-beginning 0) (match-end 0)
3712 '(invisible nil))
3713 (if (match-end 3)
3714 (progn
3715 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
3716 (add-text-properties (match-beginning 3) (match-end 3) vp)
3717 (add-text-properties (match-end 3) (match-end 0) ip))
3718 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
3719 (add-text-properties (match-beginning 1) (match-end 1) vp)
3720 (add-text-properties (match-end 1) (match-end 0) ip))
3721 t)))
3723 (defun org-activate-dates (limit)
3724 "Run through the buffer and add overlays to dates."
3725 (if (re-search-forward org-tsr-regexp-both limit t)
3726 (progn
3727 (add-text-properties (match-beginning 0) (match-end 0)
3728 (list 'mouse-face 'highlight
3729 'rear-nonsticky org-nonsticky-props
3730 'keymap org-mouse-map))
3731 (when org-display-custom-times
3732 (if (match-end 3)
3733 (org-display-custom-time (match-beginning 3) (match-end 3)))
3734 (org-display-custom-time (match-beginning 1) (match-end 1)))
3735 t)))
3737 (defvar org-target-link-regexp nil
3738 "Regular expression matching radio targets in plain text.")
3739 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
3740 "Regular expression matching a link target.")
3741 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
3742 "Regular expression matching a radio target.")
3743 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
3744 "Regular expression matching any target.")
3746 (defun org-activate-target-links (limit)
3747 "Run through the buffer and add overlays to target matches."
3748 (when org-target-link-regexp
3749 (let ((case-fold-search t))
3750 (if (re-search-forward org-target-link-regexp limit t)
3751 (progn
3752 (add-text-properties (match-beginning 0) (match-end 0)
3753 (list 'mouse-face 'highlight
3754 'rear-nonsticky org-nonsticky-props
3755 'keymap org-mouse-map
3756 'help-echo "Radio target link"
3757 'org-linked-text t))
3758 t)))))
3760 (defun org-update-radio-target-regexp ()
3761 "Find all radio targets in this file and update the regular expression."
3762 (interactive)
3763 (when (memq 'radio org-activate-links)
3764 (setq org-target-link-regexp
3765 (org-make-target-link-regexp (org-all-targets 'radio)))
3766 (org-restart-font-lock)))
3768 (defun org-hide-wide-columns (limit)
3769 (let (s e)
3770 (setq s (text-property-any (point) (or limit (point-max))
3771 'org-cwidth t))
3772 (when s
3773 (setq e (next-single-property-change s 'org-cwidth))
3774 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
3775 (goto-char e)
3776 t)))
3778 (defvar org-latex-and-specials-regexp nil
3779 "Regular expression for highlighting export special stuff.")
3780 (defvar org-match-substring-regexp)
3781 (defvar org-match-substring-with-braces-regexp)
3782 (defvar org-export-html-special-string-regexps)
3784 (defun org-compute-latex-and-specials-regexp ()
3785 "Compute regular expression for stuff treated specially by exporters."
3786 (if (not org-highlight-latex-fragments-and-specials)
3787 (org-set-local 'org-latex-and-specials-regexp nil)
3788 (require 'org-exp)
3789 (let*
3790 ((matchers (plist-get org-format-latex-options :matchers))
3791 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
3792 org-latex-regexps)))
3793 (options (org-combine-plists (org-default-export-plist)
3794 (org-infile-export-plist)))
3795 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
3796 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
3797 (org-export-with-TeX-macros (plist-get options :TeX-macros))
3798 (org-export-html-expand (plist-get options :expand-quoted-html))
3799 (org-export-with-special-strings (plist-get options :special-strings))
3800 (re-sub
3801 (cond
3802 ((equal org-export-with-sub-superscripts '{})
3803 (list org-match-substring-with-braces-regexp))
3804 (org-export-with-sub-superscripts
3805 (list org-match-substring-regexp))
3806 (t nil)))
3807 (re-latex
3808 (if org-export-with-LaTeX-fragments
3809 (mapcar (lambda (x) (nth 1 x)) latexs)))
3810 (re-macros
3811 (if org-export-with-TeX-macros
3812 (list (concat "\\\\"
3813 (regexp-opt
3814 (append (mapcar 'car org-html-entities)
3815 (if (boundp 'org-latex-entities)
3816 org-latex-entities nil))
3817 'words))) ; FIXME
3819 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
3820 (re-special (if org-export-with-special-strings
3821 (mapcar (lambda (x) (car x))
3822 org-export-html-special-string-regexps)))
3823 (re-rest
3824 (delq nil
3825 (list
3826 (if org-export-html-expand "@<[^>\n]+>")
3827 ))))
3828 (org-set-local
3829 'org-latex-and-specials-regexp
3830 (mapconcat 'identity (append re-latex re-sub re-macros re-special
3831 re-rest) "\\|")))))
3833 (defface org-latex-and-export-specials
3834 (let ((font (cond ((assq :inherit custom-face-attributes)
3835 '(:inherit underline))
3836 (t '(:underline t)))))
3837 `((((class grayscale) (background light))
3838 (:foreground "DimGray" ,@font))
3839 (((class grayscale) (background dark))
3840 (:foreground "LightGray" ,@font))
3841 (((class color) (background light))
3842 (:foreground "SaddleBrown"))
3843 (((class color) (background dark))
3844 (:foreground "burlywood"))
3845 (t (,@font))))
3846 "Face used to highlight math latex and other special exporter stuff."
3847 :group 'org-faces)
3849 (defun org-do-latex-and-special-faces (limit)
3850 "Run through the buffer and add overlays to links."
3851 (when org-latex-and-specials-regexp
3852 (let (rtn d)
3853 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
3854 limit t))
3855 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
3856 'face))
3857 '(org-code org-verbatim underline)))
3858 (progn
3859 (setq rtn t
3860 d (cond ((member (char-after (1+ (match-beginning 0)))
3861 '(?_ ?^)) 1)
3862 (t 0)))
3863 (font-lock-prepend-text-property
3864 (+ d (match-beginning 0)) (match-end 0)
3865 'face 'org-latex-and-export-specials)
3866 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
3867 '(font-lock-multiline t)))))
3868 rtn)))
3870 (defun org-restart-font-lock ()
3871 "Restart font-lock-mode, to force refontification."
3872 (when (and (boundp 'font-lock-mode) font-lock-mode)
3873 (font-lock-mode -1)
3874 (font-lock-mode 1)))
3876 (defun org-all-targets (&optional radio)
3877 "Return a list of all targets in this file.
3878 With optional argument RADIO, only find radio targets."
3879 (let ((re (if radio org-radio-target-regexp org-target-regexp))
3880 rtn)
3881 (save-excursion
3882 (goto-char (point-min))
3883 (while (re-search-forward re nil t)
3884 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
3885 rtn)))
3887 (defun org-make-target-link-regexp (targets)
3888 "Make regular expression matching all strings in TARGETS.
3889 The regular expression finds the targets also if there is a line break
3890 between words."
3891 (and targets
3892 (concat
3893 "\\<\\("
3894 (mapconcat
3895 (lambda (x)
3896 (while (string-match " +" x)
3897 (setq x (replace-match "\\s-+" t t x)))
3899 targets
3900 "\\|")
3901 "\\)\\>")))
3903 (defun org-activate-tags (limit)
3904 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \r\n]") limit t)
3905 (progn
3906 (add-text-properties (match-beginning 1) (match-end 1)
3907 (list 'mouse-face 'highlight
3908 'rear-nonsticky org-nonsticky-props
3909 'keymap org-mouse-map))
3910 t)))
3912 (defun org-outline-level ()
3913 (save-excursion
3914 (looking-at outline-regexp)
3915 (if (match-beginning 1)
3916 (+ (org-get-string-indentation (match-string 1)) 1000)
3917 (1- (- (match-end 0) (match-beginning 0))))))
3919 (defvar org-font-lock-keywords nil)
3921 (defconst org-property-re (org-re "^[ \t]*\\(:\\([[:alnum:]_]+\\):\\)[ \t]*\\(\\S-.*\\)")
3922 "Regular expression matching a property line.")
3924 (defun org-set-font-lock-defaults ()
3925 (let* ((em org-fontify-emphasized-text)
3926 (lk org-activate-links)
3927 (org-font-lock-extra-keywords
3928 (list
3929 ;; Headlines
3930 '("^\\(\\**\\)\\(\\* \\)\\(.*\\)" (1 (org-get-level-face 1))
3931 (2 (org-get-level-face 2)) (3 (org-get-level-face 3)))
3932 ;; Table lines
3933 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
3934 (1 'org-table t))
3935 ;; Table internals
3936 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
3937 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
3938 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
3939 ;; Drawers
3940 (list org-drawer-regexp '(0 'org-special-keyword t))
3941 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
3942 ;; Properties
3943 (list org-property-re
3944 '(1 'org-special-keyword t)
3945 '(3 'org-property-value t))
3946 (if org-format-transports-properties-p
3947 '("| *\\(<[0-9]+>\\) *" (1 'org-formula t)))
3948 ;; Links
3949 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
3950 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
3951 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
3952 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
3953 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
3954 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
3955 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
3956 '(org-hide-wide-columns (0 nil append))
3957 ;; TODO lines
3958 (list (concat "^\\*+[ \t]+" org-todo-regexp)
3959 '(1 (org-get-todo-face 1) t))
3960 ;; DONE
3961 (if org-fontify-done-headline
3962 (list (concat "^[*]+ +\\<\\("
3963 (mapconcat 'regexp-quote org-done-keywords "\\|")
3964 "\\)\\(.*\\)")
3965 '(2 'org-headline-done t))
3966 nil)
3967 ;; Priorities
3968 (list (concat "\\[#[A-Z0-9]\\]") '(0 'org-special-keyword t))
3969 ;; Special keywords
3970 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
3971 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
3972 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
3973 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
3974 ;; Emphasis
3975 (if em
3976 (if (featurep 'xemacs)
3977 '(org-do-emphasis-faces (0 nil append))
3978 '(org-do-emphasis-faces)))
3979 ;; Checkboxes
3980 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)"
3981 2 'bold prepend)
3982 (if org-provide-checkbox-statistics
3983 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
3984 (0 (org-get-checkbox-statistics-face) t)))
3985 (list (concat "^\\*+ \\(.*:" org-archive-tag ":.*\\)")
3986 '(1 'org-archived prepend))
3987 ;; Specials
3988 '(org-do-latex-and-special-faces)
3989 ;; Code
3990 '(org-activate-code (1 'org-code t))
3991 ;; COMMENT
3992 (list (concat "^\\*+[ \t]+\\<\\(" org-comment-string
3993 "\\|" org-quote-string "\\)\\>")
3994 '(1 'org-special-keyword t))
3995 '("^#.*" (0 'font-lock-comment-face t))
3997 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
3998 ;; Now set the full font-lock-keywords
3999 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
4000 (org-set-local 'font-lock-defaults
4001 '(org-font-lock-keywords t nil nil backward-paragraph))
4002 (kill-local-variable 'font-lock-keywords) nil))
4004 (defvar org-m nil)
4005 (defvar org-l nil)
4006 (defvar org-f nil)
4007 (defun org-get-level-face (n)
4008 "Get the right face for match N in font-lock matching of healdines."
4009 (setq org-l (- (match-end 2) (match-beginning 1) 1))
4010 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
4011 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
4012 (cond
4013 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
4014 ((eq n 2) org-f)
4015 (t (if org-level-color-stars-only nil org-f))))
4017 (defun org-get-todo-face (kwd)
4018 "Get the right face for a TODO keyword KWD.
4019 If KWD is a number, get the corresponding match group."
4020 (if (numberp kwd) (setq kwd (match-string kwd)))
4021 (or (cdr (assoc kwd org-todo-keyword-faces))
4022 (and (member kwd org-done-keywords) 'org-done)
4023 'org-todo))
4025 (defun org-unfontify-region (beg end &optional maybe_loudly)
4026 "Remove fontification and activation overlays from links."
4027 (font-lock-default-unfontify-region beg end)
4028 (let* ((buffer-undo-list t)
4029 (inhibit-read-only t) (inhibit-point-motion-hooks t)
4030 (inhibit-modification-hooks t)
4031 deactivate-mark buffer-file-name buffer-file-truename)
4032 (remove-text-properties beg end
4033 '(mouse-face t keymap t org-linked-text t
4034 invisible t intangible t))))
4036 ;;;; Visibility cycling, including org-goto and indirect buffer
4038 ;;; Cycling
4040 (defvar org-cycle-global-status nil)
4041 (make-variable-buffer-local 'org-cycle-global-status)
4042 (defvar org-cycle-subtree-status nil)
4043 (make-variable-buffer-local 'org-cycle-subtree-status)
4045 ;;;###autoload
4046 (defun org-cycle (&optional arg)
4047 "Visibility cycling for Org-mode.
4049 - When this function is called with a prefix argument, rotate the entire
4050 buffer through 3 states (global cycling)
4051 1. OVERVIEW: Show only top-level headlines.
4052 2. CONTENTS: Show all headlines of all levels, but no body text.
4053 3. SHOW ALL: Show everything.
4055 - When point is at the beginning of a headline, rotate the subtree started
4056 by this line through 3 different states (local cycling)
4057 1. FOLDED: Only the main headline is shown.
4058 2. CHILDREN: The main headline and the direct children are shown.
4059 From this state, you can move to one of the children
4060 and zoom in further.
4061 3. SUBTREE: Show the entire subtree, including body text.
4063 - When there is a numeric prefix, go up to a heading with level ARG, do
4064 a `show-subtree' and return to the previous cursor position. If ARG
4065 is negative, go up that many levels.
4067 - When point is not at the beginning of a headline, execute
4068 `indent-relative', like TAB normally does. See the option
4069 `org-cycle-emulate-tab' for details.
4071 - Special case: if point is at the beginning of the buffer and there is
4072 no headline in line 1, this function will act as if called with prefix arg.
4073 But only if also the variable `org-cycle-global-at-bob' is t."
4074 (interactive "P")
4075 (org-load-modules-maybe)
4076 (let* ((outline-regexp
4077 (if (and (org-mode-p) org-cycle-include-plain-lists)
4078 "\\(?:\\*+ \\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) \\)"
4079 outline-regexp))
4080 (bob-special (and org-cycle-global-at-bob (bobp)
4081 (not (looking-at outline-regexp))))
4082 (org-cycle-hook
4083 (if bob-special
4084 (delq 'org-optimize-window-after-visibility-change
4085 (copy-sequence org-cycle-hook))
4086 org-cycle-hook))
4087 (pos (point)))
4089 (if (or bob-special (equal arg '(4)))
4090 ;; special case: use global cycling
4091 (setq arg t))
4093 (cond
4095 ((org-at-table-p 'any)
4096 ;; Enter the table or move to the next field in the table
4097 (or (org-table-recognize-table.el)
4098 (progn
4099 (if arg (org-table-edit-field t)
4100 (org-table-justify-field-maybe)
4101 (call-interactively 'org-table-next-field)))))
4103 ((eq arg t) ;; Global cycling
4105 (cond
4106 ((and (eq last-command this-command)
4107 (eq org-cycle-global-status 'overview))
4108 ;; We just created the overview - now do table of contents
4109 ;; This can be slow in very large buffers, so indicate action
4110 (message "CONTENTS...")
4111 (org-content)
4112 (message "CONTENTS...done")
4113 (setq org-cycle-global-status 'contents)
4114 (run-hook-with-args 'org-cycle-hook 'contents))
4116 ((and (eq last-command this-command)
4117 (eq org-cycle-global-status 'contents))
4118 ;; We just showed the table of contents - now show everything
4119 (show-all)
4120 (message "SHOW ALL")
4121 (setq org-cycle-global-status 'all)
4122 (run-hook-with-args 'org-cycle-hook 'all))
4125 ;; Default action: go to overview
4126 (org-overview)
4127 (message "OVERVIEW")
4128 (setq org-cycle-global-status 'overview)
4129 (run-hook-with-args 'org-cycle-hook 'overview))))
4131 ((and org-drawers org-drawer-regexp
4132 (save-excursion
4133 (beginning-of-line 1)
4134 (looking-at org-drawer-regexp)))
4135 ;; Toggle block visibility
4136 (org-flag-drawer
4137 (not (get-char-property (match-end 0) 'invisible))))
4139 ((integerp arg)
4140 ;; Show-subtree, ARG levels up from here.
4141 (save-excursion
4142 (org-back-to-heading)
4143 (outline-up-heading (if (< arg 0) (- arg)
4144 (- (funcall outline-level) arg)))
4145 (org-show-subtree)))
4147 ((and (save-excursion (beginning-of-line 1) (looking-at outline-regexp))
4148 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
4149 ;; At a heading: rotate between three different views
4150 (org-back-to-heading)
4151 (let ((goal-column 0) eoh eol eos)
4152 ;; First, some boundaries
4153 (save-excursion
4154 (org-back-to-heading)
4155 (save-excursion
4156 (beginning-of-line 2)
4157 (while (and (not (eobp)) ;; this is like `next-line'
4158 (get-char-property (1- (point)) 'invisible))
4159 (beginning-of-line 2)) (setq eol (point)))
4160 (outline-end-of-heading) (setq eoh (point))
4161 (org-end-of-subtree t)
4162 (unless (eobp)
4163 (skip-chars-forward " \t\n")
4164 (beginning-of-line 1) ; in case this is an item
4166 (setq eos (1- (point))))
4167 ;; Find out what to do next and set `this-command'
4168 (cond
4169 ((= eos eoh)
4170 ;; Nothing is hidden behind this heading
4171 (message "EMPTY ENTRY")
4172 (setq org-cycle-subtree-status nil)
4173 (save-excursion
4174 (goto-char eos)
4175 (outline-next-heading)
4176 (if (org-invisible-p) (org-flag-heading nil))))
4177 ((or (>= eol eos)
4178 (not (string-match "\\S-" (buffer-substring eol eos))))
4179 ;; Entire subtree is hidden in one line: open it
4180 (org-show-entry)
4181 (show-children)
4182 (message "CHILDREN")
4183 (save-excursion
4184 (goto-char eos)
4185 (outline-next-heading)
4186 (if (org-invisible-p) (org-flag-heading nil)))
4187 (setq org-cycle-subtree-status 'children)
4188 (run-hook-with-args 'org-cycle-hook 'children))
4189 ((and (eq last-command this-command)
4190 (eq org-cycle-subtree-status 'children))
4191 ;; We just showed the children, now show everything.
4192 (org-show-subtree)
4193 (message "SUBTREE")
4194 (setq org-cycle-subtree-status 'subtree)
4195 (run-hook-with-args 'org-cycle-hook 'subtree))
4197 ;; Default action: hide the subtree.
4198 (hide-subtree)
4199 (message "FOLDED")
4200 (setq org-cycle-subtree-status 'folded)
4201 (run-hook-with-args 'org-cycle-hook 'folded)))))
4203 ;; TAB emulation
4204 (buffer-read-only (org-back-to-heading))
4206 ((org-try-cdlatex-tab))
4208 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
4209 (or (not (bolp))
4210 (not (looking-at outline-regexp))))
4211 (call-interactively (global-key-binding "\t")))
4213 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
4214 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
4215 (or (and (eq org-cycle-emulate-tab 'white)
4216 (= (match-end 0) (point-at-eol)))
4217 (and (eq org-cycle-emulate-tab 'whitestart)
4218 (>= (match-end 0) pos))))
4220 (eq org-cycle-emulate-tab t))
4221 (call-interactively (global-key-binding "\t")))
4223 (t (save-excursion
4224 (org-back-to-heading)
4225 (org-cycle))))))
4227 ;;;###autoload
4228 (defun org-global-cycle (&optional arg)
4229 "Cycle the global visibility. For details see `org-cycle'."
4230 (interactive "P")
4231 (let ((org-cycle-include-plain-lists
4232 (if (org-mode-p) org-cycle-include-plain-lists nil)))
4233 (if (integerp arg)
4234 (progn
4235 (show-all)
4236 (hide-sublevels arg)
4237 (setq org-cycle-global-status 'contents))
4238 (org-cycle '(4)))))
4240 (defun org-overview ()
4241 "Switch to overview mode, shoing only top-level headlines.
4242 Really, this shows all headlines with level equal or greater than the level
4243 of the first headline in the buffer. This is important, because if the
4244 first headline is not level one, then (hide-sublevels 1) gives confusing
4245 results."
4246 (interactive)
4247 (let ((level (save-excursion
4248 (goto-char (point-min))
4249 (if (re-search-forward (concat "^" outline-regexp) nil t)
4250 (progn
4251 (goto-char (match-beginning 0))
4252 (funcall outline-level))))))
4253 (and level (hide-sublevels level))))
4255 (defun org-content (&optional arg)
4256 "Show all headlines in the buffer, like a table of contents.
4257 With numerical argument N, show content up to level N."
4258 (interactive "P")
4259 (save-excursion
4260 ;; Visit all headings and show their offspring
4261 (and (integerp arg) (org-overview))
4262 (goto-char (point-max))
4263 (catch 'exit
4264 (while (and (progn (condition-case nil
4265 (outline-previous-visible-heading 1)
4266 (error (goto-char (point-min))))
4268 (looking-at outline-regexp))
4269 (if (integerp arg)
4270 (show-children (1- arg))
4271 (show-branches))
4272 (if (bobp) (throw 'exit nil))))))
4275 (defun org-optimize-window-after-visibility-change (state)
4276 "Adjust the window after a change in outline visibility.
4277 This function is the default value of the hook `org-cycle-hook'."
4278 (when (get-buffer-window (current-buffer))
4279 (cond
4280 ; ((eq state 'overview) (org-first-headline-recenter 1))
4281 ; ((eq state 'overview) (org-beginning-of-line))
4282 ((eq state 'content) nil)
4283 ((eq state 'all) nil)
4284 ((eq state 'folded) nil)
4285 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
4286 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
4288 (defun org-compact-display-after-subtree-move ()
4289 (let (beg end)
4290 (save-excursion
4291 (if (org-up-heading-safe)
4292 (progn
4293 (hide-subtree)
4294 (show-entry)
4295 (show-children)
4296 (org-cycle-show-empty-lines 'children)
4297 (org-cycle-hide-drawers 'children))
4298 (org-overview)))))
4300 (defun org-cycle-show-empty-lines (state)
4301 "Show empty lines above all visible headlines.
4302 The region to be covered depends on STATE when called through
4303 `org-cycle-hook'. Lisp program can use t for STATE to get the
4304 entire buffer covered. Note that an empty line is only shown if there
4305 are at least `org-cycle-separator-lines' empty lines before the headeline."
4306 (when (> org-cycle-separator-lines 0)
4307 (save-excursion
4308 (let* ((n org-cycle-separator-lines)
4309 (re (cond
4310 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
4311 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
4312 (t (let ((ns (number-to-string (- n 2))))
4313 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
4314 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
4315 beg end)
4316 (cond
4317 ((memq state '(overview contents t))
4318 (setq beg (point-min) end (point-max)))
4319 ((memq state '(children folded))
4320 (setq beg (point) end (progn (org-end-of-subtree t t)
4321 (beginning-of-line 2)
4322 (point)))))
4323 (when beg
4324 (goto-char beg)
4325 (while (re-search-forward re end t)
4326 (if (not (get-char-property (match-end 1) 'invisible))
4327 (outline-flag-region
4328 (match-beginning 1) (match-end 1) nil)))))))
4329 ;; Never hide empty lines at the end of the file.
4330 (save-excursion
4331 (goto-char (point-max))
4332 (outline-previous-heading)
4333 (outline-end-of-heading)
4334 (if (and (looking-at "[ \t\n]+")
4335 (= (match-end 0) (point-max)))
4336 (outline-flag-region (point) (match-end 0) nil))))
4338 (defun org-subtree-end-visible-p ()
4339 "Is the end of the current subtree visible?"
4340 (pos-visible-in-window-p
4341 (save-excursion (org-end-of-subtree t) (point))))
4343 (defun org-first-headline-recenter (&optional N)
4344 "Move cursor to the first headline and recenter the headline.
4345 Optional argument N means, put the headline into the Nth line of the window."
4346 (goto-char (point-min))
4347 (when (re-search-forward (concat "^\\(" outline-regexp "\\)") nil t)
4348 (beginning-of-line)
4349 (recenter (prefix-numeric-value N))))
4351 ;;; Org-goto
4353 (defvar org-goto-window-configuration nil)
4354 (defvar org-goto-marker nil)
4355 (defvar org-goto-map
4356 (let ((map (make-sparse-keymap)))
4357 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
4358 (while (setq cmd (pop cmds))
4359 (substitute-key-definition cmd cmd map global-map)))
4360 (suppress-keymap map)
4361 (org-defkey map "\C-m" 'org-goto-ret)
4362 (org-defkey map [(return)] 'org-goto-ret)
4363 (org-defkey map [(left)] 'org-goto-left)
4364 (org-defkey map [(right)] 'org-goto-right)
4365 (org-defkey map [(control ?g)] 'org-goto-quit)
4366 (org-defkey map "\C-i" 'org-cycle)
4367 (org-defkey map [(tab)] 'org-cycle)
4368 (org-defkey map [(down)] 'outline-next-visible-heading)
4369 (org-defkey map [(up)] 'outline-previous-visible-heading)
4370 (if org-goto-auto-isearch
4371 (if (fboundp 'define-key-after)
4372 (define-key-after map [t] 'org-goto-local-auto-isearch)
4373 nil)
4374 (org-defkey map "q" 'org-goto-quit)
4375 (org-defkey map "n" 'outline-next-visible-heading)
4376 (org-defkey map "p" 'outline-previous-visible-heading)
4377 (org-defkey map "f" 'outline-forward-same-level)
4378 (org-defkey map "b" 'outline-backward-same-level)
4379 (org-defkey map "u" 'outline-up-heading))
4380 (org-defkey map "/" 'org-occur)
4381 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
4382 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
4383 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
4384 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
4385 (org-defkey map "\C-c\C-u" 'outline-up-heading)
4386 map))
4388 (defconst org-goto-help
4389 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
4390 RET=jump to location [Q]uit and return to previous location
4391 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
4393 (defvar org-goto-start-pos) ; dynamically scoped parameter
4395 (defun org-goto (&optional alternative-interface)
4396 "Look up a different location in the current file, keeping current visibility.
4398 When you want look-up or go to a different location in a document, the
4399 fastest way is often to fold the entire buffer and then dive into the tree.
4400 This method has the disadvantage, that the previous location will be folded,
4401 which may not be what you want.
4403 This command works around this by showing a copy of the current buffer
4404 in an indirect buffer, in overview mode. You can dive into the tree in
4405 that copy, use org-occur and incremental search to find a location.
4406 When pressing RET or `Q', the command returns to the original buffer in
4407 which the visibility is still unchanged. After RET is will also jump to
4408 the location selected in the indirect buffer and expose the
4409 the headline hierarchy above."
4410 (interactive "P")
4411 (let* ((org-refile-targets '((nil . (:maxlevel . 10))))
4412 (org-refile-use-outline-path t)
4413 (interface
4414 (if (not alternative-interface)
4415 org-goto-interface
4416 (if (eq org-goto-interface 'outline)
4417 'outline-path-completion
4418 'outline)))
4419 (org-goto-start-pos (point))
4420 (selected-point
4421 (if (eq interface 'outline)
4422 (car (org-get-location (current-buffer) org-goto-help))
4423 (nth 3 (org-refile-get-location "Goto: ")))))
4424 (if selected-point
4425 (progn
4426 (org-mark-ring-push org-goto-start-pos)
4427 (goto-char selected-point)
4428 (if (or (org-invisible-p) (org-invisible-p2))
4429 (org-show-context 'org-goto)))
4430 (message "Quit"))))
4432 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
4433 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
4434 (defvar org-goto-local-auto-isearch-map) ; defined below
4436 (defun org-get-location (buf help)
4437 "Let the user select a location in the Org-mode buffer BUF.
4438 This function uses a recursive edit. It returns the selected position
4439 or nil."
4440 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
4441 (isearch-hide-immediately nil)
4442 (isearch-search-fun-function
4443 (lambda () 'org-goto-local-search-forward-headings))
4444 (org-goto-selected-point org-goto-exit-command))
4445 (save-excursion
4446 (save-window-excursion
4447 (delete-other-windows)
4448 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
4449 (switch-to-buffer
4450 (condition-case nil
4451 (make-indirect-buffer (current-buffer) "*org-goto*")
4452 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
4453 (with-output-to-temp-buffer "*Help*"
4454 (princ help))
4455 (shrink-window-if-larger-than-buffer (get-buffer-window "*Help*"))
4456 (setq buffer-read-only nil)
4457 (let ((org-startup-truncated t)
4458 (org-startup-folded nil)
4459 (org-startup-align-all-tables nil))
4460 (org-mode)
4461 (org-overview))
4462 (setq buffer-read-only t)
4463 (if (and (boundp 'org-goto-start-pos)
4464 (integer-or-marker-p org-goto-start-pos))
4465 (let ((org-show-hierarchy-above t)
4466 (org-show-siblings t)
4467 (org-show-following-heading t))
4468 (goto-char org-goto-start-pos)
4469 (and (org-invisible-p) (org-show-context)))
4470 (goto-char (point-min)))
4471 (org-beginning-of-line)
4472 (message "Select location and press RET")
4473 (use-local-map org-goto-map)
4474 (recursive-edit)
4476 (kill-buffer "*org-goto*")
4477 (cons org-goto-selected-point org-goto-exit-command)))
4479 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
4480 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
4481 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
4482 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
4484 (defun org-goto-local-search-forward-headings (string bound noerror)
4485 "Search and make sure that anu matches are in headlines."
4486 (catch 'return
4487 (while (search-forward string bound noerror)
4488 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
4489 (and (member :headline context)
4490 (not (member :tags context))))
4491 (throw 'return (point))))))
4493 (defun org-goto-local-auto-isearch ()
4494 "Start isearch."
4495 (interactive)
4496 (goto-char (point-min))
4497 (let ((keys (this-command-keys)))
4498 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
4499 (isearch-mode t)
4500 (isearch-process-search-char (string-to-char keys)))))
4502 (defun org-goto-ret (&optional arg)
4503 "Finish `org-goto' by going to the new location."
4504 (interactive "P")
4505 (setq org-goto-selected-point (point)
4506 org-goto-exit-command 'return)
4507 (throw 'exit nil))
4509 (defun org-goto-left ()
4510 "Finish `org-goto' by going to the new location."
4511 (interactive)
4512 (if (org-on-heading-p)
4513 (progn
4514 (beginning-of-line 1)
4515 (setq org-goto-selected-point (point)
4516 org-goto-exit-command 'left)
4517 (throw 'exit nil))
4518 (error "Not on a heading")))
4520 (defun org-goto-right ()
4521 "Finish `org-goto' by going to the new location."
4522 (interactive)
4523 (if (org-on-heading-p)
4524 (progn
4525 (setq org-goto-selected-point (point)
4526 org-goto-exit-command 'right)
4527 (throw 'exit nil))
4528 (error "Not on a heading")))
4530 (defun org-goto-quit ()
4531 "Finish `org-goto' without cursor motion."
4532 (interactive)
4533 (setq org-goto-selected-point nil)
4534 (setq org-goto-exit-command 'quit)
4535 (throw 'exit nil))
4537 ;;; Indirect buffer display of subtrees
4539 (defvar org-indirect-dedicated-frame nil
4540 "This is the frame being used for indirect tree display.")
4541 (defvar org-last-indirect-buffer nil)
4543 (defun org-tree-to-indirect-buffer (&optional arg)
4544 "Create indirect buffer and narrow it to current subtree.
4545 With numerical prefix ARG, go up to this level and then take that tree.
4546 If ARG is negative, go up that many levels.
4547 If `org-indirect-buffer-display' is not `new-frame', the command removes the
4548 indirect buffer previously made with this command, to avoid proliferation of
4549 indirect buffers. However, when you call the command with a `C-u' prefix, or
4550 when `org-indirect-buffer-display' is `new-frame', the last buffer
4551 is kept so that you can work with several indirect buffers at the same time.
4552 If `org-indirect-buffer-display' is `dedicated-frame', the C-u prefix also
4553 requests that a new frame be made for the new buffer, so that the dedicated
4554 frame is not changed."
4555 (interactive "P")
4556 (let ((cbuf (current-buffer))
4557 (cwin (selected-window))
4558 (pos (point))
4559 beg end level heading ibuf)
4560 (save-excursion
4561 (org-back-to-heading t)
4562 (when (numberp arg)
4563 (setq level (org-outline-level))
4564 (if (< arg 0) (setq arg (+ level arg)))
4565 (while (> (setq level (org-outline-level)) arg)
4566 (outline-up-heading 1 t)))
4567 (setq beg (point)
4568 heading (org-get-heading))
4569 (org-end-of-subtree t) (setq end (point)))
4570 (if (and (buffer-live-p org-last-indirect-buffer)
4571 (not (eq org-indirect-buffer-display 'new-frame))
4572 (not arg))
4573 (kill-buffer org-last-indirect-buffer))
4574 (setq ibuf (org-get-indirect-buffer cbuf)
4575 org-last-indirect-buffer ibuf)
4576 (cond
4577 ((or (eq org-indirect-buffer-display 'new-frame)
4578 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
4579 (select-frame (make-frame))
4580 (delete-other-windows)
4581 (switch-to-buffer ibuf)
4582 (org-set-frame-title heading))
4583 ((eq org-indirect-buffer-display 'dedicated-frame)
4584 (raise-frame
4585 (select-frame (or (and org-indirect-dedicated-frame
4586 (frame-live-p org-indirect-dedicated-frame)
4587 org-indirect-dedicated-frame)
4588 (setq org-indirect-dedicated-frame (make-frame)))))
4589 (delete-other-windows)
4590 (switch-to-buffer ibuf)
4591 (org-set-frame-title (concat "Indirect: " heading)))
4592 ((eq org-indirect-buffer-display 'current-window)
4593 (switch-to-buffer ibuf))
4594 ((eq org-indirect-buffer-display 'other-window)
4595 (pop-to-buffer ibuf))
4596 (t (error "Invalid value.")))
4597 (if (featurep 'xemacs)
4598 (save-excursion (org-mode) (turn-on-font-lock)))
4599 (narrow-to-region beg end)
4600 (show-all)
4601 (goto-char pos)
4602 (and (window-live-p cwin) (select-window cwin))))
4604 (defun org-get-indirect-buffer (&optional buffer)
4605 (setq buffer (or buffer (current-buffer)))
4606 (let ((n 1) (base (buffer-name buffer)) bname)
4607 (while (buffer-live-p
4608 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
4609 (setq n (1+ n)))
4610 (condition-case nil
4611 (make-indirect-buffer buffer bname 'clone)
4612 (error (make-indirect-buffer buffer bname)))))
4614 (defun org-set-frame-title (title)
4615 "Set the title of the current frame to the string TITLE."
4616 ;; FIXME: how to name a single frame in XEmacs???
4617 (unless (featurep 'xemacs)
4618 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
4620 ;;;; Structure editing
4622 ;;; Inserting headlines
4624 (defun org-insert-heading (&optional force-heading)
4625 "Insert a new heading or item with same depth at point.
4626 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
4627 If point is at the beginning of a headline, insert a sibling before the
4628 current headline. If point is not at the beginning, do not split the line,
4629 but create the new hedline after the current line."
4630 (interactive "P")
4631 (if (= (buffer-size) 0)
4632 (insert "\n* ")
4633 (when (or force-heading (not (org-insert-item)))
4634 (let* ((head (save-excursion
4635 (condition-case nil
4636 (progn
4637 (org-back-to-heading)
4638 (match-string 0))
4639 (error "*"))))
4640 (blank (cdr (assq 'heading org-blank-before-new-entry)))
4641 pos)
4642 (cond
4643 ((and (org-on-heading-p) (bolp)
4644 (or (bobp)
4645 (save-excursion (backward-char 1) (not (org-invisible-p)))))
4646 ;; insert before the current line
4647 (open-line (if blank 2 1)))
4648 ((and (bolp)
4649 (or (bobp)
4650 (save-excursion
4651 (backward-char 1) (not (org-invisible-p)))))
4652 ;; insert right here
4653 nil)
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-get-heading (&optional no-tags)
4685 "Return the heading of the current entry, without the stars."
4686 (save-excursion
4687 (org-back-to-heading t)
4688 (if (looking-at
4689 (if no-tags
4690 (org-re "\\*+[ \t]+\\([^\n\r]*?\\)\\([ \t]+:[[:alnum:]:_@]+:[ \t]*\\)?$")
4691 "\\*+[ \t]+\\([^\r\n]*\\)"))
4692 (match-string 1) "")))
4694 (defun org-insert-heading-after-current ()
4695 "Insert a new heading with same level as current, after current subtree."
4696 (interactive)
4697 (org-back-to-heading)
4698 (org-insert-heading)
4699 (org-move-subtree-down)
4700 (end-of-line 1))
4702 (defun org-insert-todo-heading (arg)
4703 "Insert a new heading with the same level and TODO state as current heading.
4704 If the heading has no TODO state, or if the state is DONE, use the first
4705 state (TODO by default). Also with prefix arg, force first state."
4706 (interactive "P")
4707 (when (not (org-insert-item 'checkbox))
4708 (org-insert-heading)
4709 (save-excursion
4710 (org-back-to-heading)
4711 (outline-previous-heading)
4712 (looking-at org-todo-line-regexp))
4713 (if (or arg
4714 (not (match-beginning 2))
4715 (member (match-string 2) org-done-keywords))
4716 (insert (car org-todo-keywords-1) " ")
4717 (insert (match-string 2) " "))))
4719 (defun org-insert-subheading (arg)
4720 "Insert a new subheading and demote it.
4721 Works for outline headings and for plain lists alike."
4722 (interactive "P")
4723 (org-insert-heading arg)
4724 (cond
4725 ((org-on-heading-p) (org-do-demote))
4726 ((org-at-item-p) (org-indent-item 1))))
4728 (defun org-insert-todo-subheading (arg)
4729 "Insert a new subheading with TODO keyword or checkbox and demote it.
4730 Works for outline headings and for plain lists alike."
4731 (interactive "P")
4732 (org-insert-todo-heading arg)
4733 (cond
4734 ((org-on-heading-p) (org-do-demote))
4735 ((org-at-item-p) (org-indent-item 1))))
4737 ;;; Promotion and Demotion
4739 (defun org-promote-subtree ()
4740 "Promote the entire subtree.
4741 See also `org-promote'."
4742 (interactive)
4743 (save-excursion
4744 (org-map-tree 'org-promote))
4745 (org-fix-position-after-promote))
4747 (defun org-demote-subtree ()
4748 "Demote the entire subtree. See `org-demote'.
4749 See also `org-promote'."
4750 (interactive)
4751 (save-excursion
4752 (org-map-tree 'org-demote))
4753 (org-fix-position-after-promote))
4756 (defun org-do-promote ()
4757 "Promote the current heading higher up the tree.
4758 If the region is active in `transient-mark-mode', promote all headings
4759 in the region."
4760 (interactive)
4761 (save-excursion
4762 (if (org-region-active-p)
4763 (org-map-region 'org-promote (region-beginning) (region-end))
4764 (org-promote)))
4765 (org-fix-position-after-promote))
4767 (defun org-do-demote ()
4768 "Demote the current heading lower down the tree.
4769 If the region is active in `transient-mark-mode', demote all headings
4770 in the region."
4771 (interactive)
4772 (save-excursion
4773 (if (org-region-active-p)
4774 (org-map-region 'org-demote (region-beginning) (region-end))
4775 (org-demote)))
4776 (org-fix-position-after-promote))
4778 (defun org-fix-position-after-promote ()
4779 "Make sure that after pro/demotion cursor position is right."
4780 (let ((pos (point)))
4781 (when (save-excursion
4782 (beginning-of-line 1)
4783 (looking-at org-todo-line-regexp)
4784 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
4785 (cond ((eobp) (insert " "))
4786 ((eolp) (insert " "))
4787 ((equal (char-after) ?\ ) (forward-char 1))))))
4789 (defun org-reduced-level (l)
4790 (if org-odd-levels-only (1+ (floor (/ l 2))) l))
4792 (defun org-get-valid-level (level &optional change)
4793 "Rectify a level change under the influence of `org-odd-levels-only'
4794 LEVEL is a current level, CHANGE is by how much the level should be
4795 modified. Even if CHANGE is nil, LEVEL may be returned modified because
4796 even level numbers will become the next higher odd number."
4797 (if org-odd-levels-only
4798 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
4799 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
4800 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
4801 (max 1 (+ level change))))
4803 (if (boundp 'define-obsolete-function-alias)
4804 (if (or (featurep 'xemacs) (< emacs-major-version 23))
4805 (define-obsolete-function-alias 'org-get-legal-level
4806 'org-get-valid-level)
4807 (define-obsolete-function-alias 'org-get-legal-level
4808 'org-get-valid-level "23.1")))
4810 (defun org-promote ()
4811 "Promote the current heading higher up the tree.
4812 If the region is active in `transient-mark-mode', promote all headings
4813 in the region."
4814 (org-back-to-heading t)
4815 (let* ((level (save-match-data (funcall outline-level)))
4816 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
4817 (diff (abs (- level (length up-head) -1))))
4818 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
4819 (replace-match up-head nil t)
4820 ;; Fixup tag positioning
4821 (and org-auto-align-tags (org-set-tags nil t))
4822 (if org-adapt-indentation (org-fixup-indentation (- diff)))))
4824 (defun org-demote ()
4825 "Demote the current heading lower down the tree.
4826 If the region is active in `transient-mark-mode', demote all headings
4827 in the region."
4828 (org-back-to-heading t)
4829 (let* ((level (save-match-data (funcall outline-level)))
4830 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
4831 (diff (abs (- level (length down-head) -1))))
4832 (replace-match down-head nil t)
4833 ;; Fixup tag positioning
4834 (and org-auto-align-tags (org-set-tags nil t))
4835 (if org-adapt-indentation (org-fixup-indentation diff))))
4837 (defun org-map-tree (fun)
4838 "Call FUN for every heading underneath the current one."
4839 (org-back-to-heading)
4840 (let ((level (funcall outline-level)))
4841 (save-excursion
4842 (funcall fun)
4843 (while (and (progn
4844 (outline-next-heading)
4845 (> (funcall outline-level) level))
4846 (not (eobp)))
4847 (funcall fun)))))
4849 (defun org-map-region (fun beg end)
4850 "Call FUN for every heading between BEG and END."
4851 (let ((org-ignore-region t))
4852 (save-excursion
4853 (setq end (copy-marker end))
4854 (goto-char beg)
4855 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
4856 (< (point) end))
4857 (funcall fun))
4858 (while (and (progn
4859 (outline-next-heading)
4860 (< (point) end))
4861 (not (eobp)))
4862 (funcall fun)))))
4864 (defun org-fixup-indentation (diff)
4865 "Change the indentation in the current entry by DIFF
4866 However, if any line in the current entry has no indentation, or if it
4867 would end up with no indentation after the change, nothing at all is done."
4868 (save-excursion
4869 (let ((end (save-excursion (outline-next-heading)
4870 (point-marker)))
4871 (prohibit (if (> diff 0)
4872 "^\\S-"
4873 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
4874 col)
4875 (unless (save-excursion (end-of-line 1)
4876 (re-search-forward prohibit end t))
4877 (while (and (< (point) end)
4878 (re-search-forward "^[ \t]+" end t))
4879 (goto-char (match-end 0))
4880 (setq col (current-column))
4881 (if (< diff 0) (replace-match ""))
4882 (indent-to (+ diff col))))
4883 (move-marker end nil))))
4885 (defun org-convert-to-odd-levels ()
4886 "Convert an org-mode file with all levels allowed to one with odd levels.
4887 This will leave level 1 alone, convert level 2 to level 3, level 3 to
4888 level 5 etc."
4889 (interactive)
4890 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
4891 (let ((org-odd-levels-only nil) n)
4892 (save-excursion
4893 (goto-char (point-min))
4894 (while (re-search-forward "^\\*\\*+ " nil t)
4895 (setq n (- (length (match-string 0)) 2))
4896 (while (>= (setq n (1- n)) 0)
4897 (org-demote))
4898 (end-of-line 1))))))
4901 (defun org-convert-to-oddeven-levels ()
4902 "Convert an org-mode file with only odd levels to one with odd and even levels.
4903 This promotes level 3 to level 2, level 5 to level 3 etc. If the file contains a
4904 section with an even level, conversion would destroy the structure of the file. An error
4905 is signaled in this case."
4906 (interactive)
4907 (goto-char (point-min))
4908 ;; First check if there are no even levels
4909 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
4910 (org-show-context t)
4911 (error "Not all levels are odd in this file. Conversion not possible."))
4912 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
4913 (let ((org-odd-levels-only nil) n)
4914 (save-excursion
4915 (goto-char (point-min))
4916 (while (re-search-forward "^\\*\\*+ " nil t)
4917 (setq n (/ (1- (length (match-string 0))) 2))
4918 (while (>= (setq n (1- n)) 0)
4919 (org-promote))
4920 (end-of-line 1))))))
4922 (defun org-tr-level (n)
4923 "Make N odd if required."
4924 (if org-odd-levels-only (1+ (/ n 2)) n))
4926 ;;; Vertical tree motion, cutting and pasting of subtrees
4928 (defun org-move-subtree-up (&optional arg)
4929 "Move the current subtree up past ARG headlines of the same level."
4930 (interactive "p")
4931 (org-move-subtree-down (- (prefix-numeric-value arg))))
4933 (defun org-move-subtree-down (&optional arg)
4934 "Move the current subtree down past ARG headlines of the same level."
4935 (interactive "p")
4936 (setq arg (prefix-numeric-value arg))
4937 (let ((movfunc (if (> arg 0) 'outline-get-next-sibling
4938 'outline-get-last-sibling))
4939 (ins-point (make-marker))
4940 (cnt (abs arg))
4941 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
4942 ;; Select the tree
4943 (org-back-to-heading)
4944 (setq beg0 (point))
4945 (save-excursion
4946 (setq ne-beg (org-back-over-empty-lines))
4947 (setq beg (point)))
4948 (save-match-data
4949 (save-excursion (outline-end-of-heading)
4950 (setq folded (org-invisible-p)))
4951 (outline-end-of-subtree))
4952 (outline-next-heading)
4953 (setq ne-end (org-back-over-empty-lines))
4954 (setq end (point))
4955 (goto-char beg0)
4956 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
4957 ;; include less whitespace
4958 (save-excursion
4959 (goto-char beg)
4960 (forward-line (- ne-beg ne-end))
4961 (setq beg (point))))
4962 ;; Find insertion point, with error handling
4963 (while (> cnt 0)
4964 (or (and (funcall movfunc) (looking-at outline-regexp))
4965 (progn (goto-char beg0)
4966 (error "Cannot move past superior level or buffer limit")))
4967 (setq cnt (1- cnt)))
4968 (if (> arg 0)
4969 ;; Moving forward - still need to move over subtree
4970 (progn (org-end-of-subtree t t)
4971 (save-excursion
4972 (org-back-over-empty-lines)
4973 (or (bolp) (newline)))))
4974 (setq ne-ins (org-back-over-empty-lines))
4975 (move-marker ins-point (point))
4976 (setq txt (buffer-substring beg end))
4977 (delete-region beg end)
4978 (outline-flag-region (1- beg) beg nil)
4979 (outline-flag-region (1- (point)) (point) nil)
4980 (insert txt)
4981 (or (bolp) (insert "\n"))
4982 (setq ins-end (point))
4983 (goto-char ins-point)
4984 (org-skip-whitespace)
4985 (when (and (< arg 0)
4986 (org-first-sibling-p)
4987 (> ne-ins ne-beg))
4988 ;; Move whitespace back to beginning
4989 (save-excursion
4990 (goto-char ins-end)
4991 (let ((kill-whole-line t))
4992 (kill-line (- ne-ins ne-beg)) (point)))
4993 (insert (make-string (- ne-ins ne-beg) ?\n)))
4994 (move-marker ins-point nil)
4995 (org-compact-display-after-subtree-move)
4996 (unless folded
4997 (org-show-entry)
4998 (show-children)
4999 (org-cycle-hide-drawers 'children))))
5001 (defvar org-subtree-clip ""
5002 "Clipboard for cut and paste of subtrees.
5003 This is actually only a copy of the kill, because we use the normal kill
5004 ring. We need it to check if the kill was created by `org-copy-subtree'.")
5006 (defvar org-subtree-clip-folded nil
5007 "Was the last copied subtree folded?
5008 This is used to fold the tree back after pasting.")
5010 (defun org-cut-subtree (&optional n)
5011 "Cut the current subtree into the clipboard.
5012 With prefix arg N, cut this many sequential subtrees.
5013 This is a short-hand for marking the subtree and then cutting it."
5014 (interactive "p")
5015 (org-copy-subtree n 'cut))
5017 (defun org-copy-subtree (&optional n cut)
5018 "Cut the current subtree into the clipboard.
5019 With prefix arg N, cut this many sequential subtrees.
5020 This is a short-hand for marking the subtree and then copying it.
5021 If CUT is non-nil, actually cut the subtree."
5022 (interactive "p")
5023 (let (beg end folded (beg0 (point)))
5024 (if (interactive-p)
5025 (org-back-to-heading nil) ; take what looks like a subtree
5026 (org-back-to-heading t)) ; take what is really there
5027 (org-back-over-empty-lines)
5028 (setq beg (point))
5029 (skip-chars-forward " \t\r\n")
5030 (save-match-data
5031 (save-excursion (outline-end-of-heading)
5032 (setq folded (org-invisible-p)))
5033 (condition-case nil
5034 (outline-forward-same-level (1- n))
5035 (error nil))
5036 (org-end-of-subtree t t))
5037 (org-back-over-empty-lines)
5038 (setq end (point))
5039 (goto-char beg0)
5040 (when (> end beg)
5041 (setq org-subtree-clip-folded folded)
5042 (if cut (kill-region beg end) (copy-region-as-kill beg end))
5043 (setq org-subtree-clip (current-kill 0))
5044 (message "%s: Subtree(s) with %d characters"
5045 (if cut "Cut" "Copied")
5046 (length org-subtree-clip)))))
5048 (defun org-paste-subtree (&optional level tree)
5049 "Paste the clipboard as a subtree, with modification of headline level.
5050 The entire subtree is promoted or demoted in order to match a new headline
5051 level. By default, the new level is derived from the visible headings
5052 before and after the insertion point, and taken to be the inferior headline
5053 level of the two. So if the previous visible heading is level 3 and the
5054 next is level 4 (or vice versa), level 4 will be used for insertion.
5055 This makes sure that the subtree remains an independent subtree and does
5056 not swallow low level entries.
5058 You can also force a different level, either by using a numeric prefix
5059 argument, or by inserting the heading marker by hand. For example, if the
5060 cursor is after \"*****\", then the tree will be shifted to level 5.
5062 If you want to insert the tree as is, just use \\[yank].
5064 If optional TREE is given, use this text instead of the kill ring."
5065 (interactive "P")
5066 (unless (org-kill-is-subtree-p tree)
5067 (error "%s"
5068 (substitute-command-keys
5069 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
5070 (let* ((txt (or tree (and kill-ring (current-kill 0))))
5071 (^re (concat "^\\(" outline-regexp "\\)"))
5072 (re (concat "\\(" outline-regexp "\\)"))
5073 (^re_ (concat "\\(\\*+\\)[ \t]*"))
5075 (old-level (if (string-match ^re txt)
5076 (- (match-end 0) (match-beginning 0) 1)
5077 -1))
5078 (force-level (cond (level (prefix-numeric-value level))
5079 ((string-match
5080 ^re_ (buffer-substring (point-at-bol) (point)))
5081 (- (match-end 1) (match-beginning 1)))
5082 (t nil)))
5083 (previous-level (save-excursion
5084 (condition-case nil
5085 (progn
5086 (outline-previous-visible-heading 1)
5087 (if (looking-at re)
5088 (- (match-end 0) (match-beginning 0) 1)
5090 (error 1))))
5091 (next-level (save-excursion
5092 (condition-case nil
5093 (progn
5094 (or (looking-at outline-regexp)
5095 (outline-next-visible-heading 1))
5096 (if (looking-at re)
5097 (- (match-end 0) (match-beginning 0) 1)
5099 (error 1))))
5100 (new-level (or force-level (max previous-level next-level)))
5101 (shift (if (or (= old-level -1)
5102 (= new-level -1)
5103 (= old-level new-level))
5105 (- new-level old-level)))
5106 (delta (if (> shift 0) -1 1))
5107 (func (if (> shift 0) 'org-demote 'org-promote))
5108 (org-odd-levels-only nil)
5109 beg end)
5110 ;; Remove the forced level indicator
5111 (if force-level
5112 (delete-region (point-at-bol) (point)))
5113 ;; Paste
5114 (beginning-of-line 1)
5115 (org-back-over-empty-lines)
5116 (setq beg (point))
5117 (insert-before-markers txt)
5118 (unless (string-match "\n\\'" txt) (insert "\n"))
5119 (setq end (point))
5120 (goto-char beg)
5121 (skip-chars-forward " \t\n\r")
5122 (setq beg (point))
5123 ;; Shift if necessary
5124 (unless (= shift 0)
5125 (save-restriction
5126 (narrow-to-region beg end)
5127 (while (not (= shift 0))
5128 (org-map-region func (point-min) (point-max))
5129 (setq shift (+ delta shift)))
5130 (goto-char (point-min))))
5131 (when (interactive-p)
5132 (message "Clipboard pasted as level %d subtree" new-level))
5133 (if (and kill-ring
5134 (eq org-subtree-clip (current-kill 0))
5135 org-subtree-clip-folded)
5136 ;; The tree was folded before it was killed/copied
5137 (hide-subtree))))
5139 (defun org-kill-is-subtree-p (&optional txt)
5140 "Check if the current kill is an outline subtree, or a set of trees.
5141 Returns nil if kill does not start with a headline, or if the first
5142 headline level is not the largest headline level in the tree.
5143 So this will actually accept several entries of equal levels as well,
5144 which is OK for `org-paste-subtree'.
5145 If optional TXT is given, check this string instead of the current kill."
5146 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
5147 (start-level (and kill
5148 (string-match (concat "\\`\\([ \t\n\r]*?\n\\)?\\("
5149 org-outline-regexp "\\)")
5150 kill)
5151 (- (match-end 2) (match-beginning 2) 1)))
5152 (re (concat "^" org-outline-regexp))
5153 (start (1+ (match-beginning 2))))
5154 (if (not start-level)
5155 (progn
5156 nil) ;; does not even start with a heading
5157 (catch 'exit
5158 (while (setq start (string-match re kill (1+ start)))
5159 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
5160 (throw 'exit nil)))
5161 t))))
5163 (defun org-narrow-to-subtree ()
5164 "Narrow buffer to the current subtree."
5165 (interactive)
5166 (save-excursion
5167 (save-match-data
5168 (narrow-to-region
5169 (progn (org-back-to-heading) (point))
5170 (progn (org-end-of-subtree t t) (point))))))
5173 ;;; Outline Sorting
5175 (defun org-sort (with-case)
5176 "Call `org-sort-entries-or-items' or `org-table-sort-lines'.
5177 Optional argument WITH-CASE means sort case-sensitively."
5178 (interactive "P")
5179 (if (org-at-table-p)
5180 (org-call-with-arg 'org-table-sort-lines with-case)
5181 (org-call-with-arg 'org-sort-entries-or-items with-case)))
5183 (defun org-sort-remove-invisible (s)
5184 (remove-text-properties 0 (length s) org-rm-props s)
5185 (while (string-match org-bracket-link-regexp s)
5186 (setq s (replace-match (if (match-end 2)
5187 (match-string 3 s)
5188 (match-string 1 s)) t t s)))
5191 (defvar org-priority-regexp) ; defined later in the file
5193 (defun org-sort-entries-or-items (&optional with-case sorting-type getkey-func property)
5194 "Sort entries on a certain level of an outline tree.
5195 If there is an active region, the entries in the region are sorted.
5196 Else, if the cursor is before the first entry, sort the top-level items.
5197 Else, the children of the entry at point are sorted.
5199 Sorting can be alphabetically, numerically, and by date/time as given by
5200 the first time stamp in the entry. The command prompts for the sorting
5201 type unless it has been given to the function through the SORTING-TYPE
5202 argument, which needs to a character, any of (?n ?N ?a ?A ?t ?T ?p ?P ?f ?F).
5203 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
5204 called with point at the beginning of the record. It must return either
5205 a string or a number that should serve as the sorting key for that record.
5207 Comparing entries ignores case by default. However, with an optional argument
5208 WITH-CASE, the sorting considers case as well."
5209 (interactive "P")
5210 (let ((case-func (if with-case 'identity 'downcase))
5211 start beg end stars re re2
5212 txt what tmp plain-list-p)
5213 ;; Find beginning and end of region to sort
5214 (cond
5215 ((org-region-active-p)
5216 ;; we will sort the region
5217 (setq end (region-end)
5218 what "region")
5219 (goto-char (region-beginning))
5220 (if (not (org-on-heading-p)) (outline-next-heading))
5221 (setq start (point)))
5222 ((org-at-item-p)
5223 ;; we will sort this plain list
5224 (org-beginning-of-item-list) (setq start (point))
5225 (org-end-of-item-list) (setq end (point))
5226 (goto-char start)
5227 (setq plain-list-p t
5228 what "plain list"))
5229 ((or (org-on-heading-p)
5230 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
5231 ;; we will sort the children of the current headline
5232 (org-back-to-heading)
5233 (setq start (point)
5234 end (progn (org-end-of-subtree t t)
5235 (org-back-over-empty-lines)
5236 (point))
5237 what "children")
5238 (goto-char start)
5239 (show-subtree)
5240 (outline-next-heading))
5242 ;; we will sort the top-level entries in this file
5243 (goto-char (point-min))
5244 (or (org-on-heading-p) (outline-next-heading))
5245 (setq start (point) end (point-max) what "top-level")
5246 (goto-char start)
5247 (show-all)))
5249 (setq beg (point))
5250 (if (>= beg end) (error "Nothing to sort"))
5252 (unless plain-list-p
5253 (looking-at "\\(\\*+\\)")
5254 (setq stars (match-string 1)
5255 re (concat "^" (regexp-quote stars) " +")
5256 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[^*]")
5257 txt (buffer-substring beg end))
5258 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
5259 (if (and (not (equal stars "*")) (string-match re2 txt))
5260 (error "Region to sort contains a level above the first entry")))
5262 (unless sorting-type
5263 (message
5264 (if plain-list-p
5265 "Sort %s: [a]lpha [n]umeric [t]ime [f]unc A/N/T/F means reversed:"
5266 "Sort %s: [a]lpha [n]umeric [t]ime [p]riority p[r]operty [f]unc A/N/T/P/F means reversed:")
5267 what)
5268 (setq sorting-type (read-char-exclusive))
5270 (and (= (downcase sorting-type) ?f)
5271 (setq getkey-func
5272 (completing-read "Sort using function: "
5273 obarray 'fboundp t nil nil))
5274 (setq getkey-func (intern getkey-func)))
5276 (and (= (downcase sorting-type) ?r)
5277 (setq property
5278 (completing-read "Property: "
5279 (mapcar 'list (org-buffer-property-keys t))
5280 nil t))))
5282 (message "Sorting entries...")
5284 (save-restriction
5285 (narrow-to-region start end)
5287 (let ((dcst (downcase sorting-type))
5288 (now (current-time)))
5289 (sort-subr
5290 (/= dcst sorting-type)
5291 ;; This function moves to the beginning character of the "record" to
5292 ;; be sorted.
5293 (if plain-list-p
5294 (lambda nil
5295 (if (org-at-item-p) t (goto-char (point-max))))
5296 (lambda nil
5297 (if (re-search-forward re nil t)
5298 (goto-char (match-beginning 0))
5299 (goto-char (point-max)))))
5300 ;; This function moves to the last character of the "record" being
5301 ;; sorted.
5302 (if plain-list-p
5303 'org-end-of-item
5304 (lambda nil
5305 (save-match-data
5306 (condition-case nil
5307 (outline-forward-same-level 1)
5308 (error
5309 (goto-char (point-max)))))))
5311 ;; This function returns the value that gets sorted against.
5312 (if plain-list-p
5313 (lambda nil
5314 (when (looking-at "[ \t]*[-+*0-9.)]+[ \t]+")
5315 (cond
5316 ((= dcst ?n)
5317 (string-to-number (buffer-substring (match-end 0)
5318 (point-at-eol))))
5319 ((= dcst ?a)
5320 (buffer-substring (match-end 0) (point-at-eol)))
5321 ((= dcst ?t)
5322 (if (re-search-forward org-ts-regexp
5323 (point-at-eol) t)
5324 (org-time-string-to-time (match-string 0))
5325 now))
5326 ((= dcst ?f)
5327 (if getkey-func
5328 (progn
5329 (setq tmp (funcall getkey-func))
5330 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
5331 tmp)
5332 (error "Invalid key function `%s'" getkey-func)))
5333 (t (error "Invalid sorting type `%c'" sorting-type)))))
5334 (lambda nil
5335 (cond
5336 ((= dcst ?n)
5337 (if (looking-at outline-regexp)
5338 (string-to-number (buffer-substring (match-end 0)
5339 (point-at-eol)))
5340 nil))
5341 ((= dcst ?a)
5342 (funcall case-func (buffer-substring (point-at-bol)
5343 (point-at-eol))))
5344 ((= dcst ?t)
5345 (if (re-search-forward org-ts-regexp
5346 (save-excursion
5347 (forward-line 2)
5348 (point)) t)
5349 (org-time-string-to-time (match-string 0))
5350 now))
5351 ((= dcst ?p)
5352 (if (re-search-forward org-priority-regexp (point-at-eol) t)
5353 (string-to-char (match-string 2))
5354 org-default-priority))
5355 ((= dcst ?r)
5356 (or (org-entry-get nil property) ""))
5357 ((= dcst ?f)
5358 (if getkey-func
5359 (progn
5360 (setq tmp (funcall getkey-func))
5361 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
5362 tmp)
5363 (error "Invalid key function `%s'" getkey-func)))
5364 (t (error "Invalid sorting type `%c'" sorting-type)))))
5366 (cond
5367 ((= dcst ?a) 'string<)
5368 ((= dcst ?t) 'time-less-p)
5369 (t nil)))))
5370 (message "Sorting entries...done")))
5372 (defun org-do-sort (table what &optional with-case sorting-type)
5373 "Sort TABLE of WHAT according to SORTING-TYPE.
5374 The user will be prompted for the SORTING-TYPE if the call to this
5375 function does not specify it. WHAT is only for the prompt, to indicate
5376 what is being sorted. The sorting key will be extracted from
5377 the car of the elements of the table.
5378 If WITH-CASE is non-nil, the sorting will be case-sensitive."
5379 (unless sorting-type
5380 (message
5381 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
5382 what)
5383 (setq sorting-type (read-char-exclusive)))
5384 (let ((dcst (downcase sorting-type))
5385 extractfun comparefun)
5386 ;; Define the appropriate functions
5387 (cond
5388 ((= dcst ?n)
5389 (setq extractfun 'string-to-number
5390 comparefun (if (= dcst sorting-type) '< '>)))
5391 ((= dcst ?a)
5392 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
5393 (lambda(x) (downcase (org-sort-remove-invisible x))))
5394 comparefun (if (= dcst sorting-type)
5395 'string<
5396 (lambda (a b) (and (not (string< a b))
5397 (not (string= a b)))))))
5398 ((= dcst ?t)
5399 (setq extractfun
5400 (lambda (x)
5401 (if (string-match org-ts-regexp x)
5402 (time-to-seconds
5403 (org-time-string-to-time (match-string 0 x)))
5405 comparefun (if (= dcst sorting-type) '< '>)))
5406 (t (error "Invalid sorting type `%c'" sorting-type)))
5408 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
5409 table)
5410 (lambda (a b) (funcall comparefun (car a) (car b))))))
5412 ;;;; Plain list items, including checkboxes
5414 ;;; Plain list items
5416 (defun org-at-item-p ()
5417 "Is point in a line starting a hand-formatted item?"
5418 (let ((llt org-plain-list-ordered-item-terminator))
5419 (save-excursion
5420 (goto-char (point-at-bol))
5421 (looking-at
5422 (cond
5423 ((eq llt t) "\\([ \t]*\\([-+]\\|\\([0-9]+[.)]\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
5424 ((= llt ?.) "\\([ \t]*\\([-+]\\|\\([0-9]+\\.\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
5425 ((= llt ?\)) "\\([ \t]*\\([-+]\\|\\([0-9]+))\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
5426 (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))))))
5428 (defun org-in-item-p ()
5429 "It the cursor inside a plain list item.
5430 Does not have to be the first line."
5431 (save-excursion
5432 (condition-case nil
5433 (progn
5434 (org-beginning-of-item)
5435 (org-at-item-p)
5437 (error nil))))
5439 (defun org-insert-item (&optional checkbox)
5440 "Insert a new item at the current level.
5441 Return t when things worked, nil when we are not in an item."
5442 (when (save-excursion
5443 (condition-case nil
5444 (progn
5445 (org-beginning-of-item)
5446 (org-at-item-p)
5447 (if (org-invisible-p) (error "Invisible item"))
5449 (error nil)))
5450 (let* ((bul (match-string 0))
5451 (eow (save-excursion (beginning-of-line 1) (looking-at "[ \t]*")
5452 (match-end 0)))
5453 (blank (cdr (assq 'plain-list-item org-blank-before-new-entry)))
5454 pos)
5455 (cond
5456 ((and (org-at-item-p) (<= (point) eow))
5457 ;; before the bullet
5458 (beginning-of-line 1)
5459 (open-line (if blank 2 1)))
5460 ((<= (point) eow)
5461 (beginning-of-line 1))
5463 (unless (org-get-alist-option org-M-RET-may-split-line 'item)
5464 (end-of-line 1)
5465 (delete-horizontal-space))
5466 (newline (if blank 2 1))))
5467 (insert bul (if checkbox "[ ]" ""))
5468 (just-one-space)
5469 (setq pos (point))
5470 (end-of-line 1)
5471 (unless (= (point) pos) (just-one-space) (backward-delete-char 1)))
5472 (org-maybe-renumber-ordered-list)
5473 (and checkbox (org-update-checkbox-count-maybe))
5476 ;;; Checkboxes
5478 (defun org-at-item-checkbox-p ()
5479 "Is point at a line starting a plain-list item with a checklet?"
5480 (and (org-at-item-p)
5481 (save-excursion
5482 (goto-char (match-end 0))
5483 (skip-chars-forward " \t")
5484 (looking-at "\\[[- X]\\]"))))
5486 (defun org-toggle-checkbox (&optional arg)
5487 "Toggle the checkbox in the current line."
5488 (interactive "P")
5489 (catch 'exit
5490 (let (beg end status (firstnew 'unknown))
5491 (cond
5492 ((org-region-active-p)
5493 (setq beg (region-beginning) end (region-end)))
5494 ((org-on-heading-p)
5495 (setq beg (point) end (save-excursion (outline-next-heading) (point))))
5496 ((org-at-item-checkbox-p)
5497 (let ((pos (point)))
5498 (replace-match
5499 (cond (arg "[-]")
5500 ((member (match-string 0) '("[ ]" "[-]")) "[X]")
5501 (t "[ ]"))
5502 t t)
5503 (goto-char pos))
5504 (throw 'exit t))
5505 (t (error "Not at a checkbox or heading, and no active region")))
5506 (save-excursion
5507 (goto-char beg)
5508 (while (< (point) end)
5509 (when (org-at-item-checkbox-p)
5510 (setq status (equal (match-string 0) "[X]"))
5511 (when (eq firstnew 'unknown)
5512 (setq firstnew (not status)))
5513 (replace-match
5514 (if (if arg (not status) firstnew) "[X]" "[ ]") t t))
5515 (beginning-of-line 2)))))
5516 (org-update-checkbox-count-maybe))
5518 (defun org-update-checkbox-count-maybe ()
5519 "Update checkbox statistics unless turned off by user."
5520 (when org-provide-checkbox-statistics
5521 (org-update-checkbox-count)))
5523 (defun org-update-checkbox-count (&optional all)
5524 "Update the checkbox statistics in the current section.
5525 This will find all statistic cookies like [57%] and [6/12] and update them
5526 with the current numbers. With optional prefix argument ALL, do this for
5527 the whole buffer."
5528 (interactive "P")
5529 (save-excursion
5530 (let* ((buffer-invisibility-spec (org-inhibit-invisibility)) ; Emacs 21
5531 (beg (condition-case nil
5532 (progn (outline-back-to-heading) (point))
5533 (error (point-min))))
5534 (end (move-marker (make-marker)
5535 (progn (outline-next-heading) (point))))
5536 (re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
5537 (re-box "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)")
5538 (re-find (concat re "\\|" re-box))
5539 beg-cookie end-cookie is-percent c-on c-off lim
5540 eline curr-ind next-ind continue-from startsearch
5541 (cstat 0)
5543 (when all
5544 (goto-char (point-min))
5545 (outline-next-heading)
5546 (setq beg (point) end (point-max)))
5547 (goto-char end)
5548 ;; find each statistic cookie
5549 (while (re-search-backward re-find beg t)
5550 (setq beg-cookie (match-beginning 1)
5551 end-cookie (match-end 1)
5552 cstat (+ cstat (if end-cookie 1 0))
5553 startsearch (point-at-eol)
5554 continue-from (point-at-bol)
5555 is-percent (match-beginning 2)
5556 lim (cond
5557 ((org-on-heading-p) (outline-next-heading) (point))
5558 ((org-at-item-p) (org-end-of-item) (point))
5559 (t nil))
5560 c-on 0
5561 c-off 0)
5562 (when lim
5563 ;; find first checkbox for this cookie and gather
5564 ;; statistics from all that are at this indentation level
5565 (goto-char startsearch)
5566 (if (re-search-forward re-box lim t)
5567 (progn
5568 (org-beginning-of-item)
5569 (setq curr-ind (org-get-indentation))
5570 (setq next-ind curr-ind)
5571 (while (and (bolp) (org-at-item-p) (= curr-ind next-ind))
5572 (save-excursion (end-of-line) (setq eline (point)))
5573 (if (re-search-forward re-box eline t)
5574 (if (member (match-string 2) '("[ ]" "[-]"))
5575 (setq c-off (1+ c-off))
5576 (setq c-on (1+ c-on))
5579 (org-end-of-item)
5580 (setq next-ind (org-get-indentation))
5582 (goto-char continue-from)
5583 ;; update cookie
5584 (when end-cookie
5585 (delete-region beg-cookie end-cookie)
5586 (goto-char beg-cookie)
5587 (insert
5588 (if is-percent
5589 (format "[%d%%]" (/ (* 100 c-on) (max 1 (+ c-on c-off))))
5590 (format "[%d/%d]" c-on (+ c-on c-off)))))
5591 ;; update items checkbox if it has one
5592 (when (org-at-item-p)
5593 (org-beginning-of-item)
5594 (when (and (> (+ c-on c-off) 0)
5595 (re-search-forward re-box (point-at-eol) t))
5596 (setq beg-cookie (match-beginning 2)
5597 end-cookie (match-end 2))
5598 (delete-region beg-cookie end-cookie)
5599 (goto-char beg-cookie)
5600 (cond ((= c-off 0) (insert "[X]"))
5601 ((= c-on 0) (insert "[ ]"))
5602 (t (insert "[-]")))
5604 (goto-char continue-from))
5605 (when (interactive-p)
5606 (message "Checkbox satistics updated %s (%d places)"
5607 (if all "in entire file" "in current outline entry") cstat)))))
5609 (defun org-get-checkbox-statistics-face ()
5610 "Select the face for checkbox statistics.
5611 The face will be `org-done' when all relevant boxes are checked. Otherwise
5612 it will be `org-todo'."
5613 (if (match-end 1)
5614 (if (equal (match-string 1) "100%") 'org-done 'org-todo)
5615 (if (and (> (match-end 2) (match-beginning 2))
5616 (equal (match-string 2) (match-string 3)))
5617 'org-done
5618 'org-todo)))
5620 (defun org-get-indentation (&optional line)
5621 "Get the indentation of the current line, interpreting tabs.
5622 When LINE is given, assume it represents a line and compute its indentation."
5623 (if line
5624 (if (string-match "^ *" (org-remove-tabs line))
5625 (match-end 0))
5626 (save-excursion
5627 (beginning-of-line 1)
5628 (skip-chars-forward " \t")
5629 (current-column))))
5631 (defun org-remove-tabs (s &optional width)
5632 "Replace tabulators in S with spaces.
5633 Assumes that s is a single line, starting in column 0."
5634 (setq width (or width tab-width))
5635 (while (string-match "\t" s)
5636 (setq s (replace-match
5637 (make-string
5638 (- (* width (/ (+ (match-beginning 0) width) width))
5639 (match-beginning 0)) ?\ )
5640 t t s)))
5643 (defun org-fix-indentation (line ind)
5644 "Fix indentation in LINE.
5645 IND is a cons cell with target and minimum indentation.
5646 If the current indenation in LINE is smaller than the minimum,
5647 leave it alone. If it is larger than ind, set it to the target."
5648 (let* ((l (org-remove-tabs line))
5649 (i (org-get-indentation l))
5650 (i1 (car ind)) (i2 (cdr ind)))
5651 (if (>= i i2) (setq l (substring line i2)))
5652 (if (> i1 0)
5653 (concat (make-string i1 ?\ ) l)
5654 l)))
5656 (defcustom org-empty-line-terminates-plain-lists nil
5657 "Non-nil means, an empty line ends all plain list levels.
5658 When nil, empty lines are part of the preceeding item."
5659 :group 'org-plain-lists
5660 :type 'boolean)
5662 (defun org-beginning-of-item ()
5663 "Go to the beginning of the current hand-formatted item.
5664 If the cursor is not in an item, throw an error."
5665 (interactive)
5666 (let ((pos (point))
5667 (limit (save-excursion
5668 (condition-case nil
5669 (progn
5670 (org-back-to-heading)
5671 (beginning-of-line 2) (point))
5672 (error (point-min)))))
5673 (ind-empty (if org-empty-line-terminates-plain-lists 0 10000))
5674 ind ind1)
5675 (if (org-at-item-p)
5676 (beginning-of-line 1)
5677 (beginning-of-line 1)
5678 (skip-chars-forward " \t")
5679 (setq ind (current-column))
5680 (if (catch 'exit
5681 (while t
5682 (beginning-of-line 0)
5683 (if (or (bobp) (< (point) limit)) (throw 'exit nil))
5685 (if (looking-at "[ \t]*$")
5686 (setq ind1 ind-empty)
5687 (skip-chars-forward " \t")
5688 (setq ind1 (current-column)))
5689 (if (< ind1 ind)
5690 (progn (beginning-of-line 1) (throw 'exit (org-at-item-p))))))
5692 (goto-char pos)
5693 (error "Not in an item")))))
5695 (defun org-end-of-item ()
5696 "Go to the end of the current hand-formatted item.
5697 If the cursor is not in an item, throw an error."
5698 (interactive)
5699 (let* ((pos (point))
5700 ind1
5701 (ind-empty (if org-empty-line-terminates-plain-lists 0 10000))
5702 (limit (save-excursion (outline-next-heading) (point)))
5703 (ind (save-excursion
5704 (org-beginning-of-item)
5705 (skip-chars-forward " \t")
5706 (current-column)))
5707 (end (catch 'exit
5708 (while t
5709 (beginning-of-line 2)
5710 (if (eobp) (throw 'exit (point)))
5711 (if (>= (point) limit) (throw 'exit (point-at-bol)))
5712 (if (looking-at "[ \t]*$")
5713 (setq ind1 ind-empty)
5714 (skip-chars-forward " \t")
5715 (setq ind1 (current-column)))
5716 (if (<= ind1 ind)
5717 (throw 'exit (point-at-bol)))))))
5718 (if end
5719 (goto-char end)
5720 (goto-char pos)
5721 (error "Not in an item"))))
5723 (defun org-next-item ()
5724 "Move to the beginning of the next item in the current plain list.
5725 Error if not at a plain list, or if this is the last item in the list."
5726 (interactive)
5727 (let (ind ind1 (pos (point)))
5728 (org-beginning-of-item)
5729 (setq ind (org-get-indentation))
5730 (org-end-of-item)
5731 (setq ind1 (org-get-indentation))
5732 (unless (and (org-at-item-p) (= ind ind1))
5733 (goto-char pos)
5734 (error "On last item"))))
5736 (defun org-previous-item ()
5737 "Move to the beginning of the previous item in the current plain list.
5738 Error if not at a plain list, or if this is the first item in the list."
5739 (interactive)
5740 (let (beg ind ind1 (pos (point)))
5741 (org-beginning-of-item)
5742 (setq beg (point))
5743 (setq ind (org-get-indentation))
5744 (goto-char beg)
5745 (catch 'exit
5746 (while t
5747 (beginning-of-line 0)
5748 (if (looking-at "[ \t]*$")
5750 (if (<= (setq ind1 (org-get-indentation)) ind)
5751 (throw 'exit t)))))
5752 (condition-case nil
5753 (if (or (not (org-at-item-p))
5754 (< ind1 (1- ind)))
5755 (error "")
5756 (org-beginning-of-item))
5757 (error (goto-char pos)
5758 (error "On first item")))))
5760 (defun org-first-list-item-p ()
5761 "Is this heading the item in a plain list?"
5762 (unless (org-at-item-p)
5763 (error "Not at a plain list item"))
5764 (org-beginning-of-item)
5765 (= (point) (save-excursion (org-beginning-of-item-list))))
5767 (defun org-move-item-down ()
5768 "Move the plain list item at point down, i.e. swap with following item.
5769 Subitems (items with larger indentation) are considered part of the item,
5770 so this really moves item trees."
5771 (interactive)
5772 (let (beg beg0 end end0 ind ind1 (pos (point)) txt ne-end ne-beg)
5773 (org-beginning-of-item)
5774 (setq beg0 (point))
5775 (save-excursion
5776 (setq ne-beg (org-back-over-empty-lines))
5777 (setq beg (point)))
5778 (goto-char beg0)
5779 (setq ind (org-get-indentation))
5780 (org-end-of-item)
5781 (setq end0 (point))
5782 (setq ind1 (org-get-indentation))
5783 (setq ne-end (org-back-over-empty-lines))
5784 (setq end (point))
5785 (goto-char beg0)
5786 (when (and (org-first-list-item-p) (< ne-end ne-beg))
5787 ;; include less whitespace
5788 (save-excursion
5789 (goto-char beg)
5790 (forward-line (- ne-beg ne-end))
5791 (setq beg (point))))
5792 (goto-char end0)
5793 (if (and (org-at-item-p) (= ind ind1))
5794 (progn
5795 (org-end-of-item)
5796 (org-back-over-empty-lines)
5797 (setq txt (buffer-substring beg end))
5798 (save-excursion
5799 (delete-region beg end))
5800 (setq pos (point))
5801 (insert txt)
5802 (goto-char pos) (org-skip-whitespace)
5803 (org-maybe-renumber-ordered-list))
5804 (goto-char pos)
5805 (error "Cannot move this item further down"))))
5807 (defun org-move-item-up (arg)
5808 "Move the plain list item at point up, i.e. swap with previous item.
5809 Subitems (items with larger indentation) are considered part of the item,
5810 so this really moves item trees."
5811 (interactive "p")
5812 (let (beg beg0 end ind ind1 (pos (point)) txt
5813 ne-beg ne-ins ins-end)
5814 (org-beginning-of-item)
5815 (setq beg0 (point))
5816 (setq ind (org-get-indentation))
5817 (save-excursion
5818 (setq ne-beg (org-back-over-empty-lines))
5819 (setq beg (point)))
5820 (goto-char beg0)
5821 (org-end-of-item)
5822 (setq end (point))
5823 (goto-char beg0)
5824 (catch 'exit
5825 (while t
5826 (beginning-of-line 0)
5827 (if (looking-at "[ \t]*$")
5828 (if org-empty-line-terminates-plain-lists
5829 (progn
5830 (goto-char pos)
5831 (error "Cannot move this item further up"))
5832 nil)
5833 (if (<= (setq ind1 (org-get-indentation)) ind)
5834 (throw 'exit t)))))
5835 (condition-case nil
5836 (org-beginning-of-item)
5837 (error (goto-char beg)
5838 (error "Cannot move this item further up")))
5839 (setq ind1 (org-get-indentation))
5840 (if (and (org-at-item-p) (= ind ind1))
5841 (progn
5842 (setq ne-ins (org-back-over-empty-lines))
5843 (setq txt (buffer-substring beg end))
5844 (save-excursion
5845 (delete-region beg end))
5846 (setq pos (point))
5847 (insert txt)
5848 (setq ins-end (point))
5849 (goto-char pos) (org-skip-whitespace)
5851 (when (and (org-first-list-item-p) (> ne-ins ne-beg))
5852 ;; Move whitespace back to beginning
5853 (save-excursion
5854 (goto-char ins-end)
5855 (let ((kill-whole-line t))
5856 (kill-line (- ne-ins ne-beg)) (point)))
5857 (insert (make-string (- ne-ins ne-beg) ?\n)))
5859 (org-maybe-renumber-ordered-list))
5860 (goto-char pos)
5861 (error "Cannot move this item further up"))))
5863 (defun org-maybe-renumber-ordered-list ()
5864 "Renumber the ordered list at point if setup allows it.
5865 This tests the user option `org-auto-renumber-ordered-lists' before
5866 doing the renumbering."
5867 (interactive)
5868 (when (and org-auto-renumber-ordered-lists
5869 (org-at-item-p))
5870 (if (match-beginning 3)
5871 (org-renumber-ordered-list 1)
5872 (org-fix-bullet-type))))
5874 (defun org-maybe-renumber-ordered-list-safe ()
5875 (condition-case nil
5876 (save-excursion
5877 (org-maybe-renumber-ordered-list))
5878 (error nil)))
5880 (defun org-cycle-list-bullet (&optional which)
5881 "Cycle through the different itemize/enumerate bullets.
5882 This cycle the entire list level through the sequence:
5884 `-' -> `+' -> `*' -> `1.' -> `1)'
5886 If WHICH is a string, use that as the new bullet. If WHICH is an integer,
5887 0 meand `-', 1 means `+' etc."
5888 (interactive "P")
5889 (org-preserve-lc
5890 (org-beginning-of-item-list)
5891 (org-at-item-p)
5892 (beginning-of-line 1)
5893 (let ((current (match-string 0))
5894 (prevp (eq which 'previous))
5895 new)
5896 (setq new (cond
5897 ((and (numberp which)
5898 (nth (1- which) '("-" "+" "*" "1." "1)"))))
5899 ((string-match "-" current) (if prevp "1)" "+"))
5900 ((string-match "\\+" current)
5901 (if prevp "-" (if (looking-at "\\S-") "1." "*")))
5902 ((string-match "\\*" current) (if prevp "+" "1."))
5903 ((string-match "\\." current) (if prevp "*" "1)"))
5904 ((string-match ")" current) (if prevp "1." "-"))
5905 (t (error "This should not happen"))))
5906 (and (looking-at "\\([ \t]*\\)\\S-+") (replace-match (concat "\\1" new)))
5907 (org-fix-bullet-type)
5908 (org-maybe-renumber-ordered-list))))
5910 (defun org-get-string-indentation (s)
5911 "What indentation has S due to SPACE and TAB at the beginning of the string?"
5912 (let ((n -1) (i 0) (w tab-width) c)
5913 (catch 'exit
5914 (while (< (setq n (1+ n)) (length s))
5915 (setq c (aref s n))
5916 (cond ((= c ?\ ) (setq i (1+ i)))
5917 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
5918 (t (throw 'exit t)))))
5921 (defun org-renumber-ordered-list (arg)
5922 "Renumber an ordered plain list.
5923 Cursor needs to be in the first line of an item, the line that starts
5924 with something like \"1.\" or \"2)\"."
5925 (interactive "p")
5926 (unless (and (org-at-item-p)
5927 (match-beginning 3))
5928 (error "This is not an ordered list"))
5929 (let ((line (org-current-line))
5930 (col (current-column))
5931 (ind (org-get-string-indentation
5932 (buffer-substring (point-at-bol) (match-beginning 3))))
5933 ;; (term (substring (match-string 3) -1))
5934 ind1 (n (1- arg))
5935 fmt)
5936 ;; find where this list begins
5937 (org-beginning-of-item-list)
5938 (looking-at "[ \t]*[0-9]+\\([.)]\\)")
5939 (setq fmt (concat "%d" (match-string 1)))
5940 (beginning-of-line 0)
5941 ;; walk forward and replace these numbers
5942 (catch 'exit
5943 (while t
5944 (catch 'next
5945 (beginning-of-line 2)
5946 (if (eobp) (throw 'exit nil))
5947 (if (looking-at "[ \t]*$") (throw 'next nil))
5948 (skip-chars-forward " \t") (setq ind1 (current-column))
5949 (if (> ind1 ind) (throw 'next t))
5950 (if (< ind1 ind) (throw 'exit t))
5951 (if (not (org-at-item-p)) (throw 'exit nil))
5952 (delete-region (match-beginning 2) (match-end 2))
5953 (goto-char (match-beginning 2))
5954 (insert (format fmt (setq n (1+ n)))))))
5955 (goto-line line)
5956 (move-to-column col)))
5958 (defun org-fix-bullet-type ()
5959 "Make sure all items in this list have the same bullet as the firsst item."
5960 (interactive)
5961 (unless (org-at-item-p) (error "This is not a list"))
5962 (let ((line (org-current-line))
5963 (col (current-column))
5964 (ind (current-indentation))
5965 ind1 bullet)
5966 ;; find where this list begins
5967 (org-beginning-of-item-list)
5968 (beginning-of-line 1)
5969 ;; find out what the bullet type is
5970 (looking-at "[ \t]*\\(\\S-+\\)")
5971 (setq bullet (match-string 1))
5972 ;; walk forward and replace these numbers
5973 (beginning-of-line 0)
5974 (catch 'exit
5975 (while t
5976 (catch 'next
5977 (beginning-of-line 2)
5978 (if (eobp) (throw 'exit nil))
5979 (if (looking-at "[ \t]*$") (throw 'next nil))
5980 (skip-chars-forward " \t") (setq ind1 (current-column))
5981 (if (> ind1 ind) (throw 'next t))
5982 (if (< ind1 ind) (throw 'exit t))
5983 (if (not (org-at-item-p)) (throw 'exit nil))
5984 (skip-chars-forward " \t")
5985 (looking-at "\\S-+")
5986 (replace-match bullet))))
5987 (goto-line line)
5988 (move-to-column col)
5989 (if (string-match "[0-9]" bullet)
5990 (org-renumber-ordered-list 1))))
5992 (defun org-beginning-of-item-list ()
5993 "Go to the beginning of the current item list.
5994 I.e. to the first item in this list."
5995 (interactive)
5996 (org-beginning-of-item)
5997 (let ((pos (point-at-bol))
5998 (ind (org-get-indentation))
5999 ind1)
6000 ;; find where this list begins
6001 (catch 'exit
6002 (while t
6003 (catch 'next
6004 (beginning-of-line 0)
6005 (if (looking-at "[ \t]*$")
6006 (throw (if (bobp) 'exit 'next) t))
6007 (skip-chars-forward " \t") (setq ind1 (current-column))
6008 (if (or (< ind1 ind)
6009 (and (= ind1 ind)
6010 (not (org-at-item-p)))
6011 (bobp))
6012 (throw 'exit t)
6013 (when (org-at-item-p) (setq pos (point-at-bol)))))))
6014 (goto-char pos)))
6017 (defun org-end-of-item-list ()
6018 "Go to the end of the current item list.
6019 I.e. to the text after the last item."
6020 (interactive)
6021 (org-beginning-of-item)
6022 (let ((pos (point-at-bol))
6023 (ind (org-get-indentation))
6024 ind1)
6025 ;; find where this list begins
6026 (catch 'exit
6027 (while t
6028 (catch 'next
6029 (beginning-of-line 2)
6030 (if (looking-at "[ \t]*$")
6031 (throw (if (eobp) 'exit 'next) t))
6032 (skip-chars-forward " \t") (setq ind1 (current-column))
6033 (if (or (< ind1 ind)
6034 (and (= ind1 ind)
6035 (not (org-at-item-p)))
6036 (eobp))
6037 (progn
6038 (setq pos (point-at-bol))
6039 (throw 'exit t))))))
6040 (goto-char pos)))
6043 (defvar org-last-indent-begin-marker (make-marker))
6044 (defvar org-last-indent-end-marker (make-marker))
6046 (defun org-outdent-item (arg)
6047 "Outdent a local list item."
6048 (interactive "p")
6049 (org-indent-item (- arg)))
6051 (defun org-indent-item (arg)
6052 "Indent a local list item."
6053 (interactive "p")
6054 (unless (org-at-item-p)
6055 (error "Not on an item"))
6056 (save-excursion
6057 (let (beg end ind ind1 tmp delta ind-down ind-up)
6058 (if (memq last-command '(org-shiftmetaright org-shiftmetaleft))
6059 (setq beg org-last-indent-begin-marker
6060 end org-last-indent-end-marker)
6061 (org-beginning-of-item)
6062 (setq beg (move-marker org-last-indent-begin-marker (point)))
6063 (org-end-of-item)
6064 (setq end (move-marker org-last-indent-end-marker (point))))
6065 (goto-char beg)
6066 (setq tmp (org-item-indent-positions)
6067 ind (car tmp)
6068 ind-down (nth 2 tmp)
6069 ind-up (nth 1 tmp)
6070 delta (if (> arg 0)
6071 (if ind-down (- ind-down ind) 2)
6072 (if ind-up (- ind-up ind) -2)))
6073 (if (< (+ delta ind) 0) (error "Cannot outdent beyond margin"))
6074 (while (< (point) end)
6075 (beginning-of-line 1)
6076 (skip-chars-forward " \t") (setq ind1 (current-column))
6077 (delete-region (point-at-bol) (point))
6078 (or (eolp) (indent-to-column (+ ind1 delta)))
6079 (beginning-of-line 2))))
6080 (org-fix-bullet-type)
6081 (org-maybe-renumber-ordered-list-safe)
6082 (save-excursion
6083 (beginning-of-line 0)
6084 (condition-case nil (org-beginning-of-item) (error nil))
6085 (org-maybe-renumber-ordered-list-safe)))
6087 (defun org-item-indent-positions ()
6088 "Return indentation for plain list items.
6089 This returns a list with three values: The current indentation, the
6090 parent indentation and the indentation a child should habe.
6091 Assumes cursor in item line."
6092 (let* ((bolpos (point-at-bol))
6093 (ind (org-get-indentation))
6094 ind-down ind-up pos)
6095 (save-excursion
6096 (org-beginning-of-item-list)
6097 (skip-chars-backward "\n\r \t")
6098 (when (org-in-item-p)
6099 (org-beginning-of-item)
6100 (setq ind-up (org-get-indentation))))
6101 (setq pos (point))
6102 (save-excursion
6103 (cond
6104 ((and (condition-case nil (progn (org-previous-item) t)
6105 (error nil))
6106 (or (forward-char 1) t)
6107 (re-search-forward "^\\([ \t]*\\([-+]\\|\\([0-9]+[.)]\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)" bolpos t))
6108 (setq ind-down (org-get-indentation)))
6109 ((and (goto-char pos)
6110 (org-at-item-p))
6111 (goto-char (match-end 0))
6112 (skip-chars-forward " \t")
6113 (setq ind-down (current-column)))))
6114 (list ind ind-up ind-down)))
6116 ;;; The orgstruct minor mode
6118 ;; Define a minor mode which can be used in other modes in order to
6119 ;; integrate the org-mode structure editing commands.
6121 ;; This is really a hack, because the org-mode structure commands use
6122 ;; keys which normally belong to the major mode. Here is how it
6123 ;; works: The minor mode defines all the keys necessary to operate the
6124 ;; structure commands, but wraps the commands into a function which
6125 ;; tests if the cursor is currently at a headline or a plain list
6126 ;; item. If that is the case, the structure command is used,
6127 ;; temporarily setting many Org-mode variables like regular
6128 ;; expressions for filling etc. However, when any of those keys is
6129 ;; used at a different location, function uses `key-binding' to look
6130 ;; up if the key has an associated command in another currently active
6131 ;; keymap (minor modes, major mode, global), and executes that
6132 ;; command. There might be problems if any of the keys is otherwise
6133 ;; used as a prefix key.
6135 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
6136 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
6137 ;; addresses this by checking explicitly for both bindings.
6139 (defvar orgstruct-mode-map (make-sparse-keymap)
6140 "Keymap for the minor `orgstruct-mode'.")
6142 (defvar org-local-vars nil
6143 "List of local variables, for use by `orgstruct-mode'")
6145 ;;;###autoload
6146 (define-minor-mode orgstruct-mode
6147 "Toggle the minor more `orgstruct-mode'.
6148 This mode is for using Org-mode structure commands in other modes.
6149 The following key behave as if Org-mode was active, if the cursor
6150 is on a headline, or on a plain list item (both in the definition
6151 of Org-mode).
6153 M-up Move entry/item up
6154 M-down Move entry/item down
6155 M-left Promote
6156 M-right Demote
6157 M-S-up Move entry/item up
6158 M-S-down Move entry/item down
6159 M-S-left Promote subtree
6160 M-S-right Demote subtree
6161 M-q Fill paragraph and items like in Org-mode
6162 C-c ^ Sort entries
6163 C-c - Cycle list bullet
6164 TAB Cycle item visibility
6165 M-RET Insert new heading/item
6166 S-M-RET Insert new TODO heading / Chekbox item
6167 C-c C-c Set tags / toggle checkbox"
6168 nil " OrgStruct" nil
6169 (org-load-modules-maybe)
6170 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
6172 ;;;###autoload
6173 (defun turn-on-orgstruct ()
6174 "Unconditionally turn on `orgstruct-mode'."
6175 (orgstruct-mode 1))
6177 ;;;###autoload
6178 (defun turn-on-orgstruct++ ()
6179 "Unconditionally turn on `orgstruct-mode', and force org-mode indentations.
6180 In addition to setting orgstruct-mode, this also exports all indentation and
6181 autofilling variables from org-mode into the buffer. Note that turning
6182 off orgstruct-mode will *not* remove these additional settings."
6183 (orgstruct-mode 1)
6184 (let (var val)
6185 (mapc
6186 (lambda (x)
6187 (when (string-match
6188 "^\\(paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
6189 (symbol-name (car x)))
6190 (setq var (car x) val (nth 1 x))
6191 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
6192 org-local-vars)))
6194 (defun orgstruct-error ()
6195 "Error when there is no default binding for a structure key."
6196 (interactive)
6197 (error "This key has no function outside structure elements"))
6199 (defun orgstruct-setup ()
6200 "Setup orgstruct keymaps."
6201 (let ((nfunc 0)
6202 (bindings
6203 (list
6204 '([(meta up)] org-metaup)
6205 '([(meta down)] org-metadown)
6206 '([(meta left)] org-metaleft)
6207 '([(meta right)] org-metaright)
6208 '([(meta shift up)] org-shiftmetaup)
6209 '([(meta shift down)] org-shiftmetadown)
6210 '([(meta shift left)] org-shiftmetaleft)
6211 '([(meta shift right)] org-shiftmetaright)
6212 '([(shift up)] org-shiftup)
6213 '([(shift down)] org-shiftdown)
6214 '("\C-c\C-c" org-ctrl-c-ctrl-c)
6215 '("\M-q" fill-paragraph)
6216 '("\C-c^" org-sort)
6217 '("\C-c-" org-cycle-list-bullet)))
6218 elt key fun cmd)
6219 (while (setq elt (pop bindings))
6220 (setq nfunc (1+ nfunc))
6221 (setq key (org-key (car elt))
6222 fun (nth 1 elt)
6223 cmd (orgstruct-make-binding fun nfunc key))
6224 (org-defkey orgstruct-mode-map key cmd))
6226 ;; Special treatment needed for TAB and RET
6227 (org-defkey orgstruct-mode-map [(tab)]
6228 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
6229 (org-defkey orgstruct-mode-map "\C-i"
6230 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
6232 (org-defkey orgstruct-mode-map "\M-\C-m"
6233 (orgstruct-make-binding 'org-insert-heading 105
6234 "\M-\C-m" [(meta return)]))
6235 (org-defkey orgstruct-mode-map [(meta return)]
6236 (orgstruct-make-binding 'org-insert-heading 106
6237 [(meta return)] "\M-\C-m"))
6239 (org-defkey orgstruct-mode-map [(shift meta return)]
6240 (orgstruct-make-binding 'org-insert-todo-heading 107
6241 [(meta return)] "\M-\C-m"))
6243 (unless org-local-vars
6244 (setq org-local-vars (org-get-local-variables)))
6248 (defun orgstruct-make-binding (fun n &rest keys)
6249 "Create a function for binding in the structure minor mode.
6250 FUN is the command to call inside a table. N is used to create a unique
6251 command name. KEYS are keys that should be checked in for a command
6252 to execute outside of tables."
6253 (eval
6254 (list 'defun
6255 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
6256 '(arg)
6257 (concat "In Structure, run `" (symbol-name fun) "'.\n"
6258 "Outside of structure, run the binding of `"
6259 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
6260 "'.")
6261 '(interactive "p")
6262 (list 'if
6263 '(org-context-p 'headline 'item)
6264 (list 'org-run-like-in-org-mode (list 'quote fun))
6265 (list 'let '(orgstruct-mode)
6266 (list 'call-interactively
6267 (append '(or)
6268 (mapcar (lambda (k)
6269 (list 'key-binding k))
6270 keys)
6271 '('orgstruct-error))))))))
6273 (defun org-context-p (&rest contexts)
6274 "Check if local context is and of CONTEXTS.
6275 Possible values in the list of contexts are `table', `headline', and `item'."
6276 (let ((pos (point)))
6277 (goto-char (point-at-bol))
6278 (prog1 (or (and (memq 'table contexts)
6279 (looking-at "[ \t]*|"))
6280 (and (memq 'headline contexts)
6281 (looking-at "\\*+"))
6282 (and (memq 'item contexts)
6283 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)")))
6284 (goto-char pos))))
6286 (defun org-get-local-variables ()
6287 "Return a list of all local variables in an org-mode buffer."
6288 (let (varlist)
6289 (with-current-buffer (get-buffer-create "*Org tmp*")
6290 (erase-buffer)
6291 (org-mode)
6292 (setq varlist (buffer-local-variables)))
6293 (kill-buffer "*Org tmp*")
6294 (delq nil
6295 (mapcar
6296 (lambda (x)
6297 (setq x
6298 (if (symbolp x)
6299 (list x)
6300 (list (car x) (list 'quote (cdr x)))))
6301 (if (string-match
6302 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
6303 (symbol-name (car x)))
6304 x nil))
6305 varlist))))
6307 ;;;###autoload
6308 (defun org-run-like-in-org-mode (cmd)
6309 (org-load-modules-maybe)
6310 (unless org-local-vars
6311 (setq org-local-vars (org-get-local-variables)))
6312 (eval (list 'let org-local-vars
6313 (list 'call-interactively (list 'quote cmd)))))
6315 ;;;; Archiving
6317 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
6319 (defun org-archive-subtree (&optional find-done)
6320 "Move the current subtree to the archive.
6321 The archive can be a certain top-level heading in the current file, or in
6322 a different file. The tree will be moved to that location, the subtree
6323 heading be marked DONE, and the current time will be added.
6325 When called with prefix argument FIND-DONE, find whole trees without any
6326 open TODO items and archive them (after getting confirmation from the user).
6327 If the cursor is not at a headline when this comand is called, try all level
6328 1 trees. If the cursor is on a headline, only try the direct children of
6329 this heading."
6330 (interactive "P")
6331 (if find-done
6332 (org-archive-all-done)
6333 ;; Save all relevant TODO keyword-relatex variables
6335 (let ((tr-org-todo-line-regexp org-todo-line-regexp) ; keep despite compiler
6336 (tr-org-todo-keywords-1 org-todo-keywords-1)
6337 (tr-org-todo-kwd-alist org-todo-kwd-alist)
6338 (tr-org-done-keywords org-done-keywords)
6339 (tr-org-todo-regexp org-todo-regexp)
6340 (tr-org-todo-line-regexp org-todo-line-regexp)
6341 (tr-org-odd-levels-only org-odd-levels-only)
6342 (this-buffer (current-buffer))
6343 (org-archive-location org-archive-location)
6344 (re "^#\\+ARCHIVE:[ \t]+\\(\\S-.*\\S-\\)[ \t]*$")
6345 ;; start of variables that will be used for saving context
6346 ;; The compiler complains about them - keep them anyway!
6347 (file (abbreviate-file-name (buffer-file-name)))
6348 (olpath (mapconcat 'identity (org-get-outline-path) "/"))
6349 (time (format-time-string
6350 (substring (cdr org-time-stamp-formats) 1 -1)
6351 (current-time)))
6352 afile heading buffer level newfile-p
6353 category todo priority
6354 ;; start of variables that will be used for savind context
6355 ltags itags prop)
6357 ;; Try to find a local archive location
6358 (save-excursion
6359 (save-restriction
6360 (widen)
6361 (setq prop (org-entry-get nil "ARCHIVE" 'inherit))
6362 (if (and prop (string-match "\\S-" prop))
6363 (setq org-archive-location prop)
6364 (if (or (re-search-backward re nil t)
6365 (re-search-forward re nil t))
6366 (setq org-archive-location (match-string 1))))))
6368 (if (string-match "\\(.*\\)::\\(.*\\)" org-archive-location)
6369 (progn
6370 (setq afile (format (match-string 1 org-archive-location)
6371 (file-name-nondirectory buffer-file-name))
6372 heading (match-string 2 org-archive-location)))
6373 (error "Invalid `org-archive-location'"))
6374 (if (> (length afile) 0)
6375 (setq newfile-p (not (file-exists-p afile))
6376 buffer (find-file-noselect afile))
6377 (setq buffer (current-buffer)))
6378 (unless buffer
6379 (error "Cannot access file \"%s\"" afile))
6380 (if (and (> (length heading) 0)
6381 (string-match "^\\*+" heading))
6382 (setq level (match-end 0))
6383 (setq heading nil level 0))
6384 (save-excursion
6385 (org-back-to-heading t)
6386 ;; Get context information that will be lost by moving the tree
6387 (org-refresh-category-properties)
6388 (setq category (org-get-category)
6389 todo (and (looking-at org-todo-line-regexp)
6390 (match-string 2))
6391 priority (org-get-priority (if (match-end 3) (match-string 3) ""))
6392 ltags (org-get-tags)
6393 itags (org-delete-all ltags (org-get-tags-at)))
6394 (setq ltags (mapconcat 'identity ltags " ")
6395 itags (mapconcat 'identity itags " "))
6396 ;; We first only copy, in case something goes wrong
6397 ;; we need to protect this-command, to avoid kill-region sets it,
6398 ;; which would lead to duplication of subtrees
6399 (let (this-command) (org-copy-subtree))
6400 (set-buffer buffer)
6401 ;; Enforce org-mode for the archive buffer
6402 (if (not (org-mode-p))
6403 ;; Force the mode for future visits.
6404 (let ((org-insert-mode-line-in-empty-file t)
6405 (org-inhibit-startup t))
6406 (call-interactively 'org-mode)))
6407 (when newfile-p
6408 (goto-char (point-max))
6409 (insert (format "\nArchived entries from file %s\n\n"
6410 (buffer-file-name this-buffer))))
6411 ;; Force the TODO keywords of the original buffer
6412 (let ((org-todo-line-regexp tr-org-todo-line-regexp)
6413 (org-todo-keywords-1 tr-org-todo-keywords-1)
6414 (org-todo-kwd-alist tr-org-todo-kwd-alist)
6415 (org-done-keywords tr-org-done-keywords)
6416 (org-todo-regexp tr-org-todo-regexp)
6417 (org-todo-line-regexp tr-org-todo-line-regexp)
6418 (org-odd-levels-only
6419 (if (local-variable-p 'org-odd-levels-only (current-buffer))
6420 org-odd-levels-only
6421 tr-org-odd-levels-only)))
6422 (goto-char (point-min))
6423 (show-all)
6424 (if heading
6425 (progn
6426 (if (re-search-forward
6427 (concat "^" (regexp-quote heading)
6428 (org-re "[ \t]*\\(:[[:alnum:]_@:]+:\\)?[ \t]*\\($\\|\r\\)"))
6429 nil t)
6430 (goto-char (match-end 0))
6431 ;; Heading not found, just insert it at the end
6432 (goto-char (point-max))
6433 (or (bolp) (insert "\n"))
6434 (insert "\n" heading "\n")
6435 (end-of-line 0))
6436 ;; Make the subtree visible
6437 (show-subtree)
6438 (org-end-of-subtree t)
6439 (skip-chars-backward " \t\r\n")
6440 (and (looking-at "[ \t\r\n]*")
6441 (replace-match "\n\n")))
6442 ;; No specific heading, just go to end of file.
6443 (goto-char (point-max)) (insert "\n"))
6444 ;; Paste
6445 (org-paste-subtree (org-get-valid-level level 1))
6447 ;; Mark the entry as done
6448 (when (and org-archive-mark-done
6449 (looking-at org-todo-line-regexp)
6450 (or (not (match-end 2))
6451 (not (member (match-string 2) org-done-keywords))))
6452 (let (org-log-done org-todo-log-states)
6453 (org-todo
6454 (car (or (member org-archive-mark-done org-done-keywords)
6455 org-done-keywords)))))
6457 ;; Add the context info
6458 (when org-archive-save-context-info
6459 (let ((l org-archive-save-context-info) e n v)
6460 (while (setq e (pop l))
6461 (when (and (setq v (symbol-value e))
6462 (stringp v) (string-match "\\S-" v))
6463 (setq n (concat "ARCHIVE_" (upcase (symbol-name e))))
6464 (org-entry-put (point) n v)))))
6466 ;; Save and kill the buffer, if it is not the same buffer.
6467 (if (not (eq this-buffer buffer))
6468 (progn (save-buffer) (kill-buffer buffer)))))
6469 ;; Here we are back in the original buffer. Everything seems to have
6470 ;; worked. So now cut the tree and finish up.
6471 (let (this-command) (org-cut-subtree))
6472 (if (and (not (eobp)) (looking-at "[ \t]*$")) (kill-line))
6473 (message "Subtree archived %s"
6474 (if (eq this-buffer buffer)
6475 (concat "under heading: " heading)
6476 (concat "in file: " (abbreviate-file-name afile)))))))
6478 (defun org-get-category (&optional pos)
6479 "Get the category applying to position POS."
6480 (get-text-property (or pos (point)) 'org-category))
6482 (defun org-refresh-category-properties ()
6483 "Refresh category text properties in the buffer."
6484 (let ((def-cat (cond
6485 ((null org-category)
6486 (if buffer-file-name
6487 (file-name-sans-extension
6488 (file-name-nondirectory buffer-file-name))
6489 "???"))
6490 ((symbolp org-category) (symbol-name org-category))
6491 (t org-category)))
6492 beg end cat pos optionp)
6493 (org-unmodified
6494 (save-excursion
6495 (save-restriction
6496 (widen)
6497 (goto-char (point-min))
6498 (put-text-property (point) (point-max) 'org-category def-cat)
6499 (while (re-search-forward
6500 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
6501 (setq pos (match-end 0)
6502 optionp (equal (char-after (match-beginning 0)) ?#)
6503 cat (org-trim (match-string 2)))
6504 (if optionp
6505 (setq beg (point-at-bol) end (point-max))
6506 (org-back-to-heading t)
6507 (setq beg (point) end (org-end-of-subtree t t)))
6508 (put-text-property beg end 'org-category cat)
6509 (goto-char pos)))))))
6511 (defun org-archive-all-done (&optional tag)
6512 "Archive sublevels of the current tree without open TODO items.
6513 If the cursor is not on a headline, try all level 1 trees. If
6514 it is on a headline, try all direct children.
6515 When TAG is non-nil, don't move trees, but mark them with the ARCHIVE tag."
6516 (let ((re (concat "^\\*+ +" org-not-done-regexp)) re1
6517 (rea (concat ".*:" org-archive-tag ":"))
6518 (begm (make-marker))
6519 (endm (make-marker))
6520 (question (if tag "Set ARCHIVE tag (no open TODO items)? "
6521 "Move subtree to archive (no open TODO items)? "))
6522 beg end (cntarch 0))
6523 (if (org-on-heading-p)
6524 (progn
6525 (setq re1 (concat "^" (regexp-quote
6526 (make-string
6527 (1+ (- (match-end 0) (match-beginning 0) 1))
6528 ?*))
6529 " "))
6530 (move-marker begm (point))
6531 (move-marker endm (org-end-of-subtree t)))
6532 (setq re1 "^* ")
6533 (move-marker begm (point-min))
6534 (move-marker endm (point-max)))
6535 (save-excursion
6536 (goto-char begm)
6537 (while (re-search-forward re1 endm t)
6538 (setq beg (match-beginning 0)
6539 end (save-excursion (org-end-of-subtree t) (point)))
6540 (goto-char beg)
6541 (if (re-search-forward re end t)
6542 (goto-char end)
6543 (goto-char beg)
6544 (if (and (or (not tag) (not (looking-at rea)))
6545 (y-or-n-p question))
6546 (progn
6547 (if tag
6548 (org-toggle-tag org-archive-tag 'on)
6549 (org-archive-subtree))
6550 (setq cntarch (1+ cntarch)))
6551 (goto-char end)))))
6552 (message "%d trees archived" cntarch)))
6554 (defun org-cycle-hide-drawers (state)
6555 "Re-hide all drawers after a visibility state change."
6556 (when (and (org-mode-p)
6557 (not (memq state '(overview folded))))
6558 (save-excursion
6559 (let* ((globalp (memq state '(contents all)))
6560 (beg (if globalp (point-min) (point)))
6561 (end (if globalp (point-max) (org-end-of-subtree t))))
6562 (goto-char beg)
6563 (while (re-search-forward org-drawer-regexp end t)
6564 (org-flag-drawer t))))))
6566 (defun org-flag-drawer (flag)
6567 (save-excursion
6568 (beginning-of-line 1)
6569 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
6570 (let ((b (match-end 0))
6571 (outline-regexp org-outline-regexp))
6572 (if (re-search-forward
6573 "^[ \t]*:END:"
6574 (save-excursion (outline-next-heading) (point)) t)
6575 (outline-flag-region b (point-at-eol) flag)
6576 (error ":END: line missing"))))))
6578 (defun org-cycle-hide-archived-subtrees (state)
6579 "Re-hide all archived subtrees after a visibility state change."
6580 (when (and (not org-cycle-open-archived-trees)
6581 (not (memq state '(overview folded))))
6582 (save-excursion
6583 (let* ((globalp (memq state '(contents all)))
6584 (beg (if globalp (point-min) (point)))
6585 (end (if globalp (point-max) (org-end-of-subtree t))))
6586 (org-hide-archived-subtrees beg end)
6587 (goto-char beg)
6588 (if (looking-at (concat ".*:" org-archive-tag ":"))
6589 (message "%s" (substitute-command-keys
6590 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
6592 (defun org-force-cycle-archived ()
6593 "Cycle subtree even if it is archived."
6594 (interactive)
6595 (setq this-command 'org-cycle)
6596 (let ((org-cycle-open-archived-trees t))
6597 (call-interactively 'org-cycle)))
6599 (defun org-hide-archived-subtrees (beg end)
6600 "Re-hide all archived subtrees after a visibility state change."
6601 (save-excursion
6602 (let* ((re (concat ":" org-archive-tag ":")))
6603 (goto-char beg)
6604 (while (re-search-forward re end t)
6605 (and (org-on-heading-p) (hide-subtree))
6606 (org-end-of-subtree t)))))
6608 (defun org-toggle-tag (tag &optional onoff)
6609 "Toggle the tag TAG for the current line.
6610 If ONOFF is `on' or `off', don't toggle but set to this state."
6611 (unless (org-on-heading-p t) (error "Not on headling"))
6612 (let (res current)
6613 (save-excursion
6614 (beginning-of-line)
6615 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t]*$")
6616 (point-at-eol) t)
6617 (progn
6618 (setq current (match-string 1))
6619 (replace-match ""))
6620 (setq current ""))
6621 (setq current (nreverse (org-split-string current ":")))
6622 (cond
6623 ((eq onoff 'on)
6624 (setq res t)
6625 (or (member tag current) (push tag current)))
6626 ((eq onoff 'off)
6627 (or (not (member tag current)) (setq current (delete tag current))))
6628 (t (if (member tag current)
6629 (setq current (delete tag current))
6630 (setq res t)
6631 (push tag current))))
6632 (end-of-line 1)
6633 (if current
6634 (progn
6635 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
6636 (org-set-tags nil t))
6637 (delete-horizontal-space))
6638 (run-hooks 'org-after-tags-change-hook))
6639 res))
6641 (defun org-toggle-archive-tag (&optional arg)
6642 "Toggle the archive tag for the current headline.
6643 With prefix ARG, check all children of current headline and offer tagging
6644 the children that do not contain any open TODO items."
6645 (interactive "P")
6646 (if arg
6647 (org-archive-all-done 'tag)
6648 (let (set)
6649 (save-excursion
6650 (org-back-to-heading t)
6651 (setq set (org-toggle-tag org-archive-tag))
6652 (when set (hide-subtree)))
6653 (and set (beginning-of-line 1))
6654 (message "Subtree %s" (if set "archived" "unarchived")))))
6656 ;;;; Link Stuff
6658 ;;; Link abbreviations
6660 (defun org-link-expand-abbrev (link)
6661 "Apply replacements as defined in `org-link-abbrev-alist."
6662 (if (string-match "^\\([a-zA-Z][-_a-zA-Z0-9]*\\)\\(::?\\(.*\\)\\)?$" link)
6663 (let* ((key (match-string 1 link))
6664 (as (or (assoc key org-link-abbrev-alist-local)
6665 (assoc key org-link-abbrev-alist)))
6666 (tag (and (match-end 2) (match-string 3 link)))
6667 rpl)
6668 (if (not as)
6669 link
6670 (setq rpl (cdr as))
6671 (cond
6672 ((symbolp rpl) (funcall rpl tag))
6673 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
6674 (t (concat rpl tag)))))
6675 link))
6677 ;;; Storing and inserting links
6679 (defvar org-insert-link-history nil
6680 "Minibuffer history for links inserted with `org-insert-link'.")
6682 (defvar org-stored-links nil
6683 "Contains the links stored with `org-store-link'.")
6685 (defvar org-store-link-plist nil
6686 "Plist with info about the most recently link created with `org-store-link'.")
6688 (defvar org-link-protocols nil
6689 "Link protocols added to Org-mode using `org-add-link-type'.")
6691 (defvar org-store-link-functions nil
6692 "List of functions that are called to create and store a link.
6693 Each function will be called in turn until one returns a non-nil
6694 value. Each function should check if it is responsible for creating
6695 this link (for example by looking at the major mode).
6696 If not, it must exit and return nil.
6697 If yes, it should return a non-nil value after a calling
6698 `org-store-link-props' with a list of properties and values.
6699 Special properties are:
6701 :type The link prefix. like \"http\". This must be given.
6702 :link The link, like \"http://www.astro.uva.nl/~dominik\".
6703 This is obligatory as well.
6704 :description Optional default description for the second pair
6705 of brackets in an Org-mode link. The user can still change
6706 this when inserting this link into an Org-mode buffer.
6708 In addition to these, any additional properties can be specified
6709 and then used in remember templates.")
6711 (defun org-add-link-type (type &optional follow export)
6712 "Add TYPE to the list of `org-link-types'.
6713 Re-compute all regular expressions depending on `org-link-types'
6715 FOLLOW and EXPORT are two functions.
6717 FOLLOW should take the link path as the single argument and do whatever
6718 is necessary to follow the link, for example find a file or display
6719 a mail message.
6721 EXPORT should format the link path for export to one of the export formats.
6722 It should be a function accepting three arguments:
6724 path the path of the link, the text after the prefix (like \"http:\")
6725 desc the description of the link, if any, nil if there was no descripton
6726 format the export format, a symbol like `html' or `latex'.
6728 The function may use the FORMAT information to return different values
6729 depending on the format. The return value will be put literally into
6730 the exported file.
6731 Org-mode has a built-in default for exporting links. If you are happy with
6732 this default, there is no need to define an export function for the link
6733 type. For a simple example of an export function, see `org-bbdb.el'."
6734 (add-to-list 'org-link-types type t)
6735 (org-make-link-regexps)
6736 (if (assoc type org-link-protocols)
6737 (setcdr (assoc type org-link-protocols) (list follow export))
6738 (push (list type follow export) org-link-protocols)))
6741 ;;;###autoload
6742 (defun org-store-link (arg)
6743 "\\<org-mode-map>Store an org-link to the current location.
6744 This link is added to `org-stored-links' and can later be inserted
6745 into an org-buffer with \\[org-insert-link].
6747 For some link types, a prefix arg is interpreted:
6748 For links to usenet articles, arg negates `org-usenet-links-prefer-google'.
6749 For file links, arg negates `org-context-in-file-links'."
6750 (interactive "P")
6751 (org-load-modules-maybe)
6752 (setq org-store-link-plist nil) ; reset
6753 (let (link cpltxt desc description search txt)
6754 (cond
6756 ((run-hook-with-args-until-success 'org-store-link-functions)
6757 (setq link (plist-get org-store-link-plist :link)
6758 desc (or (plist-get org-store-link-plist :description) link)))
6760 ((eq major-mode 'calendar-mode)
6761 (let ((cd (calendar-cursor-to-date)))
6762 (setq link
6763 (format-time-string
6764 (car org-time-stamp-formats)
6765 (apply 'encode-time
6766 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
6767 nil nil nil))))
6768 (org-store-link-props :type "calendar" :date cd)))
6770 ((eq major-mode 'w3-mode)
6771 (setq cpltxt (url-view-url t)
6772 link (org-make-link cpltxt))
6773 (org-store-link-props :type "w3" :url (url-view-url t)))
6775 ((eq major-mode 'w3m-mode)
6776 (setq cpltxt (or w3m-current-title w3m-current-url)
6777 link (org-make-link w3m-current-url))
6778 (org-store-link-props :type "w3m" :url (url-view-url t)))
6780 ((setq search (run-hook-with-args-until-success
6781 'org-create-file-search-functions))
6782 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
6783 "::" search))
6784 (setq cpltxt (or description link)))
6786 ((eq major-mode 'image-mode)
6787 (setq cpltxt (concat "file:"
6788 (abbreviate-file-name buffer-file-name))
6789 link (org-make-link cpltxt))
6790 (org-store-link-props :type "image" :file buffer-file-name))
6792 ((eq major-mode 'dired-mode)
6793 ;; link to the file in the current line
6794 (setq cpltxt (concat "file:"
6795 (abbreviate-file-name
6796 (expand-file-name
6797 (dired-get-filename nil t))))
6798 link (org-make-link cpltxt)))
6800 ((and buffer-file-name (org-mode-p))
6801 ;; Just link to current headline
6802 (setq cpltxt (concat "file:"
6803 (abbreviate-file-name buffer-file-name)))
6804 ;; Add a context search string
6805 (when (org-xor org-context-in-file-links arg)
6806 ;; Check if we are on a target
6807 (if (org-in-regexp "<<\\(.*?\\)>>")
6808 (setq cpltxt (concat cpltxt "::" (match-string 1)))
6809 (setq txt (cond
6810 ((org-on-heading-p) nil)
6811 ((org-region-active-p)
6812 (buffer-substring (region-beginning) (region-end)))
6813 (t (buffer-substring (point-at-bol) (point-at-eol)))))
6814 (when (or (null txt) (string-match "\\S-" txt))
6815 (setq cpltxt
6816 (concat cpltxt "::" (org-make-org-heading-search-string txt))
6817 desc "NONE"))))
6818 (if (string-match "::\\'" cpltxt)
6819 (setq cpltxt (substring cpltxt 0 -2)))
6820 (setq link (org-make-link cpltxt)))
6822 ((buffer-file-name (buffer-base-buffer))
6823 ;; Just link to this file here.
6824 (setq cpltxt (concat "file:"
6825 (abbreviate-file-name
6826 (buffer-file-name (buffer-base-buffer)))))
6827 ;; Add a context string
6828 (when (org-xor org-context-in-file-links arg)
6829 (setq txt (if (org-region-active-p)
6830 (buffer-substring (region-beginning) (region-end))
6831 (buffer-substring (point-at-bol) (point-at-eol))))
6832 ;; Only use search option if there is some text.
6833 (when (string-match "\\S-" txt)
6834 (setq cpltxt
6835 (concat cpltxt "::" (org-make-org-heading-search-string txt))
6836 desc "NONE")))
6837 (setq link (org-make-link cpltxt)))
6839 ((interactive-p)
6840 (error "Cannot link to a buffer which is not visiting a file"))
6842 (t (setq link nil)))
6844 (if (consp link) (setq cpltxt (car link) link (cdr link)))
6845 (setq link (or link cpltxt)
6846 desc (or desc cpltxt))
6847 (if (equal desc "NONE") (setq desc nil))
6849 (if (and (interactive-p) link)
6850 (progn
6851 (setq org-stored-links
6852 (cons (list link desc) org-stored-links))
6853 (message "Stored: %s" (or desc link)))
6854 (and link (org-make-link-string link desc)))))
6856 (defun org-store-link-props (&rest plist)
6857 "Store link properties, extract names and addresses."
6858 (let (x adr)
6859 (when (setq x (plist-get plist :from))
6860 (setq adr (mail-extract-address-components x))
6861 (plist-put plist :fromname (car adr))
6862 (plist-put plist :fromaddress (nth 1 adr)))
6863 (when (setq x (plist-get plist :to))
6864 (setq adr (mail-extract-address-components x))
6865 (plist-put plist :toname (car adr))
6866 (plist-put plist :toaddress (nth 1 adr))))
6867 (let ((from (plist-get plist :from))
6868 (to (plist-get plist :to)))
6869 (when (and from to org-from-is-user-regexp)
6870 (plist-put plist :fromto
6871 (if (string-match org-from-is-user-regexp from)
6872 (concat "to %t")
6873 (concat "from %f")))))
6874 (setq org-store-link-plist plist))
6876 (defun org-add-link-props (&rest plist)
6877 "Add these properties to the link property list."
6878 (let (key value)
6879 (while plist
6880 (setq key (pop plist) value (pop plist))
6881 (setq org-store-link-plist
6882 (plist-put org-store-link-plist key value)))))
6884 (defun org-email-link-description (&optional fmt)
6885 "Return the description part of an email link.
6886 This takes information from `org-store-link-plist' and formats it
6887 according to FMT (default from `org-email-link-description-format')."
6888 (setq fmt (or fmt org-email-link-description-format))
6889 (let* ((p org-store-link-plist)
6890 (to (plist-get p :toaddress))
6891 (from (plist-get p :fromaddress))
6892 (table
6893 (list
6894 (cons "%c" (plist-get p :fromto))
6895 (cons "%F" (plist-get p :from))
6896 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
6897 (cons "%T" (plist-get p :to))
6898 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
6899 (cons "%s" (plist-get p :subject))
6900 (cons "%m" (plist-get p :message-id)))))
6901 (when (string-match "%c" fmt)
6902 ;; Check if the user wrote this message
6903 (if (and org-from-is-user-regexp from to
6904 (save-match-data (string-match org-from-is-user-regexp from)))
6905 (setq fmt (replace-match "to %t" t t fmt))
6906 (setq fmt (replace-match "from %f" t t fmt))))
6907 (org-replace-escapes fmt table)))
6909 (defun org-make-org-heading-search-string (&optional string heading)
6910 "Make search string for STRING or current headline."
6911 (interactive)
6912 (let ((s (or string (org-get-heading))))
6913 (unless (and string (not heading))
6914 ;; We are using a headline, clean up garbage in there.
6915 (if (string-match org-todo-regexp s)
6916 (setq s (replace-match "" t t s)))
6917 (if (string-match (org-re ":[[:alnum:]_@:]+:[ \t]*$") s)
6918 (setq s (replace-match "" t t s)))
6919 (setq s (org-trim s))
6920 (if (string-match (concat "^\\(" org-quote-string "\\|"
6921 org-comment-string "\\)") s)
6922 (setq s (replace-match "" t t s)))
6923 (while (string-match org-ts-regexp s)
6924 (setq s (replace-match "" t t s))))
6925 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
6926 (setq s (replace-match " " t t s)))
6927 (or string (setq s (concat "*" s))) ; Add * for headlines
6928 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
6930 (defun org-make-link (&rest strings)
6931 "Concatenate STRINGS."
6932 (apply 'concat strings))
6934 (defun org-make-link-string (link &optional description)
6935 "Make a link with brackets, consisting of LINK and DESCRIPTION."
6936 (unless (string-match "\\S-" link)
6937 (error "Empty link"))
6938 (when (stringp description)
6939 ;; Remove brackets from the description, they are fatal.
6940 (while (string-match "\\[" description)
6941 (setq description (replace-match "{" t t description)))
6942 (while (string-match "\\]" description)
6943 (setq description (replace-match "}" t t description))))
6944 (when (equal (org-link-escape link) description)
6945 ;; No description needed, it is identical
6946 (setq description nil))
6947 (when (and (not description)
6948 (not (equal link (org-link-escape link))))
6949 (setq description link))
6950 (concat "[[" (org-link-escape link) "]"
6951 (if description (concat "[" description "]") "")
6952 "]"))
6954 (defconst org-link-escape-chars
6955 '((?\ . "%20")
6956 (?\[ . "%5B")
6957 (?\] . "%5D")
6958 (?\340 . "%E0") ; `a
6959 (?\342 . "%E2") ; ^a
6960 (?\347 . "%E7") ; ,c
6961 (?\350 . "%E8") ; `e
6962 (?\351 . "%E9") ; 'e
6963 (?\352 . "%EA") ; ^e
6964 (?\356 . "%EE") ; ^i
6965 (?\364 . "%F4") ; ^o
6966 (?\371 . "%F9") ; `u
6967 (?\373 . "%FB") ; ^u
6968 (?\; . "%3B")
6969 (?? . "%3F")
6970 (?= . "%3D")
6971 (?+ . "%2B")
6973 "Association list of escapes for some characters problematic in links.
6974 This is the list that is used for internal purposes.")
6976 (defconst org-link-escape-chars-browser
6977 '((?\ . "%20")) ; 32 for the SPC char
6978 "Association list of escapes for some characters problematic in links.
6979 This is the list that is used before handing over to the browser.")
6981 (defun org-link-escape (text &optional table)
6982 "Escape charaters in TEXT that are problematic for links."
6983 (setq table (or table org-link-escape-chars))
6984 (when text
6985 (let ((re (mapconcat (lambda (x) (regexp-quote
6986 (char-to-string (car x))))
6987 table "\\|")))
6988 (while (string-match re text)
6989 (setq text
6990 (replace-match
6991 (cdr (assoc (string-to-char (match-string 0 text))
6992 table))
6993 t t text)))
6994 text)))
6996 (defun org-link-unescape (text &optional table)
6997 "Reverse the action of `org-link-escape'."
6998 (setq table (or table org-link-escape-chars))
6999 (when text
7000 (let ((re (mapconcat (lambda (x) (regexp-quote (cdr x)))
7001 table "\\|")))
7002 (while (string-match re text)
7003 (setq text
7004 (replace-match
7005 (char-to-string (car (rassoc (match-string 0 text) table)))
7006 t t text)))
7007 text)))
7009 (defun org-xor (a b)
7010 "Exclusive or."
7011 (if a (not b) b))
7013 (defun org-get-header (header)
7014 "Find a header field in the current buffer."
7015 (save-excursion
7016 (goto-char (point-min))
7017 (let ((case-fold-search t) s)
7018 (cond
7019 ((eq header 'from)
7020 (if (re-search-forward "^From:\\s-+\\(.*\\)" nil t)
7021 (setq s (match-string 1)))
7022 (while (string-match "\"" s)
7023 (setq s (replace-match "" t t s)))
7024 (if (string-match "[<(].*" s)
7025 (setq s (replace-match "" t t s))))
7026 ((eq header 'message-id)
7027 (if (re-search-forward "^message-id:\\s-+\\(.*\\)" nil t)
7028 (setq s (match-string 1))))
7029 ((eq header 'subject)
7030 (if (re-search-forward "^subject:\\s-+\\(.*\\)" nil t)
7031 (setq s (match-string 1)))))
7032 (if (string-match "\\`[ \t\]+" s) (setq s (replace-match "" t t s)))
7033 (if (string-match "[ \t\]+\\'" s) (setq s (replace-match "" t t s)))
7034 s)))
7037 (defun org-fixup-message-id-for-http (s)
7038 "Replace special characters in a message id, so it can be used in an http query."
7039 (while (string-match "<" s)
7040 (setq s (replace-match "%3C" t t s)))
7041 (while (string-match ">" s)
7042 (setq s (replace-match "%3E" t t s)))
7043 (while (string-match "@" s)
7044 (setq s (replace-match "%40" t t s)))
7047 ;;;###autoload
7048 (defun org-insert-link-global ()
7049 "Insert a link like Org-mode does.
7050 This command can be called in any mode to insert a link in Org-mode syntax."
7051 (interactive)
7052 (org-load-modules-maybe)
7053 (org-run-like-in-org-mode 'org-insert-link))
7055 (defun org-insert-link (&optional complete-file)
7056 "Insert a link. At the prompt, enter the link.
7058 Completion can be used to select a link previously stored with
7059 `org-store-link'. When the empty string is entered (i.e. if you just
7060 press RET at the prompt), the link defaults to the most recently
7061 stored link. As SPC triggers completion in the minibuffer, you need to
7062 use M-SPC or C-q SPC to force the insertion of a space character.
7064 You will also be prompted for a description, and if one is given, it will
7065 be displayed in the buffer instead of the link.
7067 If there is already a link at point, this command will allow you to edit link
7068 and description parts.
7070 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can be
7071 selected using completion. The path to the file will be relative to
7072 the current directory if the file is in the current directory or a
7073 subdirectory. Otherwise, the link will be the absolute path as
7074 completed in the minibuffer (i.e. normally ~/path/to/file).
7076 With two \\[universal-argument] prefixes, enforce an absolute path even if the file
7077 is in the current directory or below.
7078 With three \\[universal-argument] prefixes, negate the meaning of
7079 `org-keep-stored-link-after-insertion'."
7080 (interactive "P")
7081 (let* ((wcf (current-window-configuration))
7082 (region (if (org-region-active-p)
7083 (buffer-substring (region-beginning) (region-end))))
7084 (remove (and region (list (region-beginning) (region-end))))
7085 (desc region)
7086 tmphist ; byte-compile incorrectly complains about this
7087 link entry file)
7088 (cond
7089 ((org-in-regexp org-bracket-link-regexp 1)
7090 ;; We do have a link at point, and we are going to edit it.
7091 (setq remove (list (match-beginning 0) (match-end 0)))
7092 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
7093 (setq link (read-string "Link: "
7094 (org-link-unescape
7095 (org-match-string-no-properties 1)))))
7096 ((or (org-in-regexp org-angle-link-re)
7097 (org-in-regexp org-plain-link-re))
7098 ;; Convert to bracket link
7099 (setq remove (list (match-beginning 0) (match-end 0))
7100 link (read-string "Link: "
7101 (org-remove-angle-brackets (match-string 0)))))
7102 ((equal complete-file '(4))
7103 ;; Completing read for file names.
7104 (setq file (read-file-name "File: "))
7105 (let ((pwd (file-name-as-directory (expand-file-name ".")))
7106 (pwd1 (file-name-as-directory (abbreviate-file-name
7107 (expand-file-name ".")))))
7108 (cond
7109 ((equal complete-file '(16))
7110 (setq link (org-make-link
7111 "file:"
7112 (abbreviate-file-name (expand-file-name file)))))
7113 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
7114 (setq link (org-make-link "file:" (match-string 1 file))))
7115 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
7116 (expand-file-name file))
7117 (setq link (org-make-link
7118 "file:" (match-string 1 (expand-file-name file)))))
7119 (t (setq link (org-make-link "file:" file))))))
7121 ;; Read link, with completion for stored links.
7122 (with-output-to-temp-buffer "*Org Links*"
7123 (princ "Insert a link. Use TAB to complete valid link prefixes.\n")
7124 (when org-stored-links
7125 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
7126 (princ (mapconcat
7127 (lambda (x)
7128 (if (nth 1 x) (concat (car x) " (" (nth 1 x) ")") (car x)))
7129 (reverse org-stored-links) "\n"))))
7130 (let ((cw (selected-window)))
7131 (select-window (get-buffer-window "*Org Links*"))
7132 (shrink-window-if-larger-than-buffer)
7133 (setq truncate-lines t)
7134 (select-window cw))
7135 ;; Fake a link history, containing the stored links.
7136 (setq tmphist (append (mapcar 'car org-stored-links)
7137 org-insert-link-history))
7138 (unwind-protect
7139 (setq link (org-completing-read
7140 "Link: "
7141 (append
7142 (mapcar (lambda (x) (list (concat (car x) ":")))
7143 (append org-link-abbrev-alist-local org-link-abbrev-alist))
7144 (mapcar (lambda (x) (list (concat x ":")))
7145 org-link-types))
7146 nil nil nil
7147 'tmphist
7148 (or (car (car org-stored-links)))))
7149 (set-window-configuration wcf)
7150 (kill-buffer "*Org Links*"))
7151 (setq entry (assoc link org-stored-links))
7152 (or entry (push link org-insert-link-history))
7153 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
7154 (not org-keep-stored-link-after-insertion))
7155 (setq org-stored-links (delq (assoc link org-stored-links)
7156 org-stored-links)))
7157 (setq desc (or desc (nth 1 entry)))))
7159 (if (string-match org-plain-link-re link)
7160 ;; URL-like link, normalize the use of angular brackets.
7161 (setq link (org-make-link (org-remove-angle-brackets link))))
7163 ;; Check if we are linking to the current file with a search option
7164 ;; If yes, simplify the link by using only the search option.
7165 (when (and buffer-file-name
7166 (string-match "\\<file:\\(.+?\\)::\\([^>]+\\)" link))
7167 (let* ((path (match-string 1 link))
7168 (case-fold-search nil)
7169 (search (match-string 2 link)))
7170 (save-match-data
7171 (if (equal (file-truename buffer-file-name) (file-truename path))
7172 ;; We are linking to this same file, with a search option
7173 (setq link search)))))
7175 ;; Check if we can/should use a relative path. If yes, simplify the link
7176 (when (string-match "\\<file:\\(.*\\)" link)
7177 (let* ((path (match-string 1 link))
7178 (origpath path)
7179 (case-fold-search nil))
7180 (cond
7181 ((eq org-link-file-path-type 'absolute)
7182 (setq path (abbreviate-file-name (expand-file-name path))))
7183 ((eq org-link-file-path-type 'noabbrev)
7184 (setq path (expand-file-name path)))
7185 ((eq org-link-file-path-type 'relative)
7186 (setq path (file-relative-name path)))
7188 (save-match-data
7189 (if (string-match (concat "^" (regexp-quote
7190 (file-name-as-directory
7191 (expand-file-name "."))))
7192 (expand-file-name path))
7193 ;; We are linking a file with relative path name.
7194 (setq path (substring (expand-file-name path)
7195 (match-end 0)))))))
7196 (setq link (concat "file:" path))
7197 (if (equal desc origpath)
7198 (setq desc path))))
7200 (setq desc (read-string "Description: " desc))
7201 (unless (string-match "\\S-" desc) (setq desc nil))
7202 (if remove (apply 'delete-region remove))
7203 (insert (org-make-link-string link desc))))
7205 (defun org-completing-read (&rest args)
7206 (let ((minibuffer-local-completion-map
7207 (copy-keymap minibuffer-local-completion-map)))
7208 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
7209 (apply 'completing-read args)))
7211 ;;; Opening/following a link
7213 (defvar org-link-search-failed nil)
7215 (defun org-next-link ()
7216 "Move forward to the next link.
7217 If the link is in hidden text, expose it."
7218 (interactive)
7219 (when (and org-link-search-failed (eq this-command last-command))
7220 (goto-char (point-min))
7221 (message "Link search wrapped back to beginning of buffer"))
7222 (setq org-link-search-failed nil)
7223 (let* ((pos (point))
7224 (ct (org-context))
7225 (a (assoc :link ct)))
7226 (if a (goto-char (nth 2 a)))
7227 (if (re-search-forward org-any-link-re nil t)
7228 (progn
7229 (goto-char (match-beginning 0))
7230 (if (org-invisible-p) (org-show-context)))
7231 (goto-char pos)
7232 (setq org-link-search-failed t)
7233 (error "No further link found"))))
7235 (defun org-previous-link ()
7236 "Move backward to the previous link.
7237 If the link is in hidden text, expose it."
7238 (interactive)
7239 (when (and org-link-search-failed (eq this-command last-command))
7240 (goto-char (point-max))
7241 (message "Link search wrapped back to end of buffer"))
7242 (setq org-link-search-failed nil)
7243 (let* ((pos (point))
7244 (ct (org-context))
7245 (a (assoc :link ct)))
7246 (if a (goto-char (nth 1 a)))
7247 (if (re-search-backward org-any-link-re nil t)
7248 (progn
7249 (goto-char (match-beginning 0))
7250 (if (org-invisible-p) (org-show-context)))
7251 (goto-char pos)
7252 (setq org-link-search-failed t)
7253 (error "No further link found"))))
7255 (defun org-find-file-at-mouse (ev)
7256 "Open file link or URL at mouse."
7257 (interactive "e")
7258 (mouse-set-point ev)
7259 (org-open-at-point 'in-emacs))
7261 (defun org-open-at-mouse (ev)
7262 "Open file link or URL at mouse."
7263 (interactive "e")
7264 (mouse-set-point ev)
7265 (org-open-at-point))
7267 (defvar org-window-config-before-follow-link nil
7268 "The window configuration before following a link.
7269 This is saved in case the need arises to restore it.")
7271 (defvar org-open-link-marker (make-marker)
7272 "Marker pointing to the location where `org-open-at-point; was called.")
7274 ;;;###autoload
7275 (defun org-open-at-point-global ()
7276 "Follow a link like Org-mode does.
7277 This command can be called in any mode to follow a link that has
7278 Org-mode syntax."
7279 (interactive)
7280 (org-run-like-in-org-mode 'org-open-at-point))
7282 (defun org-open-at-point (&optional in-emacs)
7283 "Open link at or after point.
7284 If there is no link at point, this function will search forward up to
7285 the end of the current subtree.
7286 Normally, files will be opened by an appropriate application. If the
7287 optional argument IN-EMACS is non-nil, Emacs will visit the file."
7288 (interactive "P")
7289 (org-load-modules-maybe)
7290 (move-marker org-open-link-marker (point))
7291 (setq org-window-config-before-follow-link (current-window-configuration))
7292 (org-remove-occur-highlights nil nil t)
7293 (if (org-at-timestamp-p t)
7294 (org-follow-timestamp-link)
7295 (let (type path link line search (pos (point)))
7296 (catch 'match
7297 (save-excursion
7298 (skip-chars-forward "^]\n\r")
7299 (when (org-in-regexp org-bracket-link-regexp)
7300 (setq link (org-link-unescape (org-match-string-no-properties 1)))
7301 (while (string-match " *\n *" link)
7302 (setq link (replace-match " " t t link)))
7303 (setq link (org-link-expand-abbrev link))
7304 (if (string-match org-link-re-with-space2 link)
7305 (setq type (match-string 1 link) path (match-string 2 link))
7306 (setq type "thisfile" path link))
7307 (throw 'match t)))
7309 (when (get-text-property (point) 'org-linked-text)
7310 (setq type "thisfile"
7311 pos (if (get-text-property (1+ (point)) 'org-linked-text)
7312 (1+ (point)) (point))
7313 path (buffer-substring
7314 (previous-single-property-change pos 'org-linked-text)
7315 (next-single-property-change pos 'org-linked-text)))
7316 (throw 'match t))
7318 (save-excursion
7319 (when (or (org-in-regexp org-angle-link-re)
7320 (org-in-regexp org-plain-link-re))
7321 (setq type (match-string 1) path (match-string 2))
7322 (throw 'match t)))
7323 (when (org-in-regexp "\\<\\([^><\n]+\\)\\>")
7324 (setq type "tree-match"
7325 path (match-string 1))
7326 (throw 'match t))
7327 (save-excursion
7328 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@:]+\\):[ \t]*$"))
7329 (setq type "tags"
7330 path (match-string 1))
7331 (while (string-match ":" path)
7332 (setq path (replace-match "+" t t path)))
7333 (throw 'match t))))
7334 (unless path
7335 (error "No link found"))
7336 ;; Remove any trailing spaces in path
7337 (if (string-match " +\\'" path)
7338 (setq path (replace-match "" t t path)))
7340 (cond
7342 ((assoc type org-link-protocols)
7343 (funcall (nth 1 (assoc type org-link-protocols)) path))
7345 ((equal type "mailto")
7346 (let ((cmd (car org-link-mailto-program))
7347 (args (cdr org-link-mailto-program)) args1
7348 (address path) (subject "") a)
7349 (if (string-match "\\(.*\\)::\\(.*\\)" path)
7350 (setq address (match-string 1 path)
7351 subject (org-link-escape (match-string 2 path))))
7352 (while args
7353 (cond
7354 ((not (stringp (car args))) (push (pop args) args1))
7355 (t (setq a (pop args))
7356 (if (string-match "%a" a)
7357 (setq a (replace-match address t t a)))
7358 (if (string-match "%s" a)
7359 (setq a (replace-match subject t t a)))
7360 (push a args1))))
7361 (apply cmd (nreverse args1))))
7363 ((member type '("http" "https" "ftp" "news"))
7364 (browse-url (concat type ":" (org-link-escape
7365 path org-link-escape-chars-browser))))
7367 ((member type '("message"))
7368 (browse-url (concat type ":" path)))
7370 ((string= type "tags")
7371 (org-tags-view in-emacs path))
7372 ((string= type "thisfile")
7373 (if in-emacs
7374 (switch-to-buffer-other-window
7375 (org-get-buffer-for-internal-link (current-buffer)))
7376 (org-mark-ring-push))
7377 (let ((cmd `(org-link-search
7378 ,path
7379 ,(cond ((equal in-emacs '(4)) 'occur)
7380 ((equal in-emacs '(16)) 'org-occur)
7381 (t nil))
7382 ,pos)))
7383 (condition-case nil (eval cmd)
7384 (error (progn (widen) (eval cmd))))))
7386 ((string= type "tree-match")
7387 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
7389 ((string= type "file")
7390 (if (string-match "::\\([0-9]+\\)\\'" path)
7391 (setq line (string-to-number (match-string 1 path))
7392 path (substring path 0 (match-beginning 0)))
7393 (if (string-match "::\\(.+\\)\\'" path)
7394 (setq search (match-string 1 path)
7395 path (substring path 0 (match-beginning 0)))))
7396 (if (string-match "[*?{]" (file-name-nondirectory path))
7397 (dired path)
7398 (org-open-file path in-emacs line search)))
7400 ((string= type "news")
7401 (require 'org-gnus)
7402 (org-gnus-follow-link path))
7404 ((string= type "shell")
7405 (let ((cmd path))
7406 (if (or (not org-confirm-shell-link-function)
7407 (funcall org-confirm-shell-link-function
7408 (format "Execute \"%s\" in shell? "
7409 (org-add-props cmd nil
7410 'face 'org-warning))))
7411 (progn
7412 (message "Executing %s" cmd)
7413 (shell-command cmd))
7414 (error "Abort"))))
7416 ((string= type "elisp")
7417 (let ((cmd path))
7418 (if (or (not org-confirm-elisp-link-function)
7419 (funcall org-confirm-elisp-link-function
7420 (format "Execute \"%s\" as elisp? "
7421 (org-add-props cmd nil
7422 'face 'org-warning))))
7423 (message "%s => %s" cmd (eval (read cmd)))
7424 (error "Abort"))))
7427 (browse-url-at-point)))))
7428 (move-marker org-open-link-marker nil)
7429 (run-hook-with-args 'org-follow-link-hook))
7431 ;;; File search
7433 (defvar org-create-file-search-functions nil
7434 "List of functions to construct the right search string for a file link.
7435 These functions are called in turn with point at the location to
7436 which the link should point.
7438 A function in the hook should first test if it would like to
7439 handle this file type, for example by checking the major-mode or
7440 the file extension. If it decides not to handle this file, it
7441 should just return nil to give other functions a chance. If it
7442 does handle the file, it must return the search string to be used
7443 when following the link. The search string will be part of the
7444 file link, given after a double colon, and `org-open-at-point'
7445 will automatically search for it. If special measures must be
7446 taken to make the search successful, another function should be
7447 added to the companion hook `org-execute-file-search-functions',
7448 which see.
7450 A function in this hook may also use `setq' to set the variable
7451 `description' to provide a suggestion for the descriptive text to
7452 be used for this link when it gets inserted into an Org-mode
7453 buffer with \\[org-insert-link].")
7455 (defvar org-execute-file-search-functions nil
7456 "List of functions to execute a file search triggered by a link.
7458 Functions added to this hook must accept a single argument, the
7459 search string that was part of the file link, the part after the
7460 double colon. The function must first check if it would like to
7461 handle this search, for example by checking the major-mode or the
7462 file extension. If it decides not to handle this search, it
7463 should just return nil to give other functions a chance. If it
7464 does handle the search, it must return a non-nil value to keep
7465 other functions from trying.
7467 Each function can access the current prefix argument through the
7468 variable `current-prefix-argument'. Note that a single prefix is
7469 used to force opening a link in Emacs, so it may be good to only
7470 use a numeric or double prefix to guide the search function.
7472 In case this is needed, a function in this hook can also restore
7473 the window configuration before `org-open-at-point' was called using:
7475 (set-window-configuration org-window-config-before-follow-link)")
7477 (defun org-link-search (s &optional type avoid-pos)
7478 "Search for a link search option.
7479 If S is surrounded by forward slashes, it is interpreted as a
7480 regular expression. In org-mode files, this will create an `org-occur'
7481 sparse tree. In ordinary files, `occur' will be used to list matches.
7482 If the current buffer is in `dired-mode', grep will be used to search
7483 in all files. If AVOID-POS is given, ignore matches near that position."
7484 (let ((case-fold-search t)
7485 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
7486 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
7487 (append '(("") (" ") ("\t") ("\n"))
7488 org-emphasis-alist)
7489 "\\|") "\\)"))
7490 (pos (point))
7491 (pre "") (post "")
7492 words re0 re1 re2 re3 re4 re5 re2a reall)
7493 (cond
7494 ;; First check if there are any special
7495 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
7496 ;; Now try the builtin stuff
7497 ((save-excursion
7498 (goto-char (point-min))
7499 (and
7500 (re-search-forward
7501 (concat "<<" (regexp-quote s0) ">>") nil t)
7502 (setq pos (match-beginning 0))))
7503 ;; There is an exact target for this
7504 (goto-char pos))
7505 ((string-match "^/\\(.*\\)/$" s)
7506 ;; A regular expression
7507 (cond
7508 ((org-mode-p)
7509 (org-occur (match-string 1 s)))
7510 ;;((eq major-mode 'dired-mode)
7511 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
7512 (t (org-do-occur (match-string 1 s)))))
7514 ;; A normal search strings
7515 (when (equal (string-to-char s) ?*)
7516 ;; Anchor on headlines, post may include tags.
7517 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
7518 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@:+]:[ \t]*\\)?$")
7519 s (substring s 1)))
7520 (remove-text-properties
7521 0 (length s)
7522 '(face nil mouse-face nil keymap nil fontified nil) s)
7523 ;; Make a series of regular expressions to find a match
7524 (setq words (org-split-string s "[ \n\r\t]+")
7525 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
7526 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
7527 "\\)" markers)
7528 re2a (concat "[ \t\r\n]\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
7529 re4 (concat "[^a-zA-Z_]\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
7530 re1 (concat pre re2 post)
7531 re3 (concat pre re4 post)
7532 re5 (concat pre ".*" re4)
7533 re2 (concat pre re2)
7534 re2a (concat pre re2a)
7535 re4 (concat pre re4)
7536 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
7537 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
7538 re5 "\\)"
7540 (cond
7541 ((eq type 'org-occur) (org-occur reall))
7542 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
7543 (t (goto-char (point-min))
7544 (if (or (org-search-not-self 1 re0 nil t)
7545 (org-search-not-self 1 re1 nil t)
7546 (org-search-not-self 1 re2 nil t)
7547 (org-search-not-self 1 re2a nil t)
7548 (org-search-not-self 1 re3 nil t)
7549 (org-search-not-self 1 re4 nil t)
7550 (org-search-not-self 1 re5 nil t)
7552 (goto-char (match-beginning 1))
7553 (goto-char pos)
7554 (error "No match")))))
7556 ;; Normal string-search
7557 (goto-char (point-min))
7558 (if (search-forward s nil t)
7559 (goto-char (match-beginning 0))
7560 (error "No match"))))
7561 (and (org-mode-p) (org-show-context 'link-search))))
7563 (defun org-search-not-self (group &rest args)
7564 "Execute `re-search-forward', but only accept matches that do not
7565 enclose the position of `org-open-link-marker'."
7566 (let ((m org-open-link-marker))
7567 (catch 'exit
7568 (while (apply 're-search-forward args)
7569 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
7570 (goto-char (match-end group))
7571 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
7572 (> (match-beginning 0) (marker-position m))
7573 (< (match-end 0) (marker-position m)))
7574 (save-match-data
7575 (or (not (org-in-regexp
7576 org-bracket-link-analytic-regexp 1))
7577 (not (match-end 4)) ; no description
7578 (and (<= (match-beginning 4) (point))
7579 (>= (match-end 4) (point))))))
7580 (throw 'exit (point))))))))
7582 (defun org-get-buffer-for-internal-link (buffer)
7583 "Return a buffer to be used for displaying the link target of internal links."
7584 (cond
7585 ((not org-display-internal-link-with-indirect-buffer)
7586 buffer)
7587 ((string-match "(Clone)$" (buffer-name buffer))
7588 (message "Buffer is already a clone, not making another one")
7589 ;; we also do not modify visibility in this case
7590 buffer)
7591 (t ; make a new indirect buffer for displaying the link
7592 (let* ((bn (buffer-name buffer))
7593 (ibn (concat bn "(Clone)"))
7594 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
7595 (with-current-buffer ib (org-overview))
7596 ib))))
7598 (defun org-do-occur (regexp &optional cleanup)
7599 "Call the Emacs command `occur'.
7600 If CLEANUP is non-nil, remove the printout of the regular expression
7601 in the *Occur* buffer. This is useful if the regex is long and not useful
7602 to read."
7603 (occur regexp)
7604 (when cleanup
7605 (let ((cwin (selected-window)) win beg end)
7606 (when (setq win (get-buffer-window "*Occur*"))
7607 (select-window win))
7608 (goto-char (point-min))
7609 (when (re-search-forward "match[a-z]+" nil t)
7610 (setq beg (match-end 0))
7611 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
7612 (setq end (1- (match-beginning 0)))))
7613 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
7614 (goto-char (point-min))
7615 (select-window cwin))))
7617 ;;; The mark ring for links jumps
7619 (defvar org-mark-ring nil
7620 "Mark ring for positions before jumps in Org-mode.")
7621 (defvar org-mark-ring-last-goto nil
7622 "Last position in the mark ring used to go back.")
7623 ;; Fill and close the ring
7624 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
7625 (loop for i from 1 to org-mark-ring-length do
7626 (push (make-marker) org-mark-ring))
7627 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
7628 org-mark-ring)
7630 (defun org-mark-ring-push (&optional pos buffer)
7631 "Put the current position or POS into the mark ring and rotate it."
7632 (interactive)
7633 (setq pos (or pos (point)))
7634 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
7635 (move-marker (car org-mark-ring)
7636 (or pos (point))
7637 (or buffer (current-buffer)))
7638 (message "%s"
7639 (substitute-command-keys
7640 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
7642 (defun org-mark-ring-goto (&optional n)
7643 "Jump to the previous position in the mark ring.
7644 With prefix arg N, jump back that many stored positions. When
7645 called several times in succession, walk through the entire ring.
7646 Org-mode commands jumping to a different position in the current file,
7647 or to another Org-mode file, automatically push the old position
7648 onto the ring."
7649 (interactive "p")
7650 (let (p m)
7651 (if (eq last-command this-command)
7652 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
7653 (setq p org-mark-ring))
7654 (setq org-mark-ring-last-goto p)
7655 (setq m (car p))
7656 (switch-to-buffer (marker-buffer m))
7657 (goto-char m)
7658 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
7660 (defun org-remove-angle-brackets (s)
7661 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
7662 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
7664 (defun org-add-angle-brackets (s)
7665 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
7666 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
7669 ;;; Following specific links
7671 (defun org-follow-timestamp-link ()
7672 (cond
7673 ((org-at-date-range-p t)
7674 (let ((org-agenda-start-on-weekday)
7675 (t1 (match-string 1))
7676 (t2 (match-string 2)))
7677 (setq t1 (time-to-days (org-time-string-to-time t1))
7678 t2 (time-to-days (org-time-string-to-time t2)))
7679 (org-agenda-list nil t1 (1+ (- t2 t1)))))
7680 ((org-at-timestamp-p t)
7681 (org-agenda-list nil (time-to-days (org-time-string-to-time
7682 (substring (match-string 1) 0 10)))
7684 (t (error "This should not happen"))))
7687 ;;; Following file links
7689 (defun org-open-file (path &optional in-emacs line search)
7690 "Open the file at PATH.
7691 First, this expands any special file name abbreviations. Then the
7692 configuration variable `org-file-apps' is checked if it contains an
7693 entry for this file type, and if yes, the corresponding command is launched.
7694 If no application is found, Emacs simply visits the file.
7695 With optional argument IN-EMACS, Emacs will visit the file.
7696 Optional LINE specifies a line to go to, optional SEARCH a string to
7697 search for. If LINE or SEARCH is given, the file will always be
7698 opened in Emacs.
7699 If the file does not exist, an error is thrown."
7700 (setq in-emacs (or in-emacs line search))
7701 (let* ((file (if (equal path "")
7702 buffer-file-name
7703 (substitute-in-file-name (expand-file-name path))))
7704 (apps (append org-file-apps (org-default-apps)))
7705 (remp (and (assq 'remote apps) (org-file-remote-p file)))
7706 (dirp (if remp nil (file-directory-p file)))
7707 (dfile (downcase file))
7708 (old-buffer (current-buffer))
7709 (old-pos (point))
7710 (old-mode major-mode)
7711 ext cmd)
7712 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
7713 (setq ext (match-string 1 dfile))
7714 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
7715 (setq ext (match-string 1 dfile))))
7716 (if in-emacs
7717 (setq cmd 'emacs)
7718 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
7719 (and dirp (cdr (assoc 'directory apps)))
7720 (cdr (assoc ext apps))
7721 (cdr (assoc t apps)))))
7722 (when (eq cmd 'mailcap)
7723 (require 'mailcap)
7724 (mailcap-parse-mailcaps)
7725 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
7726 (command (mailcap-mime-info mime-type)))
7727 (if (stringp command)
7728 (setq cmd command)
7729 (setq cmd 'emacs))))
7730 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
7731 (not (file-exists-p file))
7732 (not org-open-non-existing-files))
7733 (error "No such file: %s" file))
7734 (cond
7735 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
7736 ;; Remove quotes around the file name - we'll use shell-quote-argument.
7737 (while (string-match "['\"]%s['\"]" cmd)
7738 (setq cmd (replace-match "%s" t t cmd)))
7739 (while (string-match "%s" cmd)
7740 (setq cmd (replace-match
7741 (save-match-data (shell-quote-argument file))
7742 t t cmd)))
7743 (save-window-excursion
7744 (start-process-shell-command cmd nil cmd)))
7745 ((or (stringp cmd)
7746 (eq cmd 'emacs))
7747 (funcall (cdr (assq 'file org-link-frame-setup)) file)
7748 (widen)
7749 (if line (goto-line line)
7750 (if search (org-link-search search))))
7751 ((consp cmd)
7752 (eval cmd))
7753 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
7754 (and (org-mode-p) (eq old-mode 'org-mode)
7755 (or (not (equal old-buffer (current-buffer)))
7756 (not (equal old-pos (point))))
7757 (org-mark-ring-push old-pos old-buffer))))
7759 (defun org-default-apps ()
7760 "Return the default applications for this operating system."
7761 (cond
7762 ((eq system-type 'darwin)
7763 org-file-apps-defaults-macosx)
7764 ((eq system-type 'windows-nt)
7765 org-file-apps-defaults-windowsnt)
7766 (t org-file-apps-defaults-gnu)))
7768 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
7769 (defun org-file-remote-p (file)
7770 "Test whether FILE specifies a location on a remote system.
7771 Return non-nil if the location is indeed remote.
7773 For example, the filename \"/user@host:/foo\" specifies a location
7774 on the system \"/user@host:\"."
7775 (cond ((fboundp 'file-remote-p)
7776 (file-remote-p file))
7777 ((fboundp 'tramp-handle-file-remote-p)
7778 (tramp-handle-file-remote-p file))
7779 ((and (boundp 'ange-ftp-name-format)
7780 (string-match (car ange-ftp-name-format) file))
7782 (t nil)))
7785 ;;;; Refiling
7787 (defun org-get-org-file ()
7788 "Read a filename, with default directory `org-directory'."
7789 (let ((default (or org-default-notes-file remember-data-file)))
7790 (read-file-name (format "File name [%s]: " default)
7791 (file-name-as-directory org-directory)
7792 default)))
7794 (defun org-notes-order-reversed-p ()
7795 "Check if the current file should receive notes in reversed order."
7796 (cond
7797 ((not org-reverse-note-order) nil)
7798 ((eq t org-reverse-note-order) t)
7799 ((not (listp org-reverse-note-order)) nil)
7800 (t (catch 'exit
7801 (let ((all org-reverse-note-order)
7802 entry)
7803 (while (setq entry (pop all))
7804 (if (string-match (car entry) buffer-file-name)
7805 (throw 'exit (cdr entry))))
7806 nil)))))
7808 (defvar org-refile-target-table nil
7809 "The list of refile targets, created by `org-refile'.")
7811 (defvar org-agenda-new-buffers nil
7812 "Buffers created to visit agenda files.")
7814 (defun org-get-refile-targets (&optional default-buffer)
7815 "Produce a table with refile targets."
7816 (let ((entries (or org-refile-targets '((nil . (:level . 1)))))
7817 targets txt re files f desc descre)
7818 (with-current-buffer (or default-buffer (current-buffer))
7819 (while (setq entry (pop entries))
7820 (setq files (car entry) desc (cdr entry))
7821 (cond
7822 ((null files) (setq files (list (current-buffer))))
7823 ((eq files 'org-agenda-files)
7824 (setq files (org-agenda-files 'unrestricted)))
7825 ((and (symbolp files) (fboundp files))
7826 (setq files (funcall files)))
7827 ((and (symbolp files) (boundp files))
7828 (setq files (symbol-value files))))
7829 (if (stringp files) (setq files (list files)))
7830 (cond
7831 ((eq (car desc) :tag)
7832 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
7833 ((eq (car desc) :todo)
7834 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
7835 ((eq (car desc) :regexp)
7836 (setq descre (cdr desc)))
7837 ((eq (car desc) :level)
7838 (setq descre (concat "^\\*\\{" (number-to-string
7839 (if org-odd-levels-only
7840 (1- (* 2 (cdr desc)))
7841 (cdr desc)))
7842 "\\}[ \t]")))
7843 ((eq (car desc) :maxlevel)
7844 (setq descre (concat "^\\*\\{1," (number-to-string
7845 (if org-odd-levels-only
7846 (1- (* 2 (cdr desc)))
7847 (cdr desc)))
7848 "\\}[ \t]")))
7849 (t (error "Bad refiling target description %s" desc)))
7850 (while (setq f (pop files))
7851 (save-excursion
7852 (set-buffer (if (bufferp f) f (org-get-agenda-file-buffer f)))
7853 (if (bufferp f) (setq f (buffer-file-name (buffer-base-buffer f))))
7854 (save-excursion
7855 (save-restriction
7856 (widen)
7857 (goto-char (point-min))
7858 (while (re-search-forward descre nil t)
7859 (goto-char (point-at-bol))
7860 (when (looking-at org-complex-heading-regexp)
7861 (setq txt (match-string 4)
7862 re (concat "^" (regexp-quote
7863 (buffer-substring (match-beginning 1)
7864 (match-end 4)))))
7865 (if (match-end 5) (setq re (concat re "[ \t]+"
7866 (regexp-quote
7867 (match-string 5)))))
7868 (setq re (concat re "[ \t]*$"))
7869 (when org-refile-use-outline-path
7870 (setq txt (mapconcat 'identity
7871 (append
7872 (if (eq org-refile-use-outline-path 'file)
7873 (list (file-name-nondirectory
7874 (buffer-file-name (buffer-base-buffer))))
7875 (if (eq org-refile-use-outline-path 'full-file-path)
7876 (list (buffer-file-name (buffer-base-buffer)))))
7877 (org-get-outline-path)
7878 (list txt))
7879 "/")))
7880 (push (list txt f re (point)) targets))
7881 (goto-char (point-at-eol))))))))
7882 (nreverse targets))))
7884 (defun org-get-outline-path ()
7885 "Return the outline path to the current entry, as a list."
7886 (let (rtn)
7887 (save-excursion
7888 (while (org-up-heading-safe)
7889 (when (looking-at org-complex-heading-regexp)
7890 (push (org-match-string-no-properties 4) rtn)))
7891 rtn)))
7893 (defvar org-refile-history nil
7894 "History for refiling operations.")
7896 (defun org-refile (&optional goto default-buffer)
7897 "Move the entry at point to another heading.
7898 The list of target headings is compiled using the information in
7899 `org-refile-targets', which see. This list is created before each use
7900 and will therefore always be up-to-date.
7902 At the target location, the entry is filed as a subitem of the target heading.
7903 Depending on `org-reverse-note-order', the new subitem will either be the
7904 first of the last subitem.
7906 With prefix arg GOTO, the command will only visit the target location,
7907 not actually move anything.
7908 With a double prefix `C-c C-c', go to the location where the last refiling
7909 operation has put the subtree."
7910 (interactive "P")
7911 (let* ((cbuf (current-buffer))
7912 (filename (buffer-file-name (buffer-base-buffer cbuf)))
7913 pos it nbuf file re level reversed)
7914 (if (equal goto '(16))
7915 (org-refile-goto-last-stored)
7916 (when (setq it (org-refile-get-location
7917 (if goto "Goto: " "Refile to: ") default-buffer))
7918 (setq file (nth 1 it)
7919 re (nth 2 it)
7920 pos (nth 3 it))
7921 (setq nbuf (or (find-buffer-visiting file)
7922 (find-file-noselect file)))
7923 (if goto
7924 (progn
7925 (switch-to-buffer nbuf)
7926 (goto-char pos)
7927 (org-show-context 'org-goto))
7928 (org-copy-special)
7929 (save-excursion
7930 (set-buffer (setq nbuf (or (find-buffer-visiting file)
7931 (find-file-noselect file))))
7932 (setq reversed (org-notes-order-reversed-p))
7933 (save-excursion
7934 (save-restriction
7935 (widen)
7936 (goto-char pos)
7937 (looking-at outline-regexp)
7938 (setq level (org-get-valid-level (funcall outline-level) 1))
7939 (goto-char
7940 (if reversed
7941 (outline-next-heading)
7942 (or (save-excursion (outline-get-next-sibling))
7943 (org-end-of-subtree t t)
7944 (point-max))))
7945 (bookmark-set "org-refile-last-stored")
7946 (org-paste-subtree level))))
7947 (org-cut-special)
7948 (message "Entry refiled to \"%s\"" (car it)))))))
7950 (defun org-refile-goto-last-stored ()
7951 "Go to the location where the last refile was stored."
7952 (interactive)
7953 (bookmark-jump "org-refile-last-stored")
7954 (message "This is the location of the last refile"))
7956 (defun org-refile-get-location (&optional prompt default-buffer)
7957 "Prompt the user for a refile location, using PROMPT."
7958 (let ((org-refile-targets org-refile-targets)
7959 (org-refile-use-outline-path org-refile-use-outline-path))
7960 (setq org-refile-target-table (org-get-refile-targets default-buffer)))
7961 (unless org-refile-target-table
7962 (error "No refile targets"))
7963 (let* ((cbuf (current-buffer))
7964 (filename (buffer-file-name (buffer-base-buffer cbuf)))
7965 (fname (and filename (file-truename filename)))
7966 (tbl (mapcar
7967 (lambda (x)
7968 (if (not (equal fname (file-truename (nth 1 x))))
7969 (cons (concat (car x) " (" (file-name-nondirectory
7970 (nth 1 x)) ")")
7971 (cdr x))
7973 org-refile-target-table))
7974 (completion-ignore-case t))
7975 (assoc (completing-read prompt tbl nil t nil 'org-refile-history)
7976 tbl)))
7978 ;;;; Dynamic blocks
7980 (defun org-find-dblock (name)
7981 "Find the first dynamic block with name NAME in the buffer.
7982 If not found, stay at current position and return nil."
7983 (let (pos)
7984 (save-excursion
7985 (goto-char (point-min))
7986 (setq pos (and (re-search-forward (concat "^#\\+BEGIN:[ \t]+" name "\\>")
7987 nil t)
7988 (match-beginning 0))))
7989 (if pos (goto-char pos))
7990 pos))
7992 (defconst org-dblock-start-re
7993 "^#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
7994 "Matches the startline of a dynamic block, with parameters.")
7996 (defconst org-dblock-end-re "^#\\+END\\([: \t\r\n]\\|$\\)"
7997 "Matches the end of a dyhamic block.")
7999 (defun org-create-dblock (plist)
8000 "Create a dynamic block section, with parameters taken from PLIST.
8001 PLIST must containe a :name entry which is used as name of the block."
8002 (unless (bolp) (newline))
8003 (let ((name (plist-get plist :name)))
8004 (insert "#+BEGIN: " name)
8005 (while plist
8006 (if (eq (car plist) :name)
8007 (setq plist (cddr plist))
8008 (insert " " (prin1-to-string (pop plist)))))
8009 (insert "\n\n#+END:\n")
8010 (beginning-of-line -2)))
8012 (defun org-prepare-dblock ()
8013 "Prepare dynamic block for refresh.
8014 This empties the block, puts the cursor at the insert position and returns
8015 the property list including an extra property :name with the block name."
8016 (unless (looking-at org-dblock-start-re)
8017 (error "Not at a dynamic block"))
8018 (let* ((begdel (1+ (match-end 0)))
8019 (name (org-no-properties (match-string 1)))
8020 (params (append (list :name name)
8021 (read (concat "(" (match-string 3) ")")))))
8022 (unless (re-search-forward org-dblock-end-re nil t)
8023 (error "Dynamic block not terminated"))
8024 (setq params
8025 (append params
8026 (list :content (buffer-substring
8027 begdel (match-beginning 0)))))
8028 (delete-region begdel (match-beginning 0))
8029 (goto-char begdel)
8030 (open-line 1)
8031 params))
8033 (defun org-map-dblocks (&optional command)
8034 "Apply COMMAND to all dynamic blocks in the current buffer.
8035 If COMMAND is not given, use `org-update-dblock'."
8036 (let ((cmd (or command 'org-update-dblock))
8037 pos)
8038 (save-excursion
8039 (goto-char (point-min))
8040 (while (re-search-forward org-dblock-start-re nil t)
8041 (goto-char (setq pos (match-beginning 0)))
8042 (condition-case nil
8043 (funcall cmd)
8044 (error (message "Error during update of dynamic block")))
8045 (goto-char pos)
8046 (unless (re-search-forward org-dblock-end-re nil t)
8047 (error "Dynamic block not terminated"))))))
8049 (defun org-dblock-update (&optional arg)
8050 "User command for updating dynamic blocks.
8051 Update the dynamic block at point. With prefix ARG, update all dynamic
8052 blocks in the buffer."
8053 (interactive "P")
8054 (if arg
8055 (org-update-all-dblocks)
8056 (or (looking-at org-dblock-start-re)
8057 (org-beginning-of-dblock))
8058 (org-update-dblock)))
8060 (defun org-update-dblock ()
8061 "Update the dynamic block at point
8062 This means to empty the block, parse for parameters and then call
8063 the correct writing function."
8064 (save-window-excursion
8065 (let* ((pos (point))
8066 (line (org-current-line))
8067 (params (org-prepare-dblock))
8068 (name (plist-get params :name))
8069 (cmd (intern (concat "org-dblock-write:" name))))
8070 (message "Updating dynamic block `%s' at line %d..." name line)
8071 (funcall cmd params)
8072 (message "Updating dynamic block `%s' at line %d...done" name line)
8073 (goto-char pos))))
8075 (defun org-beginning-of-dblock ()
8076 "Find the beginning of the dynamic block at point.
8077 Error if there is no scuh block at point."
8078 (let ((pos (point))
8079 beg)
8080 (end-of-line 1)
8081 (if (and (re-search-backward org-dblock-start-re nil t)
8082 (setq beg (match-beginning 0))
8083 (re-search-forward org-dblock-end-re nil t)
8084 (> (match-end 0) pos))
8085 (goto-char beg)
8086 (goto-char pos)
8087 (error "Not in a dynamic block"))))
8089 (defun org-update-all-dblocks ()
8090 "Update all dynamic blocks in the buffer.
8091 This function can be used in a hook."
8092 (when (org-mode-p)
8093 (org-map-dblocks 'org-update-dblock)))
8096 ;;;; Completion
8098 (defconst org-additional-option-like-keywords
8099 '("BEGIN_HTML" "BEGIN_LaTeX" "END_HTML" "END_LaTeX"
8100 "ORGTBL" "HTML:" "LaTeX:" "BEGIN:" "END:" "TBLFM"
8101 "BEGIN_EXAMPLE" "END_EXAMPLE"))
8103 (defun org-complete (&optional arg)
8104 "Perform completion on word at point.
8105 At the beginning of a headline, this completes TODO keywords as given in
8106 `org-todo-keywords'.
8107 If the current word is preceded by a backslash, completes the TeX symbols
8108 that are supported for HTML support.
8109 If the current word is preceded by \"#+\", completes special words for
8110 setting file options.
8111 In the line after \"#+STARTUP:, complete valid keywords.\"
8112 At all other locations, this simply calls the value of
8113 `org-completion-fallback-command'."
8114 (interactive "P")
8115 (org-without-partial-completion
8116 (catch 'exit
8117 (let* ((end (point))
8118 (beg1 (save-excursion
8119 (skip-chars-backward (org-re "[:alnum:]_@"))
8120 (point)))
8121 (beg (save-excursion
8122 (skip-chars-backward "a-zA-Z0-9_:$")
8123 (point)))
8124 (confirm (lambda (x) (stringp (car x))))
8125 (searchhead (equal (char-before beg) ?*))
8126 (tag (and (equal (char-before beg1) ?:)
8127 (equal (char-after (point-at-bol)) ?*)))
8128 (prop (and (equal (char-before beg1) ?:)
8129 (not (equal (char-after (point-at-bol)) ?*))))
8130 (texp (equal (char-before beg) ?\\))
8131 (link (equal (char-before beg) ?\[))
8132 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
8133 beg)
8134 "#+"))
8135 (startup (string-match "^#\\+STARTUP:.*"
8136 (buffer-substring (point-at-bol) (point))))
8137 (completion-ignore-case opt)
8138 (type nil)
8139 (tbl nil)
8140 (table (cond
8141 (opt
8142 (setq type :opt)
8143 (require 'org-exp)
8144 (append
8145 (mapcar
8146 (lambda (x)
8147 (string-match "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
8148 (cons (match-string 2 x) (match-string 1 x)))
8149 (org-split-string (org-get-current-options) "\n"))
8150 (mapcar 'list org-additional-option-like-keywords)))
8151 (startup
8152 (setq type :startup)
8153 org-startup-options)
8154 (link (append org-link-abbrev-alist-local
8155 org-link-abbrev-alist))
8156 (texp
8157 (setq type :tex)
8158 org-html-entities)
8159 ((string-match "\\`\\*+[ \t]+\\'"
8160 (buffer-substring (point-at-bol) beg))
8161 (setq type :todo)
8162 (mapcar 'list org-todo-keywords-1))
8163 (searchhead
8164 (setq type :searchhead)
8165 (save-excursion
8166 (goto-char (point-min))
8167 (while (re-search-forward org-todo-line-regexp nil t)
8168 (push (list
8169 (org-make-org-heading-search-string
8170 (match-string 3) t))
8171 tbl)))
8172 tbl)
8173 (tag (setq type :tag beg beg1)
8174 (or org-tag-alist (org-get-buffer-tags)))
8175 (prop (setq type :prop beg beg1)
8176 (mapcar 'list (org-buffer-property-keys nil t t)))
8177 (t (progn
8178 (call-interactively org-completion-fallback-command)
8179 (throw 'exit nil)))))
8180 (pattern (buffer-substring-no-properties beg end))
8181 (completion (try-completion pattern table confirm)))
8182 (cond ((eq completion t)
8183 (if (not (assoc (upcase pattern) table))
8184 (message "Already complete")
8185 (if (and (equal type :opt)
8186 (not (member (car (assoc (upcase pattern) table))
8187 org-additional-option-like-keywords)))
8188 (insert (substring (cdr (assoc (upcase pattern) table))
8189 (length pattern)))
8190 (if (memq type '(:tag :prop)) (insert ":")))))
8191 ((null completion)
8192 (message "Can't find completion for \"%s\"" pattern)
8193 (ding))
8194 ((not (string= pattern completion))
8195 (delete-region beg end)
8196 (if (string-match " +$" completion)
8197 (setq completion (replace-match "" t t completion)))
8198 (insert completion)
8199 (if (get-buffer-window "*Completions*")
8200 (delete-window (get-buffer-window "*Completions*")))
8201 (if (assoc completion table)
8202 (if (eq type :todo) (insert " ")
8203 (if (memq type '(:tag :prop)) (insert ":"))))
8204 (if (and (equal type :opt) (assoc completion table))
8205 (message "%s" (substitute-command-keys
8206 "Press \\[org-complete] again to insert example settings"))))
8208 (message "Making completion list...")
8209 (let ((list (sort (all-completions pattern table confirm)
8210 'string<)))
8211 (with-output-to-temp-buffer "*Completions*"
8212 (condition-case nil
8213 ;; Protection needed for XEmacs and emacs 21
8214 (display-completion-list list pattern)
8215 (error (display-completion-list list)))))
8216 (message "Making completion list...%s" "done")))))))
8218 ;;;; TODO, DEADLINE, Comments
8220 (defun org-toggle-comment ()
8221 "Change the COMMENT state of an entry."
8222 (interactive)
8223 (save-excursion
8224 (org-back-to-heading)
8225 (let (case-fold-search)
8226 (if (looking-at (concat outline-regexp
8227 "\\( *\\<" org-comment-string "\\>[ \t]*\\)"))
8228 (replace-match "" t t nil 1)
8229 (if (looking-at outline-regexp)
8230 (progn
8231 (goto-char (match-end 0))
8232 (insert org-comment-string " ")))))))
8234 (defvar org-last-todo-state-is-todo nil
8235 "This is non-nil when the last TODO state change led to a TODO state.
8236 If the last change removed the TODO tag or switched to DONE, then
8237 this is nil.")
8239 (defvar org-setting-tags nil) ; dynamically skiped
8241 (defun org-parse-local-options (string var)
8242 "Parse STRING for startup setting relevant for variable VAR."
8243 (let ((rtn (symbol-value var))
8244 e opts)
8245 (save-match-data
8246 (if (or (not string) (not (string-match "\\S-" string)))
8248 (setq opts (delq nil (mapcar (lambda (x)
8249 (setq e (assoc x org-startup-options))
8250 (if (eq (nth 1 e) var) e nil))
8251 (org-split-string string "[ \t]+"))))
8252 (if (not opts)
8254 (setq rtn nil)
8255 (while (setq e (pop opts))
8256 (if (not (nth 3 e))
8257 (setq rtn (nth 2 e))
8258 (if (not (listp rtn)) (setq rtn nil))
8259 (push (nth 2 e) rtn)))
8260 rtn)))))
8262 (defvar org-blocker-hook nil
8263 "Hook for functions that are allowed to block a state change.
8265 Each function gets as its single argument a property list, see
8266 `org-trigger-hook' for more information about this list.
8268 If any of the functions in this hook returns nil, the state change
8269 is blocked.")
8271 (defvar org-trigger-hook nil
8272 "Hook for functions that are triggered by a state change.
8274 Each function gets as its single argument a property list with at least
8275 the following elements:
8277 (:type type-of-change :position pos-at-entry-start
8278 :from old-state :to new-state)
8280 Depending on the type, more properties may be present.
8282 This mechanism is currently implemented for:
8284 TODO state changes
8285 ------------------
8286 :type todo-state-change
8287 :from previous state (keyword as a string), or nil
8288 :to new state (keyword as a string), or nil")
8291 (defun org-todo (&optional arg)
8292 "Change the TODO state of an item.
8293 The state of an item is given by a keyword at the start of the heading,
8294 like
8295 *** TODO Write paper
8296 *** DONE Call mom
8298 The different keywords are specified in the variable `org-todo-keywords'.
8299 By default the available states are \"TODO\" and \"DONE\".
8300 So for this example: when the item starts with TODO, it is changed to DONE.
8301 When it starts with DONE, the DONE is removed. And when neither TODO nor
8302 DONE are present, add TODO at the beginning of the heading.
8304 With C-u prefix arg, use completion to determine the new state.
8305 With numeric prefix arg, switch to that state.
8307 For calling through lisp, arg is also interpreted in the following way:
8308 'none -> empty state
8309 \"\"(empty string) -> switch to empty state
8310 'done -> switch to DONE
8311 'nextset -> switch to the next set of keywords
8312 'previousset -> switch to the previous set of keywords
8313 \"WAITING\" -> switch to the specified keyword, but only if it
8314 really is a member of `org-todo-keywords'."
8315 (interactive "P")
8316 (save-excursion
8317 (catch 'exit
8318 (org-back-to-heading)
8319 (if (looking-at outline-regexp) (goto-char (1- (match-end 0))))
8320 (or (looking-at (concat " +" org-todo-regexp " *"))
8321 (looking-at " *"))
8322 (let* ((match-data (match-data))
8323 (startpos (point-at-bol))
8324 (logging (save-match-data (org-entry-get nil "LOGGING" t)))
8325 (org-log-done org-log-done)
8326 (org-log-repeat org-log-repeat)
8327 (org-todo-log-states org-todo-log-states)
8328 (this (match-string 1))
8329 (hl-pos (match-beginning 0))
8330 (head (org-get-todo-sequence-head this))
8331 (ass (assoc head org-todo-kwd-alist))
8332 (interpret (nth 1 ass))
8333 (done-word (nth 3 ass))
8334 (final-done-word (nth 4 ass))
8335 (last-state (or this ""))
8336 (completion-ignore-case t)
8337 (member (member this org-todo-keywords-1))
8338 (tail (cdr member))
8339 (state (cond
8340 ((and org-todo-key-trigger
8341 (or (and (equal arg '(4)) (eq org-use-fast-todo-selection 'prefix))
8342 (and (not arg) org-use-fast-todo-selection
8343 (not (eq org-use-fast-todo-selection 'prefix)))))
8344 ;; Use fast selection
8345 (org-fast-todo-selection))
8346 ((and (equal arg '(4))
8347 (or (not org-use-fast-todo-selection)
8348 (not org-todo-key-trigger)))
8349 ;; Read a state with completion
8350 (completing-read "State: " (mapcar (lambda(x) (list x))
8351 org-todo-keywords-1)
8352 nil t))
8353 ((eq arg 'right)
8354 (if this
8355 (if tail (car tail) nil)
8356 (car org-todo-keywords-1)))
8357 ((eq arg 'left)
8358 (if (equal member org-todo-keywords-1)
8360 (if this
8361 (nth (- (length org-todo-keywords-1) (length tail) 2)
8362 org-todo-keywords-1)
8363 (org-last org-todo-keywords-1))))
8364 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
8365 (setq arg nil))) ; hack to fall back to cycling
8366 (arg
8367 ;; user or caller requests a specific state
8368 (cond
8369 ((equal arg "") nil)
8370 ((eq arg 'none) nil)
8371 ((eq arg 'done) (or done-word (car org-done-keywords)))
8372 ((eq arg 'nextset)
8373 (or (car (cdr (member head org-todo-heads)))
8374 (car org-todo-heads)))
8375 ((eq arg 'previousset)
8376 (let ((org-todo-heads (reverse org-todo-heads)))
8377 (or (car (cdr (member head org-todo-heads)))
8378 (car org-todo-heads))))
8379 ((car (member arg org-todo-keywords-1)))
8380 ((nth (1- (prefix-numeric-value arg))
8381 org-todo-keywords-1))))
8382 ((null member) (or head (car org-todo-keywords-1)))
8383 ((equal this final-done-word) nil) ;; -> make empty
8384 ((null tail) nil) ;; -> first entry
8385 ((eq interpret 'sequence)
8386 (car tail))
8387 ((memq interpret '(type priority))
8388 (if (eq this-command last-command)
8389 (car tail)
8390 (if (> (length tail) 0)
8391 (or done-word (car org-done-keywords))
8392 nil)))
8393 (t nil)))
8394 (next (if state (concat " " state " ") " "))
8395 (change-plist (list :type 'todo-state-change :from this :to state
8396 :position startpos))
8397 dolog now-done-p)
8398 (when org-blocker-hook
8399 (unless (save-excursion
8400 (save-match-data
8401 (run-hook-with-args-until-failure
8402 'org-blocker-hook change-plist)))
8403 (if (interactive-p)
8404 (error "TODO state change from %s to %s blocked" this state)
8405 ;; fail silently
8406 (message "TODO state change from %s to %s blocked" this state)
8407 (throw 'exit nil))))
8408 (store-match-data match-data)
8409 (replace-match next t t)
8410 (unless (pos-visible-in-window-p hl-pos)
8411 (message "TODO state changed to %s" (org-trim next)))
8412 (unless head
8413 (setq head (org-get-todo-sequence-head state)
8414 ass (assoc head org-todo-kwd-alist)
8415 interpret (nth 1 ass)
8416 done-word (nth 3 ass)
8417 final-done-word (nth 4 ass)))
8418 (when (memq arg '(nextset previousset))
8419 (message "Keyword-Set %d/%d: %s"
8420 (- (length org-todo-sets) -1
8421 (length (memq (assoc state org-todo-sets) org-todo-sets)))
8422 (length org-todo-sets)
8423 (mapconcat 'identity (assoc state org-todo-sets) " ")))
8424 (setq org-last-todo-state-is-todo
8425 (not (member state org-done-keywords)))
8426 (setq now-done-p (and (member state org-done-keywords)
8427 (not (member this org-done-keywords))))
8428 (and logging (org-local-logging logging))
8429 (when (and (or org-todo-log-states org-log-done)
8430 (not (memq arg '(nextset previousset))))
8431 ;; we need to look at recording a time and note
8432 (setq dolog (or (nth 1 (assoc state org-todo-log-states))
8433 (nth 2 (assoc this org-todo-log-states))))
8434 (when (and state
8435 (member state org-not-done-keywords)
8436 (not (member this org-not-done-keywords)))
8437 ;; This is now a todo state and was not one before
8438 ;; If there was a CLOSED time stamp, get rid of it.
8439 (org-add-planning-info nil nil 'closed))
8440 (when (and now-done-p org-log-done)
8441 ;; It is now done, and it was not done before
8442 (org-add-planning-info 'closed (org-current-time))
8443 (if (and (not dolog) (eq 'note org-log-done))
8444 (org-add-log-setup 'done state 'findpos 'note)))
8445 (when (and state dolog)
8446 ;; This is a non-nil state, and we need to log it
8447 (org-add-log-setup 'state state 'findpos dolog)))
8448 ;; Fixup tag positioning
8449 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
8450 (run-hooks 'org-after-todo-state-change-hook)
8451 (if (and arg (not (member state org-done-keywords)))
8452 (setq head (org-get-todo-sequence-head state)))
8453 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
8454 ;; Do we need to trigger a repeat?
8455 (when now-done-p (org-auto-repeat-maybe state))
8456 ;; Fixup cursor location if close to the keyword
8457 (if (and (outline-on-heading-p)
8458 (not (bolp))
8459 (save-excursion (beginning-of-line 1)
8460 (looking-at org-todo-line-regexp))
8461 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
8462 (progn
8463 (goto-char (or (match-end 2) (match-end 1)))
8464 (just-one-space)))
8465 (when org-trigger-hook
8466 (save-excursion
8467 (run-hook-with-args 'org-trigger-hook change-plist)))))))
8469 (defun org-local-logging (value)
8470 "Get logging settings from a property VALUE."
8471 (let* (words w a)
8472 ;; directly set the variables, they are already local.
8473 (setq org-log-done nil
8474 org-log-repeat nil
8475 org-todo-log-states nil)
8476 (setq words (org-split-string value))
8477 (while (setq w (pop words))
8478 (cond
8479 ((setq a (assoc w org-startup-options))
8480 (and (member (nth 1 a) '(org-log-done org-log-repeat))
8481 (set (nth 1 a) (nth 2 a))))
8482 ((setq a (org-extract-log-state-settings w))
8483 (and (member (car a) org-todo-keywords-1)
8484 (push a org-todo-log-states)))))))
8486 (defun org-get-todo-sequence-head (kwd)
8487 "Return the head of the TODO sequence to which KWD belongs.
8488 If KWD is not set, check if there is a text property remembering the
8489 right sequence."
8490 (let (p)
8491 (cond
8492 ((not kwd)
8493 (or (get-text-property (point-at-bol) 'org-todo-head)
8494 (progn
8495 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
8496 nil (point-at-eol)))
8497 (get-text-property p 'org-todo-head))))
8498 ((not (member kwd org-todo-keywords-1))
8499 (car org-todo-keywords-1))
8500 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
8502 (defun org-fast-todo-selection ()
8503 "Fast TODO keyword selection with single keys.
8504 Returns the new TODO keyword, or nil if no state change should occur."
8505 (let* ((fulltable org-todo-key-alist)
8506 (done-keywords org-done-keywords) ;; needed for the faces.
8507 (maxlen (apply 'max (mapcar
8508 (lambda (x)
8509 (if (stringp (car x)) (string-width (car x)) 0))
8510 fulltable)))
8511 (expert nil)
8512 (fwidth (+ maxlen 3 1 3))
8513 (ncol (/ (- (window-width) 4) fwidth))
8514 tg cnt e c tbl
8515 groups ingroup)
8516 (save-window-excursion
8517 (if expert
8518 (set-buffer (get-buffer-create " *Org todo*"))
8519 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
8520 (erase-buffer)
8521 (org-set-local 'org-done-keywords done-keywords)
8522 (setq tbl fulltable cnt 0)
8523 (while (setq e (pop tbl))
8524 (cond
8525 ((equal e '(:startgroup))
8526 (push '() groups) (setq ingroup t)
8527 (when (not (= cnt 0))
8528 (setq cnt 0)
8529 (insert "\n"))
8530 (insert "{ "))
8531 ((equal e '(:endgroup))
8532 (setq ingroup nil cnt 0)
8533 (insert "}\n"))
8535 (setq tg (car e) c (cdr e))
8536 (if ingroup (push tg (car groups)))
8537 (setq tg (org-add-props tg nil 'face
8538 (org-get-todo-face tg)))
8539 (if (and (= cnt 0) (not ingroup)) (insert " "))
8540 (insert "[" c "] " tg (make-string
8541 (- fwidth 4 (length tg)) ?\ ))
8542 (when (= (setq cnt (1+ cnt)) ncol)
8543 (insert "\n")
8544 (if ingroup (insert " "))
8545 (setq cnt 0)))))
8546 (insert "\n")
8547 (goto-char (point-min))
8548 (if (and (not expert) (fboundp 'fit-window-to-buffer))
8549 (fit-window-to-buffer))
8550 (message "[a-z..]:Set [SPC]:clear")
8551 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
8552 (cond
8553 ((or (= c ?\C-g)
8554 (and (= c ?q) (not (rassoc c fulltable))))
8555 (setq quit-flag t))
8556 ((= c ?\ ) nil)
8557 ((setq e (rassoc c fulltable) tg (car e))
8559 (t (setq quit-flag t))))))
8561 (defun org-entry-is-todo-p ()
8562 (member (org-get-todo-state) org-not-done-keywords))
8564 (defun org-entry-is-done-p ()
8565 (member (org-get-todo-state) org-done-keywords))
8567 (defun org-get-todo-state ()
8568 (save-excursion
8569 (org-back-to-heading t)
8570 (and (looking-at org-todo-line-regexp)
8571 (match-end 2)
8572 (match-string 2))))
8574 (defun org-at-date-range-p (&optional inactive-ok)
8575 "Is the cursor inside a date range?"
8576 (interactive)
8577 (save-excursion
8578 (catch 'exit
8579 (let ((pos (point)))
8580 (skip-chars-backward "^[<\r\n")
8581 (skip-chars-backward "<[")
8582 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
8583 (>= (match-end 0) pos)
8584 (throw 'exit t))
8585 (skip-chars-backward "^<[\r\n")
8586 (skip-chars-backward "<[")
8587 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
8588 (>= (match-end 0) pos)
8589 (throw 'exit t)))
8590 nil)))
8592 (defun org-get-repeat ()
8593 "Check if tere is a deadline/schedule with repeater in this entry."
8594 (save-match-data
8595 (save-excursion
8596 (org-back-to-heading t)
8597 (if (re-search-forward
8598 org-repeat-re (save-excursion (outline-next-heading) (point)) t)
8599 (match-string 1)))))
8601 (defvar org-last-changed-timestamp)
8602 (defvar org-log-post-message)
8603 (defvar org-log-note-purpose)
8604 (defvar org-log-note-how)
8605 (defun org-auto-repeat-maybe (done-word)
8606 "Check if the current headline contains a repeated deadline/schedule.
8607 If yes, set TODO state back to what it was and change the base date
8608 of repeating deadline/scheduled time stamps to new date.
8609 This function is run automatically after each state change to a DONE state."
8610 ;; last-state is dynamically scoped into this function
8611 (let* ((repeat (org-get-repeat))
8612 (aa (assoc last-state org-todo-kwd-alist))
8613 (interpret (nth 1 aa))
8614 (head (nth 2 aa))
8615 (whata '(("d" . day) ("m" . month) ("y" . year)))
8616 (msg "Entry repeats: ")
8617 (org-log-done nil)
8618 (org-todo-log-states nil)
8619 (nshiftmax 10) (nshift 0)
8620 re type n what ts mb0 time)
8621 (when repeat
8622 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
8623 (org-todo (if (eq interpret 'type) last-state head))
8624 (when org-log-repeat
8625 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
8626 (memq 'org-add-log-note post-command-hook))
8627 ;; OK, we are already setup for some record
8628 (if (eq org-log-repeat 'note)
8629 ;; make sure we take a note, not only a time stamp
8630 (setq org-log-note-how 'note))
8631 ;; Set up for taking a record
8632 (org-add-log-setup 'state (or done-word (car org-done-keywords))
8633 'findpos org-log-repeat)))
8634 (org-back-to-heading t)
8635 (org-add-planning-info nil nil 'closed)
8636 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
8637 org-deadline-time-regexp "\\)\\|\\("
8638 org-ts-regexp "\\)"))
8639 (while (re-search-forward
8640 re (save-excursion (outline-next-heading) (point)) t)
8641 (setq type (if (match-end 1) org-scheduled-string
8642 (if (match-end 3) org-deadline-string "Plain:"))
8643 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0)))
8644 mb0 (match-beginning 0))
8645 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts)
8646 (setq n (string-to-number (match-string 2 ts))
8647 what (match-string 3 ts))
8648 (if (equal what "w") (setq n (* n 7) what "d"))
8649 ;; Preparation, see if we need to modify the start date for the change
8650 (when (match-end 1)
8651 (setq time (save-match-data (org-time-string-to-time ts)))
8652 (cond
8653 ((equal (match-string 1 ts) ".")
8654 ;; Shift starting date to today
8655 (org-timestamp-change
8656 (- (time-to-days (current-time)) (time-to-days time))
8657 'day))
8658 ((equal (match-string 1 ts) "+")
8659 (while (or (= nshift 0)
8660 (<= (time-to-days time) (time-to-days (current-time))))
8661 (when (= (incf nshift) nshiftmax)
8662 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
8663 (error "Abort")))
8664 (org-timestamp-change n (cdr (assoc what whata)))
8665 (org-at-timestamp-p t)
8666 (setq ts (match-string 1))
8667 (setq time (save-match-data (org-time-string-to-time ts))))
8668 (org-timestamp-change (- n) (cdr (assoc what whata)))
8669 ;; rematch, so that we have everything in place for the real shift
8670 (org-at-timestamp-p t)
8671 (setq ts (match-string 1))
8672 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts))))
8673 (org-timestamp-change n (cdr (assoc what whata)))
8674 (setq msg (concat msg type org-last-changed-timestamp " "))))
8675 (setq org-log-post-message msg)
8676 (message "%s" msg))))
8678 (defun org-show-todo-tree (arg)
8679 "Make a compact tree which shows all headlines marked with TODO.
8680 The tree will show the lines where the regexp matches, and all higher
8681 headlines above the match.
8682 With a \\[universal-argument] prefix, also show the DONE entries.
8683 With a numeric prefix N, construct a sparse tree for the Nth element
8684 of `org-todo-keywords-1'."
8685 (interactive "P")
8686 (let ((case-fold-search nil)
8687 (kwd-re
8688 (cond ((null arg) org-not-done-regexp)
8689 ((equal arg '(4))
8690 (let ((kwd (completing-read "Keyword (or KWD1|KWD2|...): "
8691 (mapcar 'list org-todo-keywords-1))))
8692 (concat "\\("
8693 (mapconcat 'identity (org-split-string kwd "|") "\\|")
8694 "\\)\\>")))
8695 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
8696 (regexp-quote (nth (1- (prefix-numeric-value arg))
8697 org-todo-keywords-1)))
8698 (t (error "Invalid prefix argument: %s" arg)))))
8699 (message "%d TODO entries found"
8700 (org-occur (concat "^" outline-regexp " *" kwd-re )))))
8702 (defun org-deadline (&optional remove)
8703 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
8704 With argument REMOVE, remove any deadline from the item."
8705 (interactive "P")
8706 (if remove
8707 (progn
8708 (org-remove-timestamp-with-keyword org-deadline-string)
8709 (message "Item no longer has a deadline."))
8710 (org-add-planning-info 'deadline nil 'closed)))
8712 (defun org-schedule (&optional remove)
8713 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
8714 With argument REMOVE, remove any scheduling date from the item."
8715 (interactive "P")
8716 (if remove
8717 (progn
8718 (org-remove-timestamp-with-keyword org-scheduled-string)
8719 (message "Item is no longer scheduled."))
8720 (org-add-planning-info 'scheduled nil 'closed)))
8722 (defun org-remove-timestamp-with-keyword (keyword)
8723 "Remove all time stamps with KEYWORD in the current entry."
8724 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
8725 beg)
8726 (save-excursion
8727 (org-back-to-heading t)
8728 (setq beg (point))
8729 (org-end-of-subtree t t)
8730 (while (re-search-backward re beg t)
8731 (replace-match "")
8732 (unless (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
8733 (delete-region (point-at-bol) (min (1+ (point)) (point-max))))))))
8735 (defun org-add-planning-info (what &optional time &rest remove)
8736 "Insert new timestamp with keyword in the line directly after the headline.
8737 WHAT indicates what kind of time stamp to add. TIME indicated the time to use.
8738 If non is given, the user is prompted for a date.
8739 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
8740 be removed."
8741 (interactive)
8742 (let (org-time-was-given org-end-time-was-given ts
8743 end default-time default-input)
8745 (when (and (not time) (memq what '(scheduled deadline)))
8746 ;; Try to get a default date/time from existing timestamp
8747 (save-excursion
8748 (org-back-to-heading t)
8749 (setq end (save-excursion (outline-next-heading) (point)))
8750 (when (re-search-forward (if (eq what 'scheduled)
8751 org-scheduled-time-regexp
8752 org-deadline-time-regexp)
8753 end t)
8754 (setq ts (match-string 1)
8755 default-time
8756 (apply 'encode-time (org-parse-time-string ts))
8757 default-input (and ts (org-get-compact-tod ts))))))
8758 (when what
8759 ;; If necessary, get the time from the user
8760 (setq time (or time (org-read-date nil 'to-time nil nil
8761 default-time default-input))))
8763 (when (and org-insert-labeled-timestamps-at-point
8764 (member what '(scheduled deadline)))
8765 (insert
8766 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
8767 (org-insert-time-stamp time org-time-was-given
8768 nil nil nil (list org-end-time-was-given))
8769 (setq what nil))
8770 (save-excursion
8771 (save-restriction
8772 (let (col list elt ts buffer-invisibility-spec)
8773 (org-back-to-heading t)
8774 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
8775 (goto-char (match-end 1))
8776 (setq col (current-column))
8777 (goto-char (match-end 0))
8778 (if (eobp) (insert "\n") (forward-char 1))
8779 (if (and (not (looking-at outline-regexp))
8780 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
8781 "[^\r\n]*"))
8782 (not (equal (match-string 1) org-clock-string)))
8783 (narrow-to-region (match-beginning 0) (match-end 0))
8784 (insert-before-markers "\n")
8785 (backward-char 1)
8786 (narrow-to-region (point) (point))
8787 (indent-to-column col))
8788 ;; Check if we have to remove something.
8789 (setq list (cons what remove))
8790 (while list
8791 (setq elt (pop list))
8792 (goto-char (point-min))
8793 (when (or (and (eq elt 'scheduled)
8794 (re-search-forward org-scheduled-time-regexp nil t))
8795 (and (eq elt 'deadline)
8796 (re-search-forward org-deadline-time-regexp nil t))
8797 (and (eq elt 'closed)
8798 (re-search-forward org-closed-time-regexp nil t)))
8799 (replace-match "")
8800 (if (looking-at "--+<[^>]+>") (replace-match ""))
8801 (if (looking-at " +") (replace-match ""))))
8802 (goto-char (point-max))
8803 (when what
8804 (insert
8805 (if (not (equal (char-before) ?\ )) " " "")
8806 (cond ((eq what 'scheduled) org-scheduled-string)
8807 ((eq what 'deadline) org-deadline-string)
8808 ((eq what 'closed) org-closed-string))
8809 " ")
8810 (setq ts (org-insert-time-stamp
8811 time
8812 (or org-time-was-given
8813 (and (eq what 'closed) org-log-done-with-time))
8814 (eq what 'closed)
8815 nil nil (list org-end-time-was-given)))
8816 (end-of-line 1))
8817 (goto-char (point-min))
8818 (widen)
8819 (if (looking-at "[ \t]+\r?\n")
8820 (replace-match ""))
8821 ts)))))
8823 (defvar org-log-note-marker (make-marker))
8824 (defvar org-log-note-purpose nil)
8825 (defvar org-log-note-state nil)
8826 (defvar org-log-note-how nil)
8827 (defvar org-log-note-window-configuration nil)
8828 (defvar org-log-note-return-to (make-marker))
8829 (defvar org-log-post-message nil
8830 "Message to be displayed after a log note has been stored.
8831 The auto-repeater uses this.")
8833 (defun org-add-note ()
8834 "Add a note to the current entry.
8835 This is done in the same way as adding a state change note."
8836 (interactive)
8837 (org-add-log-setup 'note nil t nil))
8839 (defun org-add-log-setup (&optional purpose state findpos how)
8840 "Set up the post command hook to take a note.
8841 If this is about to TODO state change, the new state is expected in STATE.
8842 When FINDPOS is non-nil, find the correct position for the note in
8843 the current entry. If not, assume that it can be inserted at point."
8844 (save-excursion
8845 (when findpos
8846 (org-back-to-heading t)
8847 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"
8848 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
8849 "[^\r\n]*\\)?"))
8850 (goto-char (match-end 0))
8851 (unless org-log-states-order-reversed
8852 (and (= (char-after) ?\n) (forward-char 1))
8853 (org-skip-over-state-notes)
8854 (skip-chars-backward " \t\n\r")))
8855 (move-marker org-log-note-marker (point))
8856 (setq org-log-note-purpose purpose
8857 org-log-note-state state
8858 org-log-note-how how)
8859 (add-hook 'post-command-hook 'org-add-log-note 'append)))
8861 (defun org-skip-over-state-notes ()
8862 "Skip past the list of State notes in an entry."
8863 (if (looking-at "\n[ \t]*- State") (forward-char 1))
8864 (while (looking-at "[ \t]*- State")
8865 (condition-case nil
8866 (org-next-item)
8867 (error (org-end-of-item)))))
8869 (defun org-add-log-note (&optional purpose)
8870 "Pop up a window for taking a note, and add this note later at point."
8871 (remove-hook 'post-command-hook 'org-add-log-note)
8872 (setq org-log-note-window-configuration (current-window-configuration))
8873 (delete-other-windows)
8874 (move-marker org-log-note-return-to (point))
8875 (switch-to-buffer (marker-buffer org-log-note-marker))
8876 (goto-char org-log-note-marker)
8877 (org-switch-to-buffer-other-window "*Org Note*")
8878 (erase-buffer)
8879 (if (memq org-log-note-how '(time state))
8880 (org-store-log-note)
8881 (let ((org-inhibit-startup t)) (org-mode))
8882 (insert (format "# Insert note for %s.
8883 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
8884 (cond
8885 ((eq org-log-note-purpose 'clock-out) "stopped clock")
8886 ((eq org-log-note-purpose 'done) "closed todo item")
8887 ((eq org-log-note-purpose 'state)
8888 (format "state change to \"%s\"" org-log-note-state))
8889 ((eq org-log-note-purpose 'note)
8890 "this entry")
8891 (t (error "This should not happen")))))
8892 (org-set-local 'org-finish-function 'org-store-log-note)))
8894 (defvar org-note-abort nil) ; dynamically scoped
8895 (defun org-store-log-note ()
8896 "Finish taking a log note, and insert it to where it belongs."
8897 (let ((txt (buffer-string))
8898 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
8899 lines ind)
8900 (kill-buffer (current-buffer))
8901 (while (string-match "\\`#.*\n[ \t\n]*" txt)
8902 (setq txt (replace-match "" t t txt)))
8903 (if (string-match "\\s-+\\'" txt)
8904 (setq txt (replace-match "" t t txt)))
8905 (setq lines (org-split-string txt "\n"))
8906 (when (and note (string-match "\\S-" note))
8907 (setq note
8908 (org-replace-escapes
8909 note
8910 (list (cons "%u" (user-login-name))
8911 (cons "%U" user-full-name)
8912 (cons "%t" (format-time-string
8913 (org-time-stamp-format 'long 'inactive)
8914 (current-time)))
8915 (cons "%s" (if org-log-note-state
8916 (concat "\"" org-log-note-state "\"")
8917 "")))))
8918 (if lines (setq note (concat note " \\\\")))
8919 (push note lines))
8920 (when (or current-prefix-arg org-note-abort) (setq lines nil))
8921 (when lines
8922 (save-excursion
8923 (set-buffer (marker-buffer org-log-note-marker))
8924 (save-excursion
8925 (goto-char org-log-note-marker)
8926 (move-marker org-log-note-marker nil)
8927 (end-of-line 1)
8928 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
8929 (indent-relative nil)
8930 (insert "- " (pop lines))
8931 (org-indent-line-function)
8932 (beginning-of-line 1)
8933 (looking-at "[ \t]*")
8934 (setq ind (concat (match-string 0) " "))
8935 (end-of-line 1)
8936 (while lines (insert "\n" ind (pop lines)))))))
8937 (set-window-configuration org-log-note-window-configuration)
8938 (with-current-buffer (marker-buffer org-log-note-return-to)
8939 (goto-char org-log-note-return-to))
8940 (move-marker org-log-note-return-to nil)
8941 (and org-log-post-message (message "%s" org-log-post-message)))
8943 (defun org-sparse-tree (&optional arg)
8944 "Create a sparse tree, prompt for the details.
8945 This command can create sparse trees. You first need to select the type
8946 of match used to create the tree:
8948 t Show entries with a specific TODO keyword.
8949 T Show entries selected by a tags match.
8950 p Enter a property name and its value (both with completion on existing
8951 names/values) and show entries with that property.
8952 r Show entries matching a regular expression
8953 d Show deadlines due within `org-deadline-warning-days'."
8954 (interactive "P")
8955 (let (ans kwd value)
8956 (message "Sparse tree: [/]regexp [t]odo-kwd [T]ag [p]roperty [d]eadlines [b]efore-date")
8957 (setq ans (read-char-exclusive))
8958 (cond
8959 ((equal ans ?d)
8960 (call-interactively 'org-check-deadlines))
8961 ((equal ans ?b)
8962 (call-interactively 'org-check-before-date))
8963 ((equal ans ?t)
8964 (org-show-todo-tree '(4)))
8965 ((equal ans ?T)
8966 (call-interactively 'org-tags-sparse-tree))
8967 ((member ans '(?p ?P))
8968 (setq kwd (completing-read "Property: "
8969 (mapcar 'list (org-buffer-property-keys))))
8970 (setq value (completing-read "Value: "
8971 (mapcar 'list (org-property-values kwd))))
8972 (unless (string-match "\\`{.*}\\'" value)
8973 (setq value (concat "\"" value "\"")))
8974 (org-tags-sparse-tree arg (concat kwd "=" value)))
8975 ((member ans '(?r ?R ?/))
8976 (call-interactively 'org-occur))
8977 (t (error "No such sparse tree command \"%c\"" ans)))))
8979 (defvar org-occur-highlights nil
8980 "List of overlays used for occur matches.")
8981 (make-variable-buffer-local 'org-occur-highlights)
8982 (defvar org-occur-parameters nil
8983 "Parameters of the active org-occur calls.
8984 This is a list, each call to org-occur pushes as cons cell,
8985 containing the regular expression and the callback, onto the list.
8986 The list can contain several entries if `org-occur' has been called
8987 several time with the KEEP-PREVIOUS argument. Otherwise, this list
8988 will only contain one set of parameters. When the highlights are
8989 removed (for example with `C-c C-c', or with the next edit (depending
8990 on `org-remove-highlights-with-change'), this variable is emptied
8991 as well.")
8992 (make-variable-buffer-local 'org-occur-parameters)
8994 (defun org-occur (regexp &optional keep-previous callback)
8995 "Make a compact tree which shows all matches of REGEXP.
8996 The tree will show the lines where the regexp matches, and all higher
8997 headlines above the match. It will also show the heading after the match,
8998 to make sure editing the matching entry is easy.
8999 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
9000 call to `org-occur' will be kept, to allow stacking of calls to this
9001 command.
9002 If CALLBACK is non-nil, it is a function which is called to confirm
9003 that the match should indeed be shown."
9004 (interactive "sRegexp: \nP")
9005 (unless keep-previous
9006 (org-remove-occur-highlights nil nil t))
9007 (push (cons regexp callback) org-occur-parameters)
9008 (let ((cnt 0))
9009 (save-excursion
9010 (goto-char (point-min))
9011 (if (or (not keep-previous) ; do not want to keep
9012 (not org-occur-highlights)) ; no previous matches
9013 ;; hide everything
9014 (org-overview))
9015 (while (re-search-forward regexp nil t)
9016 (when (or (not callback)
9017 (save-match-data (funcall callback)))
9018 (setq cnt (1+ cnt))
9019 (when org-highlight-sparse-tree-matches
9020 (org-highlight-new-match (match-beginning 0) (match-end 0)))
9021 (org-show-context 'occur-tree))))
9022 (when org-remove-highlights-with-change
9023 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
9024 nil 'local))
9025 (unless org-sparse-tree-open-archived-trees
9026 (org-hide-archived-subtrees (point-min) (point-max)))
9027 (run-hooks 'org-occur-hook)
9028 (if (interactive-p)
9029 (message "%d match(es) for regexp %s" cnt regexp))
9030 cnt))
9032 (defun org-show-context (&optional key)
9033 "Make sure point and context and visible.
9034 How much context is shown depends upon the variables
9035 `org-show-hierarchy-above', `org-show-following-heading'. and
9036 `org-show-siblings'."
9037 (let ((heading-p (org-on-heading-p t))
9038 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
9039 (following-p (org-get-alist-option org-show-following-heading key))
9040 (entry-p (org-get-alist-option org-show-entry-below key))
9041 (siblings-p (org-get-alist-option org-show-siblings key)))
9042 (catch 'exit
9043 ;; Show heading or entry text
9044 (if (and heading-p (not entry-p))
9045 (org-flag-heading nil) ; only show the heading
9046 (and (or entry-p (org-invisible-p) (org-invisible-p2))
9047 (org-show-hidden-entry))) ; show entire entry
9048 (when following-p
9049 ;; Show next sibling, or heading below text
9050 (save-excursion
9051 (and (if heading-p (org-goto-sibling) (outline-next-heading))
9052 (org-flag-heading nil))))
9053 (when siblings-p (org-show-siblings))
9054 (when hierarchy-p
9055 ;; show all higher headings, possibly with siblings
9056 (save-excursion
9057 (while (and (condition-case nil
9058 (progn (org-up-heading-all 1) t)
9059 (error nil))
9060 (not (bobp)))
9061 (org-flag-heading nil)
9062 (when siblings-p (org-show-siblings))))))))
9064 (defun org-reveal (&optional siblings)
9065 "Show current entry, hierarchy above it, and the following headline.
9066 This can be used to show a consistent set of context around locations
9067 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
9068 not t for the search context.
9070 With optional argument SIBLINGS, on each level of the hierarchy all
9071 siblings are shown. This repairs the tree structure to what it would
9072 look like when opened with hierarchical calls to `org-cycle'."
9073 (interactive "P")
9074 (let ((org-show-hierarchy-above t)
9075 (org-show-following-heading t)
9076 (org-show-siblings (if siblings t org-show-siblings)))
9077 (org-show-context nil)))
9079 (defun org-highlight-new-match (beg end)
9080 "Highlight from BEG to END and mark the highlight is an occur headline."
9081 (let ((ov (org-make-overlay beg end)))
9082 (org-overlay-put ov 'face 'secondary-selection)
9083 (push ov org-occur-highlights)))
9085 (defun org-remove-occur-highlights (&optional beg end noremove)
9086 "Remove the occur highlights from the buffer.
9087 BEG and END are ignored. If NOREMOVE is nil, remove this function
9088 from the `before-change-functions' in the current buffer."
9089 (interactive)
9090 (unless org-inhibit-highlight-removal
9091 (mapc 'org-delete-overlay org-occur-highlights)
9092 (setq org-occur-highlights nil)
9093 (setq org-occur-parameters nil)
9094 (unless noremove
9095 (remove-hook 'before-change-functions
9096 'org-remove-occur-highlights 'local))))
9098 ;;;; Priorities
9100 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
9101 "Regular expression matching the priority indicator.")
9103 (defvar org-remove-priority-next-time nil)
9105 (defun org-priority-up ()
9106 "Increase the priority of the current item."
9107 (interactive)
9108 (org-priority 'up))
9110 (defun org-priority-down ()
9111 "Decrease the priority of the current item."
9112 (interactive)
9113 (org-priority 'down))
9115 (defun org-priority (&optional action)
9116 "Change the priority of an item by ARG.
9117 ACTION can be `set', `up', `down', or a character."
9118 (interactive)
9119 (setq action (or action 'set))
9120 (let (current new news have remove)
9121 (save-excursion
9122 (org-back-to-heading)
9123 (if (looking-at org-priority-regexp)
9124 (setq current (string-to-char (match-string 2))
9125 have t)
9126 (setq current org-default-priority))
9127 (cond
9128 ((or (eq action 'set) (integerp action))
9129 (if (integerp action)
9130 (setq new action)
9131 (message "Priority %c-%c, SPC to remove: " org-highest-priority org-lowest-priority)
9132 (setq new (read-char-exclusive)))
9133 (if (and (= (upcase org-highest-priority) org-highest-priority)
9134 (= (upcase org-lowest-priority) org-lowest-priority))
9135 (setq new (upcase new)))
9136 (cond ((equal new ?\ ) (setq remove t))
9137 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
9138 (error "Priority must be between `%c' and `%c'"
9139 org-highest-priority org-lowest-priority))))
9140 ((eq action 'up)
9141 (if (and (not have) (eq last-command this-command))
9142 (setq new org-lowest-priority)
9143 (setq new (if (and org-priority-start-cycle-with-default (not have))
9144 org-default-priority (1- current)))))
9145 ((eq action 'down)
9146 (if (and (not have) (eq last-command this-command))
9147 (setq new org-highest-priority)
9148 (setq new (if (and org-priority-start-cycle-with-default (not have))
9149 org-default-priority (1+ current)))))
9150 (t (error "Invalid action")))
9151 (if (or (< (upcase new) org-highest-priority)
9152 (> (upcase new) org-lowest-priority))
9153 (setq remove t))
9154 (setq news (format "%c" new))
9155 (if have
9156 (if remove
9157 (replace-match "" t t nil 1)
9158 (replace-match news t t nil 2))
9159 (if remove
9160 (error "No priority cookie found in line")
9161 (looking-at org-todo-line-regexp)
9162 (if (match-end 2)
9163 (progn
9164 (goto-char (match-end 2))
9165 (insert " [#" news "]"))
9166 (goto-char (match-beginning 3))
9167 (insert "[#" news "] ")))))
9168 (org-preserve-lc (org-set-tags nil 'align))
9169 (if remove
9170 (message "Priority removed")
9171 (message "Priority of current item set to %s" news))))
9174 (defun org-get-priority (s)
9175 "Find priority cookie and return priority."
9176 (save-match-data
9177 (if (not (string-match org-priority-regexp s))
9178 (* 1000 (- org-lowest-priority org-default-priority))
9179 (* 1000 (- org-lowest-priority
9180 (string-to-char (match-string 2 s)))))))
9182 ;;;; Tags
9184 (defun org-scan-tags (action matcher &optional todo-only)
9185 "Scan headline tags with inheritance and produce output ACTION.
9186 ACTION can be `sparse-tree' or `agenda'. MATCHER is a Lisp form to be
9187 evaluated, testing if a given set of tags qualifies a headline for
9188 inclusion. When TODO-ONLY is non-nil, only lines with a TODO keyword
9189 are included in the output."
9190 (let* ((re (concat "[\n\r]" outline-regexp " *\\(\\<\\("
9191 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
9192 (org-re
9193 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*$")))
9194 (props (list 'face nil
9195 'done-face 'org-done
9196 'undone-face nil
9197 'mouse-face 'highlight
9198 'org-not-done-regexp org-not-done-regexp
9199 'org-todo-regexp org-todo-regexp
9200 'keymap org-agenda-keymap
9201 'help-echo
9202 (format "mouse-2 or RET jump to org file %s"
9203 (abbreviate-file-name
9204 (or (buffer-file-name (buffer-base-buffer))
9205 (buffer-name (buffer-base-buffer)))))))
9206 (case-fold-search nil)
9207 lspos
9208 tags tags-list tags-alist (llast 0) rtn level category i txt
9209 todo marker entry priority)
9210 (save-excursion
9211 (goto-char (point-min))
9212 (when (eq action 'sparse-tree)
9213 (org-overview)
9214 (org-remove-occur-highlights))
9215 (while (re-search-forward re nil t)
9216 (catch :skip
9217 (setq todo (if (match-end 1) (match-string 2))
9218 tags (if (match-end 4) (match-string 4)))
9219 (goto-char (setq lspos (1+ (match-beginning 0))))
9220 (setq level (org-reduced-level (funcall outline-level))
9221 category (org-get-category))
9222 (setq i llast llast level)
9223 ;; remove tag lists from same and sublevels
9224 (while (>= i level)
9225 (when (setq entry (assoc i tags-alist))
9226 (setq tags-alist (delete entry tags-alist)))
9227 (setq i (1- i)))
9228 ;; add the next tags
9229 (when tags
9230 (setq tags (mapcar 'downcase (org-split-string tags ":"))
9231 tags-alist
9232 (cons (cons level tags) tags-alist)))
9233 ;; compile tags for current headline
9234 (setq tags-list
9235 (if org-use-tag-inheritance
9236 (apply 'append (mapcar 'cdr tags-alist))
9237 tags))
9238 (when (and tags org-use-tag-inheritance
9239 (not (eq t org-use-tag-inheritance)))
9240 ;; selective inheritance, remove uninherited ones
9241 (setcdr (car tags-alist)
9242 (org-remove-uniherited-tags (cdar tags-alist))))
9243 (when (and (or (not todo-only) (member todo org-not-done-keywords))
9244 (eval matcher)
9245 (or (not org-agenda-skip-archived-trees)
9246 (not (member org-archive-tag tags-list))))
9247 (and (eq action 'agenda) (org-agenda-skip))
9248 ;; list this headline
9250 (if (eq action 'sparse-tree)
9251 (progn
9252 (and org-highlight-sparse-tree-matches
9253 (org-get-heading) (match-end 0)
9254 (org-highlight-new-match
9255 (match-beginning 0) (match-beginning 1)))
9256 (org-show-context 'tags-tree))
9257 (setq txt (org-format-agenda-item
9259 (concat
9260 (if org-tags-match-list-sublevels
9261 (make-string (1- level) ?.) "")
9262 (org-get-heading))
9263 category tags-list)
9264 priority (org-get-priority txt))
9265 (goto-char lspos)
9266 (setq marker (org-agenda-new-marker))
9267 (org-add-props txt props
9268 'org-marker marker 'org-hd-marker marker 'org-category category
9269 'priority priority 'type "tagsmatch")
9270 (push txt rtn))
9271 ;; if we are to skip sublevels, jump to end of subtree
9272 (or org-tags-match-list-sublevels (org-end-of-subtree t))))))
9273 (when (and (eq action 'sparse-tree)
9274 (not org-sparse-tree-open-archived-trees))
9275 (org-hide-archived-subtrees (point-min) (point-max)))
9276 (nreverse rtn)))
9278 (defun org-remove-uniherited-tags (tags)
9279 "Remove all tags that are not inherited from the list TAGS."
9280 (cond
9281 ((eq org-use-tag-inheritance t) tags)
9282 ((not org-use-tag-inheritance) nil)
9283 ((stringp org-use-tag-inheritance)
9284 (delq nil (mapcar
9285 (lambda (x) (if (string-match org-use-tag-inheritance x) x nil))
9286 tags)))
9287 ((listp org-use-tag-inheritance)
9288 (org-delete-all org-use-tag-inheritance tags))))
9290 (defvar todo-only) ;; dynamically scoped
9292 (defun org-tags-sparse-tree (&optional todo-only match)
9293 "Create a sparse tree according to tags string MATCH.
9294 MATCH can contain positive and negative selection of tags, like
9295 \"+WORK+URGENT-WITHBOSS\".
9296 If optional argument TODO_ONLY is non-nil, only select lines that are
9297 also TODO lines."
9298 (interactive "P")
9299 (org-prepare-agenda-buffers (list (current-buffer)))
9300 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
9302 (defvar org-cached-props nil)
9303 (defun org-cached-entry-get (pom property)
9304 (if (or (eq t org-use-property-inheritance)
9305 (and (stringp org-use-property-inheritance)
9306 (string-match org-use-property-inheritance property))
9307 (and (listp org-use-property-inheritance)
9308 (member property org-use-property-inheritance)))
9309 ;; Caching is not possible, check it directly
9310 (org-entry-get pom property 'inherit)
9311 ;; Get all properties, so that we can do complicated checks easily
9312 (cdr (assoc property (or org-cached-props
9313 (setq org-cached-props
9314 (org-entry-properties pom)))))))
9316 (defun org-global-tags-completion-table (&optional files)
9317 "Return the list of all tags in all agenda buffer/files."
9318 (save-excursion
9319 (org-uniquify
9320 (delq nil
9321 (apply 'append
9322 (mapcar
9323 (lambda (file)
9324 (set-buffer (find-file-noselect file))
9325 (append (org-get-buffer-tags)
9326 (mapcar (lambda (x) (if (stringp (car-safe x))
9327 (list (car-safe x)) nil))
9328 org-tag-alist)))
9329 (if (and files (car files))
9330 files
9331 (org-agenda-files))))))))
9333 (defun org-make-tags-matcher (match)
9334 "Create the TAGS//TODO matcher form for the selection string MATCH."
9335 ;; todo-only is scoped dynamically into this function, and the function
9336 ;; may change it it the matcher asksk for it.
9337 (unless match
9338 ;; Get a new match request, with completion
9339 (let ((org-last-tags-completion-table
9340 (org-global-tags-completion-table)))
9341 (setq match (completing-read
9342 "Match: " 'org-tags-completion-function nil nil nil
9343 'org-tags-history))))
9345 ;; Parse the string and create a lisp form
9346 (let ((match0 match)
9347 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL=\\([0-9]+\\)\\|\\([[:alnum:]_]+\\)=\\({[^}]+}\\|\"[^\"]*\"\\)\\|[[:alnum:]_@]+\\)"))
9348 minus tag mm
9349 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
9350 orterms term orlist re-p level-p prop-p pn pv cat-p gv)
9351 (if (string-match "/+" match)
9352 ;; match contains also a todo-matching request
9353 (progn
9354 (setq tagsmatch (substring match 0 (match-beginning 0))
9355 todomatch (substring match (match-end 0)))
9356 (if (string-match "^!" todomatch)
9357 (setq todo-only t todomatch (substring todomatch 1)))
9358 (if (string-match "^\\s-*$" todomatch)
9359 (setq todomatch nil)))
9360 ;; only matching tags
9361 (setq tagsmatch match todomatch nil))
9363 ;; Make the tags matcher
9364 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
9365 (setq tagsmatcher t)
9366 (setq orterms (org-split-string tagsmatch "|") orlist nil)
9367 (while (setq term (pop orterms))
9368 (while (and (equal (substring term -1) "\\") orterms)
9369 (setq term (concat term "|" (pop orterms)))) ; repair bad split
9370 (while (string-match re term)
9371 (setq minus (and (match-end 1)
9372 (equal (match-string 1 term) "-"))
9373 tag (match-string 2 term)
9374 re-p (equal (string-to-char tag) ?{)
9375 level-p (match-end 3)
9376 prop-p (match-end 4)
9377 mm (cond
9378 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
9379 (level-p `(= level ,(string-to-number
9380 (match-string 3 term))))
9381 (prop-p
9382 (setq pn (match-string 4 term)
9383 pv (match-string 5 term)
9384 cat-p (equal pn "CATEGORY")
9385 re-p (equal (string-to-char pv) ?{)
9386 pv (substring pv 1 -1))
9387 (if (equal pn "CATEGORY")
9388 (setq gv '(get-text-property (point) 'org-category))
9389 (setq gv `(org-cached-entry-get nil ,pn)))
9390 (if re-p
9391 `(string-match ,pv (or ,gv ""))
9392 `(equal ,pv (or ,gv ""))))
9393 (t `(member ,(downcase tag) tags-list)))
9394 mm (if minus (list 'not mm) mm)
9395 term (substring term (match-end 0)))
9396 (push mm tagsmatcher))
9397 (push (if (> (length tagsmatcher) 1)
9398 (cons 'and tagsmatcher)
9399 (car tagsmatcher))
9400 orlist)
9401 (setq tagsmatcher nil))
9402 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
9403 (setq tagsmatcher
9404 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
9406 ;; Make the todo matcher
9407 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
9408 (setq todomatcher t)
9409 (setq orterms (org-split-string todomatch "|") orlist nil)
9410 (while (setq term (pop orterms))
9411 (while (string-match re term)
9412 (setq minus (and (match-end 1)
9413 (equal (match-string 1 term) "-"))
9414 kwd (match-string 2 term)
9415 re-p (equal (string-to-char kwd) ?{)
9416 term (substring term (match-end 0))
9417 mm (if re-p
9418 `(string-match ,(substring kwd 1 -1) todo)
9419 (list 'equal 'todo kwd))
9420 mm (if minus (list 'not mm) mm))
9421 (push mm todomatcher))
9422 (push (if (> (length todomatcher) 1)
9423 (cons 'and todomatcher)
9424 (car todomatcher))
9425 orlist)
9426 (setq todomatcher nil))
9427 (setq todomatcher (if (> (length orlist) 1)
9428 (cons 'or orlist) (car orlist))))
9430 ;; Return the string and lisp forms of the matcher
9431 (setq matcher (if todomatcher
9432 (list 'and tagsmatcher todomatcher)
9433 tagsmatcher))
9434 (cons match0 matcher)))
9436 (defun org-match-any-p (re list)
9437 "Does re match any element of list?"
9438 (setq list (mapcar (lambda (x) (string-match re x)) list))
9439 (delq nil list))
9441 (defvar org-add-colon-after-tag-completion nil) ;; dynamically skoped param
9442 (defvar org-tags-overlay (org-make-overlay 1 1))
9443 (org-detach-overlay org-tags-overlay)
9445 (defun org-get-tags-at (&optional pos)
9446 "Get a list of all headline tags applicable at POS.
9447 POS defaults to point. If tags are inherited, the list contains
9448 the targets in the same sequence as the headlines appear, i.e.
9449 sthe tags of the current headline come last."
9450 (interactive)
9451 (let (tags ltags lastpos parent)
9452 (save-excursion
9453 (save-restriction
9454 (widen)
9455 (goto-char (or pos (point)))
9456 (save-match-data
9457 (condition-case nil
9458 (progn
9459 (org-back-to-heading t)
9460 (while (not (equal lastpos (point)))
9461 (setq lastpos (point))
9462 (when (looking-at (org-re "[^\r\n]+?:\\([[:alnum:]_@:]+\\):[ \t]*$"))
9463 (setq ltags (org-split-string
9464 (org-match-string-no-properties 1) ":"))
9465 (setq tags (append (org-remove-uniherited-tags ltags)
9466 tags)))
9467 (or org-use-tag-inheritance (error ""))
9468 (org-up-heading-all 1)
9469 (setq parent t)))
9470 (error nil))))
9471 tags)))
9473 (defun org-align-tags-here (to-col)
9474 ;; Assumes that this is a headline
9475 (let ((pos (point)) (col (current-column)) tags)
9476 (beginning-of-line 1)
9477 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
9478 (< pos (match-beginning 2)))
9479 (progn
9480 (setq tags (match-string 2))
9481 (goto-char (match-beginning 1))
9482 (insert " ")
9483 (delete-region (point) (1+ (match-end 0)))
9484 (backward-char 1)
9485 (move-to-column
9486 (max (1+ (current-column))
9487 (1+ col)
9488 (if (> to-col 0)
9489 to-col
9490 (- (abs to-col) (length tags))))
9492 (insert tags)
9493 (move-to-column (min (current-column) col) t))
9494 (goto-char pos))))
9496 (defun org-set-tags (&optional arg just-align)
9497 "Set the tags for the current headline.
9498 With prefix ARG, realign all tags in headings in the current buffer."
9499 (interactive "P")
9500 (let* ((re (concat "^" outline-regexp))
9501 (current (org-get-tags-string))
9502 (col (current-column))
9503 (org-setting-tags t)
9504 table current-tags inherited-tags ; computed below when needed
9505 tags p0 c0 c1 rpl)
9506 (if arg
9507 (save-excursion
9508 (goto-char (point-min))
9509 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
9510 (while (re-search-forward re nil t)
9511 (org-set-tags nil t)
9512 (end-of-line 1)))
9513 (message "All tags realigned to column %d" org-tags-column))
9514 (if just-align
9515 (setq tags current)
9516 ;; Get a new set of tags from the user
9517 (save-excursion
9518 (setq table (or org-tag-alist (org-get-buffer-tags))
9519 org-last-tags-completion-table table
9520 current-tags (org-split-string current ":")
9521 inherited-tags (nreverse
9522 (nthcdr (length current-tags)
9523 (nreverse (org-get-tags-at))))
9524 tags
9525 (if (or (eq t org-use-fast-tag-selection)
9526 (and org-use-fast-tag-selection
9527 (delq nil (mapcar 'cdr table))))
9528 (org-fast-tag-selection
9529 current-tags inherited-tags table
9530 (if org-fast-tag-selection-include-todo org-todo-key-alist))
9531 (let ((org-add-colon-after-tag-completion t))
9532 (org-trim
9533 (org-without-partial-completion
9534 (completing-read "Tags: " 'org-tags-completion-function
9535 nil nil current 'org-tags-history)))))))
9536 (while (string-match "[-+&]+" tags)
9537 ;; No boolean logic, just a list
9538 (setq tags (replace-match ":" t t tags))))
9540 (if (string-match "\\`[\t ]*\\'" tags)
9541 (setq tags "")
9542 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
9543 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
9545 ;; Insert new tags at the correct column
9546 (beginning-of-line 1)
9547 (cond
9548 ((and (equal current "") (equal tags "")))
9549 ((re-search-forward
9550 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
9551 (point-at-eol) t)
9552 (if (equal tags "")
9553 (setq rpl "")
9554 (goto-char (match-beginning 0))
9555 (setq c0 (current-column) p0 (point)
9556 c1 (max (1+ c0) (if (> org-tags-column 0)
9557 org-tags-column
9558 (- (- org-tags-column) (length tags))))
9559 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
9560 (replace-match rpl t t)
9561 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
9562 tags)
9563 (t (error "Tags alignment failed")))
9564 (move-to-column col)
9565 (unless just-align
9566 (run-hooks 'org-after-tags-change-hook)))))
9568 (defun org-change-tag-in-region (beg end tag off)
9569 "Add or remove TAG for each entry in the region.
9570 This works in the agenda, and also in an org-mode buffer."
9571 (interactive
9572 (list (region-beginning) (region-end)
9573 (let ((org-last-tags-completion-table
9574 (if (org-mode-p)
9575 (org-get-buffer-tags)
9576 (org-global-tags-completion-table))))
9577 (completing-read
9578 "Tag: " 'org-tags-completion-function nil nil nil
9579 'org-tags-history))
9580 (progn
9581 (message "[s]et or [r]emove? ")
9582 (equal (read-char-exclusive) ?r))))
9583 (if (fboundp 'deactivate-mark) (deactivate-mark))
9584 (let ((agendap (equal major-mode 'org-agenda-mode))
9585 l1 l2 m buf pos newhead (cnt 0))
9586 (goto-char end)
9587 (setq l2 (1- (org-current-line)))
9588 (goto-char beg)
9589 (setq l1 (org-current-line))
9590 (loop for l from l1 to l2 do
9591 (goto-line l)
9592 (setq m (get-text-property (point) 'org-hd-marker))
9593 (when (or (and (org-mode-p) (org-on-heading-p))
9594 (and agendap m))
9595 (setq buf (if agendap (marker-buffer m) (current-buffer))
9596 pos (if agendap m (point)))
9597 (with-current-buffer buf
9598 (save-excursion
9599 (save-restriction
9600 (goto-char pos)
9601 (setq cnt (1+ cnt))
9602 (org-toggle-tag tag (if off 'off 'on))
9603 (setq newhead (org-get-heading)))))
9604 (and agendap (org-agenda-change-all-lines newhead m))))
9605 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
9607 (defun org-tags-completion-function (string predicate &optional flag)
9608 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
9609 (confirm (lambda (x) (stringp (car x)))))
9610 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
9611 (setq s1 (match-string 1 string)
9612 s2 (match-string 2 string))
9613 (setq s1 "" s2 string))
9614 (cond
9615 ((eq flag nil)
9616 ;; try completion
9617 (setq rtn (try-completion s2 ctable confirm))
9618 (if (stringp rtn)
9619 (setq rtn
9620 (concat s1 s2 (substring rtn (length s2))
9621 (if (and org-add-colon-after-tag-completion
9622 (assoc rtn ctable))
9623 ":" ""))))
9624 rtn)
9625 ((eq flag t)
9626 ;; all-completions
9627 (all-completions s2 ctable confirm)
9629 ((eq flag 'lambda)
9630 ;; exact match?
9631 (assoc s2 ctable)))
9634 (defun org-fast-tag-insert (kwd tags face &optional end)
9635 "Insert KDW, and the TAGS, the latter with face FACE. Also inser END."
9636 (insert (format "%-12s" (concat kwd ":"))
9637 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
9638 (or end "")))
9640 (defun org-fast-tag-show-exit (flag)
9641 (save-excursion
9642 (goto-line 3)
9643 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
9644 (replace-match ""))
9645 (when flag
9646 (end-of-line 1)
9647 (move-to-column (- (window-width) 19) t)
9648 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
9650 (defun org-set-current-tags-overlay (current prefix)
9651 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
9652 (if (featurep 'xemacs)
9653 (org-overlay-display org-tags-overlay (concat prefix s)
9654 'secondary-selection)
9655 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
9656 (org-overlay-display org-tags-overlay (concat prefix s)))))
9658 (defun org-fast-tag-selection (current inherited table &optional todo-table)
9659 "Fast tag selection with single keys.
9660 CURRENT is the current list of tags in the headline, INHERITED is the
9661 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
9662 possibly with grouping information. TODO-TABLE is a similar table with
9663 TODO keywords, should these have keys assigned to them.
9664 If the keys are nil, a-z are automatically assigned.
9665 Returns the new tags string, or nil to not change the current settings."
9666 (let* ((fulltable (append table todo-table))
9667 (maxlen (apply 'max (mapcar
9668 (lambda (x)
9669 (if (stringp (car x)) (string-width (car x)) 0))
9670 fulltable)))
9671 (buf (current-buffer))
9672 (expert (eq org-fast-tag-selection-single-key 'expert))
9673 (buffer-tags nil)
9674 (fwidth (+ maxlen 3 1 3))
9675 (ncol (/ (- (window-width) 4) fwidth))
9676 (i-face 'org-done)
9677 (c-face 'org-todo)
9678 tg cnt e c char c1 c2 ntable tbl rtn
9679 ov-start ov-end ov-prefix
9680 (exit-after-next org-fast-tag-selection-single-key)
9681 (done-keywords org-done-keywords)
9682 groups ingroup)
9683 (save-excursion
9684 (beginning-of-line 1)
9685 (if (looking-at
9686 (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
9687 (setq ov-start (match-beginning 1)
9688 ov-end (match-end 1)
9689 ov-prefix "")
9690 (setq ov-start (1- (point-at-eol))
9691 ov-end (1+ ov-start))
9692 (skip-chars-forward "^\n\r")
9693 (setq ov-prefix
9694 (concat
9695 (buffer-substring (1- (point)) (point))
9696 (if (> (current-column) org-tags-column)
9698 (make-string (- org-tags-column (current-column)) ?\ ))))))
9699 (org-move-overlay org-tags-overlay ov-start ov-end)
9700 (save-window-excursion
9701 (if expert
9702 (set-buffer (get-buffer-create " *Org tags*"))
9703 (delete-other-windows)
9704 (split-window-vertically)
9705 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
9706 (erase-buffer)
9707 (org-set-local 'org-done-keywords done-keywords)
9708 (org-fast-tag-insert "Inherited" inherited i-face "\n")
9709 (org-fast-tag-insert "Current" current c-face "\n\n")
9710 (org-fast-tag-show-exit exit-after-next)
9711 (org-set-current-tags-overlay current ov-prefix)
9712 (setq tbl fulltable char ?a cnt 0)
9713 (while (setq e (pop tbl))
9714 (cond
9715 ((equal e '(:startgroup))
9716 (push '() groups) (setq ingroup t)
9717 (when (not (= cnt 0))
9718 (setq cnt 0)
9719 (insert "\n"))
9720 (insert "{ "))
9721 ((equal e '(:endgroup))
9722 (setq ingroup nil cnt 0)
9723 (insert "}\n"))
9725 (setq tg (car e) c2 nil)
9726 (if (cdr e)
9727 (setq c (cdr e))
9728 ;; automatically assign a character.
9729 (setq c1 (string-to-char
9730 (downcase (substring
9731 tg (if (= (string-to-char tg) ?@) 1 0)))))
9732 (if (or (rassoc c1 ntable) (rassoc c1 table))
9733 (while (or (rassoc char ntable) (rassoc char table))
9734 (setq char (1+ char)))
9735 (setq c2 c1))
9736 (setq c (or c2 char)))
9737 (if ingroup (push tg (car groups)))
9738 (setq tg (org-add-props tg nil 'face
9739 (cond
9740 ((not (assoc tg table))
9741 (org-get-todo-face tg))
9742 ((member tg current) c-face)
9743 ((member tg inherited) i-face)
9744 (t nil))))
9745 (if (and (= cnt 0) (not ingroup)) (insert " "))
9746 (insert "[" c "] " tg (make-string
9747 (- fwidth 4 (length tg)) ?\ ))
9748 (push (cons tg c) ntable)
9749 (when (= (setq cnt (1+ cnt)) ncol)
9750 (insert "\n")
9751 (if ingroup (insert " "))
9752 (setq cnt 0)))))
9753 (setq ntable (nreverse ntable))
9754 (insert "\n")
9755 (goto-char (point-min))
9756 (if (and (not expert) (fboundp 'fit-window-to-buffer))
9757 (fit-window-to-buffer))
9758 (setq rtn
9759 (catch 'exit
9760 (while t
9761 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free%s%s"
9762 (if groups " [!] no groups" " [!]groups")
9763 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
9764 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
9765 (cond
9766 ((= c ?\r) (throw 'exit t))
9767 ((= c ?!)
9768 (setq groups (not groups))
9769 (goto-char (point-min))
9770 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
9771 ((= c ?\C-c)
9772 (if (not expert)
9773 (org-fast-tag-show-exit
9774 (setq exit-after-next (not exit-after-next)))
9775 (setq expert nil)
9776 (delete-other-windows)
9777 (split-window-vertically)
9778 (org-switch-to-buffer-other-window " *Org tags*")
9779 (and (fboundp 'fit-window-to-buffer)
9780 (fit-window-to-buffer))))
9781 ((or (= c ?\C-g)
9782 (and (= c ?q) (not (rassoc c ntable))))
9783 (org-detach-overlay org-tags-overlay)
9784 (setq quit-flag t))
9785 ((= c ?\ )
9786 (setq current nil)
9787 (if exit-after-next (setq exit-after-next 'now)))
9788 ((= c ?\t)
9789 (condition-case nil
9790 (setq tg (completing-read
9791 "Tag: "
9792 (or buffer-tags
9793 (with-current-buffer buf
9794 (org-get-buffer-tags)))))
9795 (quit (setq tg "")))
9796 (when (string-match "\\S-" tg)
9797 (add-to-list 'buffer-tags (list tg))
9798 (if (member tg current)
9799 (setq current (delete tg current))
9800 (push tg current)))
9801 (if exit-after-next (setq exit-after-next 'now)))
9802 ((setq e (rassoc c todo-table) tg (car e))
9803 (with-current-buffer buf
9804 (save-excursion (org-todo tg)))
9805 (if exit-after-next (setq exit-after-next 'now)))
9806 ((setq e (rassoc c ntable) tg (car e))
9807 (if (member tg current)
9808 (setq current (delete tg current))
9809 (loop for g in groups do
9810 (if (member tg g)
9811 (mapc (lambda (x)
9812 (setq current (delete x current)))
9813 g)))
9814 (push tg current))
9815 (if exit-after-next (setq exit-after-next 'now))))
9817 ;; Create a sorted list
9818 (setq current
9819 (sort current
9820 (lambda (a b)
9821 (assoc b (cdr (memq (assoc a ntable) ntable))))))
9822 (if (eq exit-after-next 'now) (throw 'exit t))
9823 (goto-char (point-min))
9824 (beginning-of-line 2)
9825 (delete-region (point) (point-at-eol))
9826 (org-fast-tag-insert "Current" current c-face)
9827 (org-set-current-tags-overlay current ov-prefix)
9828 (while (re-search-forward
9829 (org-re "\\[.\\] \\([[:alnum:]_@]+\\)") nil t)
9830 (setq tg (match-string 1))
9831 (add-text-properties
9832 (match-beginning 1) (match-end 1)
9833 (list 'face
9834 (cond
9835 ((member tg current) c-face)
9836 ((member tg inherited) i-face)
9837 (t (get-text-property (match-beginning 1) 'face))))))
9838 (goto-char (point-min)))))
9839 (org-detach-overlay org-tags-overlay)
9840 (if rtn
9841 (mapconcat 'identity current ":")
9842 nil))))
9844 (defun org-get-tags-string ()
9845 "Get the TAGS string in the current headline."
9846 (unless (org-on-heading-p t)
9847 (error "Not on a heading"))
9848 (save-excursion
9849 (beginning-of-line 1)
9850 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
9851 (org-match-string-no-properties 1)
9852 "")))
9854 (defun org-get-tags ()
9855 "Get the list of tags specified in the current headline."
9856 (org-split-string (org-get-tags-string) ":"))
9858 (defun org-get-buffer-tags ()
9859 "Get a table of all tags used in the buffer, for completion."
9860 (let (tags)
9861 (save-excursion
9862 (goto-char (point-min))
9863 (while (re-search-forward
9864 (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t\r\n]") nil t)
9865 (when (equal (char-after (point-at-bol 0)) ?*)
9866 (mapc (lambda (x) (add-to-list 'tags x))
9867 (org-split-string (org-match-string-no-properties 1) ":")))))
9868 (mapcar 'list tags)))
9871 ;;;; Properties
9873 ;;; Setting and retrieving properties
9875 (defconst org-special-properties
9876 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "PRIORITY"
9877 "TIMESTAMP" "TIMESTAMP_IA")
9878 "The special properties valid in Org-mode.
9880 These are properties that are not defined in the property drawer,
9881 but in some other way.")
9883 (defconst org-default-properties
9884 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION"
9885 "LOCATION" "LOGGING" "COLUMNS")
9886 "Some properties that are used by Org-mode for various purposes.
9887 Being in this list makes sure that they are offered for completion.")
9889 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
9890 "Regular expression matching the first line of a property drawer.")
9892 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
9893 "Regular expression matching the first line of a property drawer.")
9895 (defun org-property-action ()
9896 "Do an action on properties."
9897 (interactive)
9898 (let (c)
9899 (org-at-property-p)
9900 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
9901 (setq c (read-char-exclusive))
9902 (cond
9903 ((equal c ?s)
9904 (call-interactively 'org-set-property))
9905 ((equal c ?d)
9906 (call-interactively 'org-delete-property))
9907 ((equal c ?D)
9908 (call-interactively 'org-delete-property-globally))
9909 ((equal c ?c)
9910 (call-interactively 'org-compute-property-at-point))
9911 (t (error "No such property action %c" c)))))
9913 (defun org-at-property-p ()
9914 "Is the cursor in a property line?"
9915 ;; FIXME: Does not check if we are actually in the drawer.
9916 ;; FIXME: also returns true on any drawers.....
9917 ;; This is used by C-c C-c for property action.
9918 (save-excursion
9919 (beginning-of-line 1)
9920 (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))))
9922 (defun org-get-property-block (&optional beg end force)
9923 "Return the (beg . end) range of the body of the property drawer.
9924 BEG and END can be beginning and end of subtree, if not given
9925 they will be found.
9926 If the drawer does not exist and FORCE is non-nil, create the drawer."
9927 (catch 'exit
9928 (save-excursion
9929 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
9930 (end (or end (progn (outline-next-heading) (point)))))
9931 (goto-char beg)
9932 (if (re-search-forward org-property-start-re end t)
9933 (setq beg (1+ (match-end 0)))
9934 (if force
9935 (save-excursion
9936 (org-insert-property-drawer)
9937 (setq end (progn (outline-next-heading) (point))))
9938 (throw 'exit nil))
9939 (goto-char beg)
9940 (if (re-search-forward org-property-start-re end t)
9941 (setq beg (1+ (match-end 0)))))
9942 (if (re-search-forward org-property-end-re end t)
9943 (setq end (match-beginning 0))
9944 (or force (throw 'exit nil))
9945 (goto-char beg)
9946 (setq end beg)
9947 (org-indent-line-function)
9948 (insert ":END:\n"))
9949 (cons beg end)))))
9951 (defun org-entry-properties (&optional pom which)
9952 "Get all properties of the entry at point-or-marker POM.
9953 This includes the TODO keyword, the tags, time strings for deadline,
9954 scheduled, and clocking, and any additional properties defined in the
9955 entry. The return value is an alist, keys may occur multiple times
9956 if the property key was used several times.
9957 POM may also be nil, in which case the current entry is used.
9958 If WHICH is nil or `all', get all properties. If WHICH is
9959 `special' or `standard', only get that subclass."
9960 (setq which (or which 'all))
9961 (org-with-point-at pom
9962 (let ((clockstr (substring org-clock-string 0 -1))
9963 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY"))
9964 beg end range props sum-props key value string clocksum)
9965 (save-excursion
9966 (when (condition-case nil (org-back-to-heading t) (error nil))
9967 (setq beg (point))
9968 (setq sum-props (get-text-property (point) 'org-summaries))
9969 (setq clocksum (get-text-property (point) :org-clock-minutes))
9970 (outline-next-heading)
9971 (setq end (point))
9972 (when (memq which '(all special))
9973 ;; Get the special properties, like TODO and tags
9974 (goto-char beg)
9975 (when (and (looking-at org-todo-line-regexp) (match-end 2))
9976 (push (cons "TODO" (org-match-string-no-properties 2)) props))
9977 (when (looking-at org-priority-regexp)
9978 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
9979 (when (and (setq value (org-get-tags-string))
9980 (string-match "\\S-" value))
9981 (push (cons "TAGS" value) props))
9982 (when (setq value (org-get-tags-at))
9983 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":") ":"))
9984 props))
9985 (while (re-search-forward org-maybe-keyword-time-regexp end t)
9986 (setq key (if (match-end 1) (substring (org-match-string-no-properties 1) 0 -1))
9987 string (if (equal key clockstr)
9988 (org-no-properties
9989 (org-trim
9990 (buffer-substring
9991 (match-beginning 3) (goto-char (point-at-eol)))))
9992 (substring (org-match-string-no-properties 3) 1 -1)))
9993 (unless key
9994 (if (= (char-after (match-beginning 3)) ?\[)
9995 (setq key "TIMESTAMP_IA")
9996 (setq key "TIMESTAMP")))
9997 (when (or (equal key clockstr) (not (assoc key props)))
9998 (push (cons key string) props)))
10002 (when (memq which '(all standard))
10003 ;; Get the standard properties, like :PORP: ...
10004 (setq range (org-get-property-block beg end))
10005 (when range
10006 (goto-char (car range))
10007 (while (re-search-forward
10008 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
10009 (cdr range) t)
10010 (setq key (org-match-string-no-properties 1)
10011 value (org-trim (or (org-match-string-no-properties 2) "")))
10012 (unless (member key excluded)
10013 (push (cons key (or value "")) props)))))
10014 (if clocksum
10015 (push (cons "CLOCKSUM"
10016 (org-column-number-to-string (/ (float clocksum) 60.)
10017 'add_times))
10018 props))
10019 (append sum-props (nreverse props)))))))
10021 (defun org-entry-get (pom property &optional inherit)
10022 "Get value of PROPERTY for entry at point-or-marker POM.
10023 If INHERIT is non-nil and the entry does not have the property,
10024 then also check higher levels of the hierarchy.
10025 If INHERIT is the symbol `selective', use inheritance only if the setting
10026 in `org-use-property-inheritance' selects PROPERTY for inheritance.
10027 If the property is present but empty, the return value is the empty string.
10028 If the property is not present at all, nil is returned."
10029 (org-with-point-at pom
10030 (if (and inherit (if (eq inherit 'selective)
10031 (org-property-inherit-p property)
10033 (org-entry-get-with-inheritance property)
10034 (if (member property org-special-properties)
10035 ;; We need a special property. Use brute force, get all properties.
10036 (cdr (assoc property (org-entry-properties nil 'special)))
10037 (let ((range (org-get-property-block)))
10038 (if (and range
10039 (goto-char (car range))
10040 (re-search-forward
10041 (concat "^[ \t]*:" property ":[ \t]*\\(.*\\S-\\)?")
10042 (cdr range) t))
10043 ;; Found the property, return it.
10044 (if (match-end 1)
10045 (org-match-string-no-properties 1)
10046 "")))))))
10048 (defun org-property-or-variable-value (var &optional inherit)
10049 "Check if there is a property fixing the value of VAR.
10050 If yes, return this value. If not, return the current value of the variable."
10051 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
10052 (if (and prop (stringp prop) (string-match "\\S-" prop))
10053 (read prop)
10054 (symbol-value var))))
10056 (defun org-entry-delete (pom property)
10057 "Delete the property PROPERTY from entry at point-or-marker POM."
10058 (org-with-point-at pom
10059 (if (member property org-special-properties)
10060 nil ; cannot delete these properties.
10061 (let ((range (org-get-property-block)))
10062 (if (and range
10063 (goto-char (car range))
10064 (re-search-forward
10065 (concat "^[ \t]*:" property ":[ \t]*\\(.*\\S-\\)")
10066 (cdr range) t))
10067 (progn
10068 (delete-region (match-beginning 0) (1+ (point-at-eol)))
10070 nil)))))
10072 ;; Multi-values properties are properties that contain multiple values
10073 ;; These values are assumed to be single words, separated by whitespace.
10074 (defun org-entry-add-to-multivalued-property (pom property value)
10075 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
10076 (let* ((old (org-entry-get pom property))
10077 (values (and old (org-split-string old "[ \t]"))))
10078 (unless (member value values)
10079 (setq values (cons value values))
10080 (org-entry-put pom property
10081 (mapconcat 'identity values " ")))))
10083 (defun org-entry-remove-from-multivalued-property (pom property value)
10084 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
10085 (let* ((old (org-entry-get pom property))
10086 (values (and old (org-split-string old "[ \t]"))))
10087 (when (member value values)
10088 (setq values (delete value values))
10089 (org-entry-put pom property
10090 (mapconcat 'identity values " ")))))
10092 (defun org-entry-member-in-multivalued-property (pom property value)
10093 "Is VALUE one of 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 (member value values)))
10098 (defvar org-entry-property-inherited-from (make-marker))
10100 (defun org-entry-get-with-inheritance (property)
10101 "Get entry property, and search higher levels if not present."
10102 (let (tmp)
10103 (save-excursion
10104 (save-restriction
10105 (widen)
10106 (catch 'ex
10107 (while t
10108 (when (setq tmp (org-entry-get nil property))
10109 (org-back-to-heading t)
10110 (move-marker org-entry-property-inherited-from (point))
10111 (throw 'ex tmp))
10112 (or (org-up-heading-safe) (throw 'ex nil)))))
10113 (or tmp (cdr (assoc property org-local-properties))
10114 (cdr (assoc property org-global-properties))))))
10116 (defun org-entry-put (pom property value)
10117 "Set PROPERTY to VALUE for entry at point-or-marker POM."
10118 (org-with-point-at pom
10119 (org-back-to-heading t)
10120 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
10121 range)
10122 (cond
10123 ((equal property "TODO")
10124 (when (and (stringp value) (string-match "\\S-" value)
10125 (not (member value org-todo-keywords-1)))
10126 (error "\"%s\" is not a valid TODO state" value))
10127 (if (or (not value)
10128 (not (string-match "\\S-" value)))
10129 (setq value 'none))
10130 (org-todo value)
10131 (org-set-tags nil 'align))
10132 ((equal property "PRIORITY")
10133 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
10134 (string-to-char value) ?\ ))
10135 (org-set-tags nil 'align))
10136 ((equal property "SCHEDULED")
10137 (if (re-search-forward org-scheduled-time-regexp end t)
10138 (cond
10139 ((eq value 'earlier) (org-timestamp-change -1 'day))
10140 ((eq value 'later) (org-timestamp-change 1 'day))
10141 (t (call-interactively 'org-schedule)))
10142 (call-interactively 'org-schedule)))
10143 ((equal property "DEADLINE")
10144 (if (re-search-forward org-deadline-time-regexp end t)
10145 (cond
10146 ((eq value 'earlier) (org-timestamp-change -1 'day))
10147 ((eq value 'later) (org-timestamp-change 1 'day))
10148 (t (call-interactively 'org-deadline)))
10149 (call-interactively 'org-deadline)))
10150 ((member property org-special-properties)
10151 (error "The %s property can not yet be set with `org-entry-put'"
10152 property))
10153 (t ; a non-special property
10154 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
10155 (setq range (org-get-property-block beg end 'force))
10156 (goto-char (car range))
10157 (if (re-search-forward
10158 (concat "^[ \t]*:" property ":\\(.*\\)") (cdr range) t)
10159 (progn
10160 (delete-region (match-beginning 1) (match-end 1))
10161 (goto-char (match-beginning 1)))
10162 (goto-char (cdr range))
10163 (insert "\n")
10164 (backward-char 1)
10165 (org-indent-line-function)
10166 (insert ":" property ":"))
10167 (and value (insert " " value))
10168 (org-indent-line-function)))))))
10170 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
10171 "Get all property keys in the current buffer.
10172 With INCLUDE-SPECIALS, also list the special properties that relect things
10173 like tags and TODO state.
10174 With INCLUDE-DEFAULTS, also include properties that has special meaning
10175 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING.
10176 With INCLUDE-COLUMNS, also include property names given in COLUMN
10177 formats in the current buffer."
10178 (let (rtn range cfmt cols s p)
10179 (save-excursion
10180 (save-restriction
10181 (widen)
10182 (goto-char (point-min))
10183 (while (re-search-forward org-property-start-re nil t)
10184 (setq range (org-get-property-block))
10185 (goto-char (car range))
10186 (while (re-search-forward
10187 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
10188 (cdr range) t)
10189 (add-to-list 'rtn (org-match-string-no-properties 1)))
10190 (outline-next-heading))))
10192 (when include-specials
10193 (setq rtn (append org-special-properties rtn)))
10195 (when include-defaults
10196 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties))
10198 (when include-columns
10199 (save-excursion
10200 (save-restriction
10201 (widen)
10202 (goto-char (point-min))
10203 (while (re-search-forward
10204 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
10205 nil t)
10206 (setq cfmt (match-string 2) s 0)
10207 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
10208 cfmt s)
10209 (setq s (match-end 0)
10210 p (match-string 1 cfmt))
10211 (unless (or (equal p "ITEM")
10212 (member p org-special-properties))
10213 (add-to-list 'rtn (match-string 1 cfmt))))))))
10215 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
10217 (defun org-property-values (key)
10218 "Return a list of all values of property KEY."
10219 (save-excursion
10220 (save-restriction
10221 (widen)
10222 (goto-char (point-min))
10223 (let ((re (concat "^[ \t]*:" key ":[ \t]*\\(\\S-.*\\)"))
10224 values)
10225 (while (re-search-forward re nil t)
10226 (add-to-list 'values (org-trim (match-string 1))))
10227 (delete "" values)))))
10229 (defun org-insert-property-drawer ()
10230 "Insert a property drawer into the current entry."
10231 (interactive)
10232 (org-back-to-heading t)
10233 (looking-at outline-regexp)
10234 (let ((indent (- (match-end 0)(match-beginning 0)))
10235 (beg (point))
10236 (re (concat "^[ \t]*" org-keyword-time-regexp))
10237 end hiddenp)
10238 (outline-next-heading)
10239 (setq end (point))
10240 (goto-char beg)
10241 (while (re-search-forward re end t))
10242 (setq hiddenp (org-invisible-p))
10243 (end-of-line 1)
10244 (and (equal (char-after) ?\n) (forward-char 1))
10245 (org-skip-over-state-notes)
10246 (skip-chars-backward " \t\n\r")
10247 (if (eq (char-before) ?*) (forward-char 1))
10248 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
10249 (beginning-of-line 0)
10250 (indent-to-column indent)
10251 (beginning-of-line 2)
10252 (indent-to-column indent)
10253 (beginning-of-line 0)
10254 (if hiddenp
10255 (save-excursion
10256 (org-back-to-heading t)
10257 (hide-entry))
10258 (org-flag-drawer t))))
10260 (defun org-set-property (property value)
10261 "In the current entry, set PROPERTY to VALUE.
10262 When called interactively, this will prompt for a property name, offering
10263 completion on existing and default properties. And then it will prompt
10264 for a value, offering competion either on allowed values (via an inherited
10265 xxx_ALL property) or on existing values in other instances of this property
10266 in the current file."
10267 (interactive
10268 (let* ((prop (completing-read
10269 "Property: " (mapcar 'list (org-buffer-property-keys nil t t))))
10270 (cur (org-entry-get nil prop))
10271 (allowed (org-property-get-allowed-values nil prop 'table))
10272 (existing (mapcar 'list (org-property-values prop)))
10273 (val (if allowed
10274 (completing-read "Value: " allowed nil 'req-match)
10275 (completing-read
10276 (concat "Value" (if (and cur (string-match "\\S-" cur))
10277 (concat "[" cur "]") "")
10278 ": ")
10279 existing nil nil "" nil cur))))
10280 (list prop (if (equal val "") cur val))))
10281 (unless (equal (org-entry-get nil property) value)
10282 (org-entry-put nil property value)))
10284 (defun org-delete-property (property)
10285 "In the current entry, delete PROPERTY."
10286 (interactive
10287 (let* ((prop (completing-read
10288 "Property: " (org-entry-properties nil 'standard))))
10289 (list prop)))
10290 (message "Property %s %s" property
10291 (if (org-entry-delete nil property)
10292 "deleted"
10293 "was not present in the entry")))
10295 (defun org-delete-property-globally (property)
10296 "Remove PROPERTY globally, from all entries."
10297 (interactive
10298 (let* ((prop (completing-read
10299 "Globally remove property: "
10300 (mapcar 'list (org-buffer-property-keys)))))
10301 (list prop)))
10302 (save-excursion
10303 (save-restriction
10304 (widen)
10305 (goto-char (point-min))
10306 (let ((cnt 0))
10307 (while (re-search-forward
10308 (concat "^[ \t]*:" (regexp-quote property) ":.*\n?")
10309 nil t)
10310 (setq cnt (1+ cnt))
10311 (replace-match ""))
10312 (message "Property \"%s\" removed from %d entries" property cnt)))))
10314 (defvar org-columns-current-fmt-compiled) ; defined below
10316 (defun org-compute-property-at-point ()
10317 "Compute the property at point.
10318 This looks for an enclosing column format, extracts the operator and
10319 then applies it to the proerty in the column format's scope."
10320 (interactive)
10321 (unless (org-at-property-p)
10322 (error "Not at a property"))
10323 (let ((prop (org-match-string-no-properties 2)))
10324 (org-columns-get-format-and-top-level)
10325 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
10326 (error "No operator defined for property %s" prop))
10327 (org-columns-compute prop)))
10329 (defun org-property-get-allowed-values (pom property &optional table)
10330 "Get allowed values for the property PROPERTY.
10331 When TABLE is non-nil, return an alist that can directly be used for
10332 completion."
10333 (let (vals)
10334 (cond
10335 ((equal property "TODO")
10336 (setq vals (org-with-point-at pom
10337 (append org-todo-keywords-1 '("")))))
10338 ((equal property "PRIORITY")
10339 (let ((n org-lowest-priority))
10340 (while (>= n org-highest-priority)
10341 (push (char-to-string n) vals)
10342 (setq n (1- n)))))
10343 ((member property org-special-properties))
10345 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
10347 (when (and vals (string-match "\\S-" vals))
10348 (setq vals (car (read-from-string (concat "(" vals ")"))))
10349 (setq vals (mapcar (lambda (x)
10350 (cond ((stringp x) x)
10351 ((numberp x) (number-to-string x))
10352 ((symbolp x) (symbol-name x))
10353 (t "???")))
10354 vals)))))
10355 (if table (mapcar 'list vals) vals)))
10357 (defun org-property-previous-allowed-value (&optional previous)
10358 "Switch to the next allowed value for this property."
10359 (interactive)
10360 (org-property-next-allowed-value t))
10362 (defun org-property-next-allowed-value (&optional previous)
10363 "Switch to the next allowed value for this property."
10364 (interactive)
10365 (unless (org-at-property-p)
10366 (error "Not at a property"))
10367 (let* ((key (match-string 2))
10368 (value (match-string 3))
10369 (allowed (or (org-property-get-allowed-values (point) key)
10370 (and (member value '("[ ]" "[-]" "[X]"))
10371 '("[ ]" "[X]"))))
10372 nval)
10373 (unless allowed
10374 (error "Allowed values for this property have not been defined"))
10375 (if previous (setq allowed (reverse allowed)))
10376 (if (member value allowed)
10377 (setq nval (car (cdr (member value allowed)))))
10378 (setq nval (or nval (car allowed)))
10379 (if (equal nval value)
10380 (error "Only one allowed value for this property"))
10381 (org-at-property-p)
10382 (replace-match (concat " :" key ": " nval) t t)
10383 (org-indent-line-function)
10384 (beginning-of-line 1)
10385 (skip-chars-forward " \t")))
10387 (defun org-find-entry-with-id (ident)
10388 "Locate the entry that contains the ID property with exact value IDENT.
10389 IDENT can be a string, a symbol or a number, this function will search for
10390 the string representation of it.
10391 Return the position where this entry starts, or nil if there is no such entry."
10392 (let ((id (cond
10393 ((stringp ident) ident)
10394 ((symbol-name ident) (symbol-name ident))
10395 ((numberp ident) (number-to-string ident))
10396 (t (error "IDENT %s must be a string, symbol or number" ident))))
10397 (case-fold-search nil))
10398 (save-excursion
10399 (save-restriction
10400 (widen)
10401 (goto-char (point-min))
10402 (when (re-search-forward
10403 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
10404 nil t)
10405 (org-back-to-heading)
10406 (point))))))
10408 ;;; Column View
10410 (defvar org-columns-overlays nil
10411 "Holds the list of current column overlays.")
10413 (defvar org-columns-current-fmt nil
10414 "Local variable, holds the currently active column format.")
10415 (defvar org-columns-current-fmt-compiled nil
10416 "Local variable, holds the currently active column format.
10417 This is the compiled version of the format.")
10418 (defvar org-columns-current-widths nil
10419 "Loval variable, holds the currently widths of fields.")
10420 (defvar org-columns-current-maxwidths nil
10421 "Loval variable, holds the currently active maximum column widths.")
10422 (defvar org-columns-begin-marker (make-marker)
10423 "Points to the position where last a column creation command was called.")
10424 (defvar org-columns-top-level-marker (make-marker)
10425 "Points to the position where current columns region starts.")
10427 (defvar org-columns-map (make-sparse-keymap)
10428 "The keymap valid in column display.")
10430 (defun org-columns-content ()
10431 "Switch to contents view while in columns view."
10432 (interactive)
10433 (org-overview)
10434 (org-content))
10436 (org-defkey org-columns-map "c" 'org-columns-content)
10437 (org-defkey org-columns-map "o" 'org-overview)
10438 (org-defkey org-columns-map "e" 'org-columns-edit-value)
10439 (org-defkey org-columns-map "\C-c\C-t" 'org-columns-todo)
10440 (org-defkey org-columns-map "\C-c\C-c" 'org-columns-set-tags-or-toggle)
10441 (org-defkey org-columns-map "\C-c\C-o" 'org-columns-open-link)
10442 (org-defkey org-columns-map "v" 'org-columns-show-value)
10443 (org-defkey org-columns-map "q" 'org-columns-quit)
10444 (org-defkey org-columns-map "r" 'org-columns-redo)
10445 (org-defkey org-columns-map "g" 'org-columns-redo)
10446 (org-defkey org-columns-map [left] 'backward-char)
10447 (org-defkey org-columns-map "\M-b" 'backward-char)
10448 (org-defkey org-columns-map "a" 'org-columns-edit-allowed)
10449 (org-defkey org-columns-map "s" 'org-columns-edit-attributes)
10450 (org-defkey org-columns-map "\M-f" (lambda () (interactive) (goto-char (1+ (point)))))
10451 (org-defkey org-columns-map [right] (lambda () (interactive) (goto-char (1+ (point)))))
10452 (org-defkey org-columns-map [(shift right)] 'org-columns-next-allowed-value)
10453 (org-defkey org-columns-map "n" 'org-columns-next-allowed-value)
10454 (org-defkey org-columns-map [(shift left)] 'org-columns-previous-allowed-value)
10455 (org-defkey org-columns-map "p" 'org-columns-previous-allowed-value)
10456 (org-defkey org-columns-map "<" 'org-columns-narrow)
10457 (org-defkey org-columns-map ">" 'org-columns-widen)
10458 (org-defkey org-columns-map [(meta right)] 'org-columns-move-right)
10459 (org-defkey org-columns-map [(meta left)] 'org-columns-move-left)
10460 (org-defkey org-columns-map [(shift meta right)] 'org-columns-new)
10461 (org-defkey org-columns-map [(shift meta left)] 'org-columns-delete)
10463 (easy-menu-define org-columns-menu org-columns-map "Org Column Menu"
10464 '("Column"
10465 ["Edit property" org-columns-edit-value t]
10466 ["Next allowed value" org-columns-next-allowed-value t]
10467 ["Previous allowed value" org-columns-previous-allowed-value t]
10468 ["Show full value" org-columns-show-value t]
10469 ["Edit allowed values" org-columns-edit-allowed t]
10470 "--"
10471 ["Edit column attributes" org-columns-edit-attributes t]
10472 ["Increase column width" org-columns-widen t]
10473 ["Decrease column width" org-columns-narrow t]
10474 "--"
10475 ["Move column right" org-columns-move-right t]
10476 ["Move column left" org-columns-move-left t]
10477 ["Add column" org-columns-new t]
10478 ["Delete column" org-columns-delete t]
10479 "--"
10480 ["CONTENTS" org-columns-content t]
10481 ["OVERVIEW" org-overview t]
10482 ["Refresh columns display" org-columns-redo t]
10483 "--"
10484 ["Open link" org-columns-open-link t]
10485 "--"
10486 ["Quit" org-columns-quit t]))
10488 (defun org-columns-new-overlay (beg end &optional string face)
10489 "Create a new column overlay and add it to the list."
10490 (let ((ov (org-make-overlay beg end)))
10491 (org-overlay-put ov 'face (or face 'secondary-selection))
10492 (org-overlay-display ov string face)
10493 (push ov org-columns-overlays)
10494 ov))
10496 (defun org-columns-display-here (&optional props)
10497 "Overlay the current line with column display."
10498 (interactive)
10499 (let* ((fmt org-columns-current-fmt-compiled)
10500 (beg (point-at-bol))
10501 (level-face (save-excursion
10502 (beginning-of-line 1)
10503 (and (looking-at "\\(\\**\\)\\(\\* \\)")
10504 (org-get-level-face 2))))
10505 (color (list :foreground
10506 (face-attribute (or level-face 'default) :foreground)))
10507 props pom property ass width f string ov column val modval)
10508 ;; Check if the entry is in another buffer.
10509 (unless props
10510 (if (eq major-mode 'org-agenda-mode)
10511 (setq pom (or (get-text-property (point) 'org-hd-marker)
10512 (get-text-property (point) 'org-marker))
10513 props (if pom (org-entry-properties pom) nil))
10514 (setq props (org-entry-properties nil))))
10515 ;; Walk the format
10516 (while (setq column (pop fmt))
10517 (setq property (car column)
10518 ass (if (equal property "ITEM")
10519 (cons "ITEM"
10520 (save-match-data
10521 (org-no-properties
10522 (org-remove-tabs
10523 (buffer-substring-no-properties
10524 (point-at-bol) (point-at-eol))))))
10525 (assoc property props))
10526 width (or (cdr (assoc property org-columns-current-maxwidths))
10527 (nth 2 column)
10528 (length property))
10529 f (format "%%-%d.%ds | " width width)
10530 val (or (cdr ass) "")
10531 modval (if (equal property "ITEM")
10532 (org-columns-cleanup-item val org-columns-current-fmt-compiled))
10533 string (format f (or modval val)))
10534 ;; Create the overlay
10535 (org-unmodified
10536 (setq ov (org-columns-new-overlay
10537 beg (setq beg (1+ beg)) string
10538 (list color 'org-column)))
10539 (org-overlay-put ov 'keymap org-columns-map)
10540 (org-overlay-put ov 'org-columns-key property)
10541 (org-overlay-put ov 'org-columns-value (cdr ass))
10542 (org-overlay-put ov 'org-columns-value-modified modval)
10543 (org-overlay-put ov 'org-columns-pom pom)
10544 (org-overlay-put ov 'org-columns-format f))
10545 (if (or (not (char-after beg))
10546 (equal (char-after beg) ?\n))
10547 (let ((inhibit-read-only t))
10548 (save-excursion
10549 (goto-char beg)
10550 (org-unmodified (insert " ")))))) ;; FIXME: add props and remove later?
10551 ;; Make the rest of the line disappear.
10552 (org-unmodified
10553 (setq ov (org-columns-new-overlay beg (point-at-eol)))
10554 (org-overlay-put ov 'invisible t)
10555 (org-overlay-put ov 'keymap org-columns-map)
10556 (org-overlay-put ov 'intangible t)
10557 (push ov org-columns-overlays)
10558 (setq ov (org-make-overlay (1- (point-at-eol)) (1+ (point-at-eol))))
10559 (org-overlay-put ov 'keymap org-columns-map)
10560 (push ov org-columns-overlays)
10561 (let ((inhibit-read-only t))
10562 (put-text-property (max (point-min) (1- (point-at-bol)))
10563 (min (point-max) (1+ (point-at-eol)))
10564 'read-only "Type `e' to edit property")))))
10566 (defvar org-columns-full-header-line-format nil
10567 "Fthe full header line format, will be shifted by horizontal scrolling." )
10568 (defvar org-previous-header-line-format nil
10569 "The header line format before column view was turned on.")
10570 (defvar org-columns-inhibit-recalculation nil
10571 "Inhibit recomputing of columns on column view startup.")
10574 (defvar header-line-format)
10575 (defvar org-columns-previous-hscroll 0)
10576 (defun org-columns-display-here-title ()
10577 "Overlay the newline before the current line with the table title."
10578 (interactive)
10579 (let ((fmt org-columns-current-fmt-compiled)
10580 string (title "")
10581 property width f column str widths)
10582 (while (setq column (pop fmt))
10583 (setq property (car column)
10584 str (or (nth 1 column) property)
10585 width (or (cdr (assoc property org-columns-current-maxwidths))
10586 (nth 2 column)
10587 (length str))
10588 widths (push width widths)
10589 f (format "%%-%d.%ds | " width width)
10590 string (format f str)
10591 title (concat title string)))
10592 (setq title (concat
10593 (org-add-props " " nil 'display '(space :align-to 0))
10594 (org-add-props title nil 'face '(:weight bold :underline t :inherit default))))
10595 (org-set-local 'org-previous-header-line-format header-line-format)
10596 (org-set-local 'org-columns-current-widths (nreverse widths))
10597 (setq org-columns-full-header-line-format title)
10598 (setq org-columns-previous-hscroll -1)
10599 ; (org-columns-hscoll-title)
10600 (org-add-hook 'post-command-hook 'org-columns-hscoll-title nil 'local)))
10602 (defun org-columns-hscoll-title ()
10603 "Set the header-line-format so that it scrolls along with the table."
10604 (sit-for .0001) ; need to force a redisplay to update window-hscroll
10605 (when (not (= (window-hscroll) org-columns-previous-hscroll))
10606 (setq header-line-format
10607 (concat (substring org-columns-full-header-line-format 0 1)
10608 (substring org-columns-full-header-line-format
10609 (1+ (window-hscroll))))
10610 org-columns-previous-hscroll (window-hscroll))
10611 (force-mode-line-update)))
10613 (defun org-columns-remove-overlays ()
10614 "Remove all currently active column overlays."
10615 (interactive)
10616 (when (marker-buffer org-columns-begin-marker)
10617 (with-current-buffer (marker-buffer org-columns-begin-marker)
10618 (when (local-variable-p 'org-previous-header-line-format)
10619 (setq header-line-format org-previous-header-line-format)
10620 (kill-local-variable 'org-previous-header-line-format)
10621 (remove-hook 'post-command-hook 'org-columns-hscoll-title 'local))
10622 (move-marker org-columns-begin-marker nil)
10623 (move-marker org-columns-top-level-marker nil)
10624 (org-unmodified
10625 (mapc 'org-delete-overlay org-columns-overlays)
10626 (setq org-columns-overlays nil)
10627 (let ((inhibit-read-only t))
10628 (remove-text-properties (point-min) (point-max) '(read-only t)))))))
10630 (defun org-columns-cleanup-item (item fmt)
10631 "Remove from ITEM what is a column in the format FMT."
10632 (if (not org-complex-heading-regexp)
10633 item
10634 (when (string-match org-complex-heading-regexp item)
10635 (concat
10636 (org-add-props (concat (match-string 1 item) " ") nil
10637 'org-whitespace (* 2 (1- (org-reduced-level (- (match-end 1) (match-beginning 1))))))
10638 (and (match-end 2) (not (assoc "TODO" fmt)) (concat " " (match-string 2 item)))
10639 (and (match-end 3) (not (assoc "PRIORITY" fmt)) (concat " " (match-string 3 item)))
10640 " " (match-string 4 item)
10641 (and (match-end 5) (not (assoc "TAGS" fmt)) (concat " " (match-string 5 item)))))))
10643 (defun org-columns-show-value ()
10644 "Show the full value of the property."
10645 (interactive)
10646 (let ((value (get-char-property (point) 'org-columns-value)))
10647 (message "Value is: %s" (or value ""))))
10649 (defun org-columns-quit ()
10650 "Remove the column overlays and in this way exit column editing."
10651 (interactive)
10652 (org-unmodified
10653 (org-columns-remove-overlays)
10654 (let ((inhibit-read-only t))
10655 (remove-text-properties (point-min) (point-max) '(read-only t))))
10656 (when (eq major-mode 'org-agenda-mode)
10657 (message
10658 "Modification not yet reflected in Agenda buffer, use `r' to refresh")))
10660 (defun org-columns-check-computed ()
10661 "Check if this column value is computed.
10662 If yes, throw an error indicating that changing it does not make sense."
10663 (let ((val (get-char-property (point) 'org-columns-value)))
10664 (when (and (stringp val)
10665 (get-char-property 0 'org-computed val))
10666 (error "This value is computed from the entry's children"))))
10668 (defun org-columns-todo (&optional arg)
10669 "Change the TODO state during column view."
10670 (interactive "P")
10671 (org-columns-edit-value "TODO"))
10673 (defun org-columns-set-tags-or-toggle (&optional arg)
10674 "Toggle checkbox at point, or set tags for current headline."
10675 (interactive "P")
10676 (if (string-match "\\`\\[[ xX-]\\]\\'"
10677 (get-char-property (point) 'org-columns-value))
10678 (org-columns-next-allowed-value)
10679 (org-columns-edit-value "TAGS")))
10681 (defun org-columns-edit-value (&optional key)
10682 "Edit the value of the property at point in column view.
10683 Where possible, use the standard interface for changing this line."
10684 (interactive)
10685 (org-columns-check-computed)
10686 (let* ((external-key key)
10687 (col (current-column))
10688 (key (or key (get-char-property (point) 'org-columns-key)))
10689 (value (get-char-property (point) 'org-columns-value))
10690 (bol (point-at-bol)) (eol (point-at-eol))
10691 (pom (or (get-text-property bol 'org-hd-marker)
10692 (point))) ; keep despite of compiler waring
10693 (line-overlays
10694 (delq nil (mapcar (lambda (x)
10695 (and (eq (overlay-buffer x) (current-buffer))
10696 (>= (overlay-start x) bol)
10697 (<= (overlay-start x) eol)
10699 org-columns-overlays)))
10700 nval eval allowed)
10701 (cond
10702 ((equal key "CLOCKSUM")
10703 (error "This special column cannot be edited"))
10704 ((equal key "ITEM")
10705 (setq eval '(org-with-point-at pom
10706 (org-edit-headline))))
10707 ((equal key "TODO")
10708 (setq eval '(org-with-point-at pom
10709 (let ((current-prefix-arg
10710 (if external-key current-prefix-arg '(4))))
10711 (call-interactively 'org-todo)))))
10712 ((equal key "PRIORITY")
10713 (setq eval '(org-with-point-at pom
10714 (call-interactively 'org-priority))))
10715 ((equal key "TAGS")
10716 (setq eval '(org-with-point-at pom
10717 (let ((org-fast-tag-selection-single-key
10718 (if (eq org-fast-tag-selection-single-key 'expert)
10719 t org-fast-tag-selection-single-key)))
10720 (call-interactively 'org-set-tags)))))
10721 ((equal key "DEADLINE")
10722 (setq eval '(org-with-point-at pom
10723 (call-interactively 'org-deadline))))
10724 ((equal key "SCHEDULED")
10725 (setq eval '(org-with-point-at pom
10726 (call-interactively 'org-schedule))))
10728 (setq allowed (org-property-get-allowed-values pom key 'table))
10729 (if allowed
10730 (setq nval (completing-read "Value: " allowed nil t))
10731 (setq nval (read-string "Edit: " value)))
10732 (setq nval (org-trim nval))
10733 (when (not (equal nval value))
10734 (setq eval '(org-entry-put pom key nval)))))
10735 (when eval
10736 (let ((inhibit-read-only t))
10737 (remove-text-properties (max (point-min) (1- bol)) eol '(read-only t))
10738 (unwind-protect
10739 (progn
10740 (setq org-columns-overlays
10741 (org-delete-all line-overlays org-columns-overlays))
10742 (mapc 'org-delete-overlay line-overlays)
10743 (org-columns-eval eval))
10744 (org-columns-display-here))))
10745 (move-to-column col)
10746 (if (and (org-mode-p)
10747 (nth 3 (assoc key org-columns-current-fmt-compiled)))
10748 (org-columns-update key))))
10750 (defun org-edit-headline () ; FIXME: this is not columns specific. Make interactive????? Use from agenda????
10751 "Edit the current headline, the part without TODO keyword, TAGS."
10752 (org-back-to-heading)
10753 (when (looking-at org-todo-line-regexp)
10754 (let ((pre (buffer-substring (match-beginning 0) (match-beginning 3)))
10755 (txt (match-string 3))
10756 (post "")
10757 txt2)
10758 (if (string-match (org-re "[ \t]+:[[:alnum:]:_@]+:[ \t]*$") txt)
10759 (setq post (match-string 0 txt)
10760 txt (substring txt 0 (match-beginning 0))))
10761 (setq txt2 (read-string "Edit: " txt))
10762 (when (not (equal txt txt2))
10763 (beginning-of-line 1)
10764 (insert pre txt2 post)
10765 (delete-region (point) (point-at-eol))
10766 (org-set-tags nil t)))))
10768 (defun org-columns-edit-allowed ()
10769 "Edit the list of allowed values for the current property."
10770 (interactive)
10771 (let* ((key (get-char-property (point) 'org-columns-key))
10772 (key1 (concat key "_ALL"))
10773 (allowed (org-entry-get (point) key1 t))
10774 nval)
10775 ;; FIXME: Cover editing TODO, TAGS etc in-buffer settings.????
10776 (setq nval (read-string "Allowed: " allowed))
10777 (org-entry-put
10778 (cond ((marker-position org-entry-property-inherited-from)
10779 org-entry-property-inherited-from)
10780 ((marker-position org-columns-top-level-marker)
10781 org-columns-top-level-marker))
10782 key1 nval)))
10784 (defun org-columns-eval (form)
10785 (let (hidep)
10786 (save-excursion
10787 (beginning-of-line 1)
10788 ;; `next-line' is needed here, because it skips invisible line.
10789 (condition-case nil (org-no-warnings (next-line 1)) (error nil))
10790 (setq hidep (org-on-heading-p 1)))
10791 (eval form)
10792 (and hidep (hide-entry))))
10794 (defun org-columns-previous-allowed-value ()
10795 "Switch to the previous allowed value for this column."
10796 (interactive)
10797 (org-columns-next-allowed-value t))
10799 (defun org-columns-next-allowed-value (&optional previous)
10800 "Switch to the next allowed value for this column."
10801 (interactive)
10802 (org-columns-check-computed)
10803 (let* ((col (current-column))
10804 (key (get-char-property (point) 'org-columns-key))
10805 (value (get-char-property (point) 'org-columns-value))
10806 (bol (point-at-bol)) (eol (point-at-eol))
10807 (pom (or (get-text-property bol 'org-hd-marker)
10808 (point))) ; keep despite of compiler waring
10809 (line-overlays
10810 (delq nil (mapcar (lambda (x)
10811 (and (eq (overlay-buffer x) (current-buffer))
10812 (>= (overlay-start x) bol)
10813 (<= (overlay-start x) eol)
10815 org-columns-overlays)))
10816 (allowed (or (org-property-get-allowed-values pom key)
10817 (and (memq
10818 (nth 4 (assoc key org-columns-current-fmt-compiled))
10819 '(checkbox checkbox-n-of-m checkbox-percent))
10820 '("[ ]" "[X]"))))
10821 nval)
10822 (when (equal key "ITEM")
10823 (error "Cannot edit item headline from here"))
10824 (unless (or allowed (member key '("SCHEDULED" "DEADLINE")))
10825 (error "Allowed values for this property have not been defined"))
10826 (if (member key '("SCHEDULED" "DEADLINE"))
10827 (setq nval (if previous 'earlier 'later))
10828 (if previous (setq allowed (reverse allowed)))
10829 (if (member value allowed)
10830 (setq nval (car (cdr (member value allowed)))))
10831 (setq nval (or nval (car allowed)))
10832 (if (equal nval value)
10833 (error "Only one allowed value for this property")))
10834 (let ((inhibit-read-only t))
10835 (remove-text-properties (1- bol) eol '(read-only t))
10836 (unwind-protect
10837 (progn
10838 (setq org-columns-overlays
10839 (org-delete-all line-overlays org-columns-overlays))
10840 (mapc 'org-delete-overlay line-overlays)
10841 (org-columns-eval '(org-entry-put pom key nval)))
10842 (org-columns-display-here)))
10843 (move-to-column col)
10844 (if (and (org-mode-p)
10845 (nth 3 (assoc key org-columns-current-fmt-compiled)))
10846 (org-columns-update key))))
10848 (defun org-verify-version (task)
10849 (cond
10850 ((eq task 'columns)
10851 (if (or (featurep 'xemacs)
10852 (< emacs-major-version 22))
10853 (error "Emacs 22 is required for the columns feature")))))
10855 (defun org-columns-open-link (&optional arg)
10856 (interactive "P")
10857 (let ((value (get-char-property (point) 'org-columns-value)))
10858 (org-open-link-from-string value arg)))
10860 (defun org-open-link-from-string (s &optional arg)
10861 "Open a link in the string S, as if it was in Org-mode."
10862 (interactive)
10863 (with-temp-buffer
10864 (let ((org-inhibit-startup t))
10865 (org-mode)
10866 (insert s)
10867 (goto-char (point-min))
10868 (org-open-at-point arg))))
10870 (defun org-columns-get-format-and-top-level ()
10871 (let (fmt)
10872 (when (condition-case nil (org-back-to-heading) (error nil))
10873 (move-marker org-entry-property-inherited-from nil)
10874 (setq fmt (org-entry-get nil "COLUMNS" t)))
10875 (setq fmt (or fmt org-columns-default-format))
10876 (org-set-local 'org-columns-current-fmt fmt)
10877 (org-columns-compile-format fmt)
10878 (if (marker-position org-entry-property-inherited-from)
10879 (move-marker org-columns-top-level-marker
10880 org-entry-property-inherited-from)
10881 (move-marker org-columns-top-level-marker (point)))
10882 fmt))
10884 (defun org-columns ()
10885 "Turn on column view on an org-mode file."
10886 (interactive)
10887 (org-verify-version 'columns)
10888 (org-columns-remove-overlays)
10889 (move-marker org-columns-begin-marker (point))
10890 (let (beg end fmt cache maxwidths)
10891 (setq fmt (org-columns-get-format-and-top-level))
10892 (save-excursion
10893 (goto-char org-columns-top-level-marker)
10894 (setq beg (point))
10895 (unless org-columns-inhibit-recalculation
10896 (org-columns-compute-all))
10897 (setq end (or (condition-case nil (org-end-of-subtree t t) (error nil))
10898 (point-max)))
10899 ;; Get and cache the properties
10900 (goto-char beg)
10901 (when (assoc "CLOCKSUM" org-columns-current-fmt-compiled)
10902 (save-excursion
10903 (save-restriction
10904 (narrow-to-region beg end)
10905 (org-clock-sum))))
10906 (while (re-search-forward (concat "^" outline-regexp) end t)
10907 (push (cons (org-current-line) (org-entry-properties)) cache))
10908 (when cache
10909 (setq maxwidths (org-columns-get-autowidth-alist fmt cache))
10910 (org-set-local 'org-columns-current-maxwidths maxwidths)
10911 (org-columns-display-here-title)
10912 (mapc (lambda (x)
10913 (goto-line (car x))
10914 (org-columns-display-here (cdr x)))
10915 cache)))))
10917 (defun org-columns-new (&optional prop title width op fmt &rest rest)
10918 "Insert a new column, to the left of the current column."
10919 (interactive)
10920 (let ((editp (and prop (assoc prop org-columns-current-fmt-compiled)))
10921 cell)
10922 (setq prop (completing-read
10923 "Property: " (mapcar 'list (org-buffer-property-keys t nil t))
10924 nil nil prop))
10925 (setq title (read-string (concat "Column title [" prop "]: ") (or title prop)))
10926 (setq width (read-string "Column width: " (if width (number-to-string width))))
10927 (if (string-match "\\S-" width)
10928 (setq width (string-to-number width))
10929 (setq width nil))
10930 (setq fmt (completing-read "Summary [none]: "
10931 '(("none") ("add_numbers") ("currency") ("add_times") ("checkbox") ("checkbox-n-of-m") ("checkbox-percent"))
10932 nil t))
10933 (if (string-match "\\S-" fmt)
10934 (setq fmt (intern fmt))
10935 (setq fmt nil))
10936 (if (eq fmt 'none) (setq fmt nil))
10937 (if editp
10938 (progn
10939 (setcar editp prop)
10940 (setcdr editp (list title width nil fmt)))
10941 (setq cell (nthcdr (1- (current-column))
10942 org-columns-current-fmt-compiled))
10943 (setcdr cell (cons (list prop title width nil fmt)
10944 (cdr cell))))
10945 (org-columns-store-format)
10946 (org-columns-redo)))
10948 (defun org-columns-delete ()
10949 "Delete the column at point from columns view."
10950 (interactive)
10951 (let* ((n (current-column))
10952 (title (nth 1 (nth n org-columns-current-fmt-compiled))))
10953 (when (y-or-n-p
10954 (format "Are you sure you want to remove column \"%s\"? " title))
10955 (setq org-columns-current-fmt-compiled
10956 (delq (nth n org-columns-current-fmt-compiled)
10957 org-columns-current-fmt-compiled))
10958 (org-columns-store-format)
10959 (org-columns-redo)
10960 (if (>= (current-column) (length org-columns-current-fmt-compiled))
10961 (backward-char 1)))))
10963 (defun org-columns-edit-attributes ()
10964 "Edit the attributes of the current column."
10965 (interactive)
10966 (let* ((n (current-column))
10967 (info (nth n org-columns-current-fmt-compiled)))
10968 (apply 'org-columns-new info)))
10970 (defun org-columns-widen (arg)
10971 "Make the column wider by ARG characters."
10972 (interactive "p")
10973 (let* ((n (current-column))
10974 (entry (nth n org-columns-current-fmt-compiled))
10975 (width (or (nth 2 entry)
10976 (cdr (assoc (car entry) org-columns-current-maxwidths)))))
10977 (setq width (max 1 (+ width arg)))
10978 (setcar (nthcdr 2 entry) width)
10979 (org-columns-store-format)
10980 (org-columns-redo)))
10982 (defun org-columns-narrow (arg)
10983 "Make the column nrrower by ARG characters."
10984 (interactive "p")
10985 (org-columns-widen (- arg)))
10987 (defun org-columns-move-right ()
10988 "Swap this column with the one to the right."
10989 (interactive)
10990 (let* ((n (current-column))
10991 (cell (nthcdr n org-columns-current-fmt-compiled))
10993 (when (>= n (1- (length org-columns-current-fmt-compiled)))
10994 (error "Cannot shift this column further to the right"))
10995 (setq e (car cell))
10996 (setcar cell (car (cdr cell)))
10997 (setcdr cell (cons e (cdr (cdr cell))))
10998 (org-columns-store-format)
10999 (org-columns-redo)
11000 (forward-char 1)))
11002 (defun org-columns-move-left ()
11003 "Swap this column with the one to the left."
11004 (interactive)
11005 (let* ((n (current-column)))
11006 (when (= n 0)
11007 (error "Cannot shift this column further to the left"))
11008 (backward-char 1)
11009 (org-columns-move-right)
11010 (backward-char 1)))
11012 (defun org-columns-store-format ()
11013 "Store the text version of the current columns format in appropriate place.
11014 This is either in the COLUMNS property of the node starting the current column
11015 display, or in the #+COLUMNS line of the current buffer."
11016 (let (fmt (cnt 0))
11017 (setq fmt (org-columns-uncompile-format org-columns-current-fmt-compiled))
11018 (org-set-local 'org-columns-current-fmt fmt)
11019 (if (marker-position org-columns-top-level-marker)
11020 (save-excursion
11021 (goto-char org-columns-top-level-marker)
11022 (if (and (org-at-heading-p)
11023 (org-entry-get nil "COLUMNS"))
11024 (org-entry-put nil "COLUMNS" fmt)
11025 (goto-char (point-min))
11026 ;; Overwrite all #+COLUMNS lines....
11027 (while (re-search-forward "^#\\+COLUMNS:.*" nil t)
11028 (setq cnt (1+ cnt))
11029 (replace-match (concat "#+COLUMNS: " fmt) t t))
11030 (unless (> cnt 0)
11031 (goto-char (point-min))
11032 (or (org-on-heading-p t) (outline-next-heading))
11033 (let ((inhibit-read-only t))
11034 (insert-before-markers "#+COLUMNS: " fmt "\n")))
11035 (org-set-local 'org-columns-default-format fmt))))))
11037 (defvar org-overriding-columns-format nil
11038 "When set, overrides any other definition.")
11039 (defvar org-agenda-view-columns-initially nil
11040 "When set, switch to columns view immediately after creating the agenda.")
11042 (defun org-agenda-columns ()
11043 "Turn on column view in the agenda."
11044 (interactive)
11045 (org-verify-version 'columns)
11046 (org-columns-remove-overlays)
11047 (move-marker org-columns-begin-marker (point))
11048 (let (fmt cache maxwidths m)
11049 (cond
11050 ((and (local-variable-p 'org-overriding-columns-format)
11051 org-overriding-columns-format)
11052 (setq fmt org-overriding-columns-format))
11053 ((setq m (get-text-property (point-at-bol) 'org-hd-marker))
11054 (setq fmt (or (org-entry-get m "COLUMNS" t)
11055 (with-current-buffer (marker-buffer m)
11056 org-columns-default-format))))
11057 ((and (boundp 'org-columns-current-fmt)
11058 (local-variable-p 'org-columns-current-fmt)
11059 org-columns-current-fmt)
11060 (setq fmt org-columns-current-fmt))
11061 ((setq m (next-single-property-change (point-min) 'org-hd-marker))
11062 (setq m (get-text-property m 'org-hd-marker))
11063 (setq fmt (or (org-entry-get m "COLUMNS" t)
11064 (with-current-buffer (marker-buffer m)
11065 org-columns-default-format)))))
11066 (setq fmt (or fmt org-columns-default-format))
11067 (org-set-local 'org-columns-current-fmt fmt)
11068 (org-columns-compile-format fmt)
11069 (save-excursion
11070 ;; Get and cache the properties
11071 (goto-char (point-min))
11072 (while (not (eobp))
11073 (when (setq m (or (get-text-property (point) 'org-hd-marker)
11074 (get-text-property (point) 'org-marker)))
11075 (push (cons (org-current-line) (org-entry-properties m)) cache))
11076 (beginning-of-line 2))
11077 (when cache
11078 (setq maxwidths (org-columns-get-autowidth-alist fmt cache))
11079 (org-set-local 'org-columns-current-maxwidths maxwidths)
11080 (org-columns-display-here-title)
11081 (mapc (lambda (x)
11082 (goto-line (car x))
11083 (org-columns-display-here (cdr x)))
11084 cache)))))
11086 (defun org-columns-get-autowidth-alist (s cache)
11087 "Derive the maximum column widths from the format and the cache."
11088 (let ((start 0) rtn)
11089 (while (string-match (org-re "%\\([[:alpha:]][[:alnum:]_-]*\\)") s start)
11090 (push (cons (match-string 1 s) 1) rtn)
11091 (setq start (match-end 0)))
11092 (mapc (lambda (x)
11093 (setcdr x (apply 'max
11094 (mapcar
11095 (lambda (y)
11096 (length (or (cdr (assoc (car x) (cdr y))) " ")))
11097 cache))))
11098 rtn)
11099 rtn))
11101 (defun org-columns-compute-all ()
11102 "Compute all columns that have operators defined."
11103 (org-unmodified
11104 (remove-text-properties (point-min) (point-max) '(org-summaries t)))
11105 (let ((columns org-columns-current-fmt-compiled) col)
11106 (while (setq col (pop columns))
11107 (when (nth 3 col)
11108 (save-excursion
11109 (org-columns-compute (car col)))))))
11111 (defun org-columns-update (property)
11112 "Recompute PROPERTY, and update the columns display for it."
11113 (org-columns-compute property)
11114 (let (fmt val pos)
11115 (save-excursion
11116 (mapc (lambda (ov)
11117 (when (equal (org-overlay-get ov 'org-columns-key) property)
11118 (setq pos (org-overlay-start ov))
11119 (goto-char pos)
11120 (when (setq val (cdr (assoc property
11121 (get-text-property
11122 (point-at-bol) 'org-summaries))))
11123 (setq fmt (org-overlay-get ov 'org-columns-format))
11124 (org-overlay-put ov 'org-columns-value val)
11125 (org-overlay-put ov 'display (format fmt val)))))
11126 org-columns-overlays))))
11128 (defun org-columns-compute (property)
11129 "Sum the values of property PROPERTY hierarchically, for the entire buffer."
11130 (interactive)
11131 (let* ((re (concat "^" outline-regexp))
11132 (lmax 30) ; Does anyone use deeper levels???
11133 (lsum (make-vector lmax 0))
11134 (lflag (make-vector lmax nil))
11135 (level 0)
11136 (ass (assoc property org-columns-current-fmt-compiled))
11137 (format (nth 4 ass))
11138 (printf (nth 5 ass))
11139 (beg org-columns-top-level-marker)
11140 last-level val valflag flag end sumpos sum-alist sum str str1 useval)
11141 (save-excursion
11142 ;; Find the region to compute
11143 (goto-char beg)
11144 (setq end (condition-case nil (org-end-of-subtree t) (error (point-max))))
11145 (goto-char end)
11146 ;; Walk the tree from the back and do the computations
11147 (while (re-search-backward re beg t)
11148 (setq sumpos (match-beginning 0)
11149 last-level level
11150 level (org-outline-level)
11151 val (org-entry-get nil property)
11152 valflag (and val (string-match "\\S-" val)))
11153 (cond
11154 ((< level last-level)
11155 ;; put the sum of lower levels here as a property
11156 (setq sum (aref lsum last-level) ; current sum
11157 flag (aref lflag last-level) ; any valid entries from children?
11158 str (org-column-number-to-string sum format printf)
11159 str1 (org-add-props (copy-sequence str) nil 'org-computed t 'face 'bold)
11160 useval (if flag str1 (if valflag val ""))
11161 sum-alist (get-text-property sumpos 'org-summaries))
11162 (if (assoc property sum-alist)
11163 (setcdr (assoc property sum-alist) useval)
11164 (push (cons property useval) sum-alist)
11165 (org-unmodified
11166 (add-text-properties sumpos (1+ sumpos)
11167 (list 'org-summaries sum-alist))))
11168 (when val
11169 (org-entry-put nil property (if flag str val)))
11170 ;; add current to current level accumulator
11171 (when (or flag valflag)
11172 (aset lsum level (+ (aref lsum level)
11173 (if flag sum (org-column-string-to-number
11174 (if flag str val) format))))
11175 (aset lflag level t))
11176 ;; clear accumulators for deeper levels
11177 (loop for l from (1+ level) to (1- lmax) do
11178 (aset lsum l 0)
11179 (aset lflag l nil)))
11180 ((>= level last-level)
11181 ;; add what we have here to the accumulator for this level
11182 (aset lsum level (+ (aref lsum level)
11183 (org-column-string-to-number (or val "0") format)))
11184 (and valflag (aset lflag level t)))
11185 (t (error "This should not happen")))))))
11187 (defun org-columns-redo ()
11188 "Construct the column display again."
11189 (interactive)
11190 (message "Recomputing columns...")
11191 (save-excursion
11192 (if (marker-position org-columns-begin-marker)
11193 (goto-char org-columns-begin-marker))
11194 (org-columns-remove-overlays)
11195 (if (org-mode-p)
11196 (call-interactively 'org-columns)
11197 (call-interactively 'org-agenda-columns)))
11198 (message "Recomputing columns...done"))
11200 (defun org-columns-not-in-agenda ()
11201 (if (eq major-mode 'org-agenda-mode)
11202 (error "This command is only allowed in Org-mode buffers")))
11205 (defun org-string-to-number (s)
11206 "Convert string to number, and interpret hh:mm:ss."
11207 (if (not (string-match ":" s))
11208 (string-to-number s)
11209 (let ((l (nreverse (org-split-string s ":"))) (sum 0.0))
11210 (while l
11211 (setq sum (+ (string-to-number (pop l)) (/ sum 60))))
11212 sum)))
11214 (defun org-column-number-to-string (n fmt &optional printf)
11215 "Convert a computed column number to a string value, according to FMT."
11216 (cond
11217 ((eq fmt 'add_times)
11218 (let* ((h (floor n)) (m (floor (+ 0.5 (* 60 (- n h))))))
11219 (format "%d:%02d" h m)))
11220 ((eq fmt 'checkbox)
11221 (cond ((= n (floor n)) "[X]")
11222 ((> n 1.) "[-]")
11223 (t "[ ]")))
11224 ((memq fmt '(checkbox-n-of-m checkbox-percent))
11225 (let* ((n1 (floor n)) (n2 (floor (+ .5 (* 1000000 (- n n1))))))
11226 (org-nofm-to-completion n1 (+ n2 n1) (eq fmt 'checkbox-percent))))
11227 (printf (format printf n))
11228 ((eq fmt 'currency)
11229 (format "%.2f" n))
11230 (t (number-to-string n))))
11232 (defun org-nofm-to-completion (n m &optional percent)
11233 (if (not percent)
11234 (format "[%d/%d]" n m)
11235 (format "[%d%%]"(floor (+ 0.5 (* 100. (/ (* 1.0 n) m)))))))
11237 (defun org-column-string-to-number (s fmt)
11238 "Convert a column value to a number that can be used for column computing."
11239 (cond
11240 ((string-match ":" s)
11241 (let ((l (nreverse (org-split-string s ":"))) (sum 0.0))
11242 (while l
11243 (setq sum (+ (string-to-number (pop l)) (/ sum 60))))
11244 sum))
11245 ((memq fmt '(checkbox checkbox-n-of-m checkbox-percent))
11246 (if (equal s "[X]") 1. 0.000001))
11247 (t (string-to-number s))))
11249 (defun org-columns-uncompile-format (cfmt)
11250 "Turn the compiled columns format back into a string representation."
11251 (let ((rtn "") e s prop title op width fmt printf)
11252 (while (setq e (pop cfmt))
11253 (setq prop (car e)
11254 title (nth 1 e)
11255 width (nth 2 e)
11256 op (nth 3 e)
11257 fmt (nth 4 e)
11258 printf (nth 5 e))
11259 (cond
11260 ((eq fmt 'add_times) (setq op ":"))
11261 ((eq fmt 'checkbox) (setq op "X"))
11262 ((eq fmt 'checkbox-n-of-m) (setq op "X/"))
11263 ((eq fmt 'checkbox-percent) (setq op "X%"))
11264 ((eq fmt 'add_numbers) (setq op "+"))
11265 ((eq fmt 'currency) (setq op "$")))
11266 (if (and op printf) (setq op (concat op ";" printf)))
11267 (if (equal title prop) (setq title nil))
11268 (setq s (concat "%" (if width (number-to-string width))
11269 prop
11270 (if title (concat "(" title ")"))
11271 (if op (concat "{" op "}"))))
11272 (setq rtn (concat rtn " " s)))
11273 (org-trim rtn)))
11275 (defun org-columns-compile-format (fmt)
11276 "Turn a column format string into an alist of specifications.
11277 The alist has one entry for each column in the format. The elements of
11278 that list are:
11279 property the property
11280 title the title field for the columns
11281 width the column width in characters, can be nil for automatic
11282 operator the operator if any
11283 format the output format for computed results, derived from operator
11284 printf a printf format for computed values"
11285 (let ((start 0) width prop title op f printf)
11286 (setq org-columns-current-fmt-compiled nil)
11287 (while (string-match
11288 (org-re "%\\([0-9]+\\)?\\([[:alnum:]_-]+\\)\\(?:(\\([^)]+\\))\\)?\\(?:{\\([^}]+\\)}\\)?\\s-*")
11289 fmt start)
11290 (setq start (match-end 0)
11291 width (match-string 1 fmt)
11292 prop (match-string 2 fmt)
11293 title (or (match-string 3 fmt) prop)
11294 op (match-string 4 fmt)
11295 f nil
11296 printf nil)
11297 (if width (setq width (string-to-number width)))
11298 (when (and op (string-match ";" op))
11299 (setq printf (substring op (match-end 0))
11300 op (substring op 0 (match-beginning 0))))
11301 (cond
11302 ((equal op "+") (setq f 'add_numbers))
11303 ((equal op "$") (setq f 'currency))
11304 ((equal op ":") (setq f 'add_times))
11305 ((equal op "X") (setq f 'checkbox))
11306 ((equal op "X/") (setq f 'checkbox-n-of-m))
11307 ((equal op "X%") (setq f 'checkbox-percent))
11309 (push (list prop title width op f printf) org-columns-current-fmt-compiled))
11310 (setq org-columns-current-fmt-compiled
11311 (nreverse org-columns-current-fmt-compiled))))
11314 ;;; Dynamic block for Column view
11316 (defun org-columns-capture-view (&optional maxlevel skip-empty-rows)
11317 "Get the column view of the current buffer or subtree.
11318 The first optional argument MAXLEVEL sets the level limit. A
11319 second optional argument SKIP-EMPTY-ROWS tells whether to skip
11320 empty rows, an empty row being one where all the column view
11321 specifiers except ITEM are empty. This function returns a list
11322 containing the title row and all other rows. Each row is a list
11323 of fields."
11324 (save-excursion
11325 (let* ((title (mapcar 'cadr org-columns-current-fmt-compiled))
11326 (n (length title)) row tbl)
11327 (goto-char (point-min))
11328 (while (and (re-search-forward "^\\(\\*+\\) " nil t)
11329 (or (null maxlevel)
11330 (>= maxlevel
11331 (if org-odd-levels-only
11332 (/ (1+ (length (match-string 1))) 2)
11333 (length (match-string 1))))))
11334 (when (get-char-property (match-beginning 0) 'org-columns-key)
11335 (setq row nil)
11336 (loop for i from 0 to (1- n) do
11337 (push (or (get-char-property (+ (match-beginning 0) i) 'org-columns-value-modified)
11338 (get-char-property (+ (match-beginning 0) i) 'org-columns-value)
11340 row))
11341 (setq row (nreverse row))
11342 (unless (and skip-empty-rows
11343 (eq 1 (length (delete "" (delete-dups row)))))
11344 (push row tbl))))
11345 (append (list title 'hline) (nreverse tbl)))))
11347 (defun org-dblock-write:columnview (params)
11348 "Write the column view table.
11349 PARAMS is a property list of parameters:
11351 :width enforce same column widths with <N> specifiers.
11352 :id the :ID: property of the entry where the columns view
11353 should be built, as a string. When `local', call locally.
11354 When `global' call column view with the cursor at the beginning
11355 of the buffer (usually this means that the whole buffer switches
11356 to column view).
11357 :hlines When t, insert a hline before each item. When a number, insert
11358 a hline before each level <= that number.
11359 :vlines When t, make each column a colgroup to enforce vertical lines.
11360 :maxlevel When set to a number, don't capture headlines below this level.
11361 :skip-empty-rows
11362 When t, skip rows where all specifiers other than ITEM are empty."
11363 (let ((pos (move-marker (make-marker) (point)))
11364 (hlines (plist-get params :hlines))
11365 (vlines (plist-get params :vlines))
11366 (maxlevel (plist-get params :maxlevel))
11367 (skip-empty-rows (plist-get params :skip-empty-rows))
11368 tbl id idpos nfields tmp)
11369 (save-excursion
11370 (save-restriction
11371 (when (setq id (plist-get params :id))
11372 (cond ((not id) nil)
11373 ((eq id 'global) (goto-char (point-min)))
11374 ((eq id 'local) nil)
11375 ((setq idpos (org-find-entry-with-id id))
11376 (goto-char idpos))
11377 (t (error "Cannot find entry with :ID: %s" id))))
11378 (org-columns)
11379 (setq tbl (org-columns-capture-view maxlevel skip-empty-rows))
11380 (setq nfields (length (car tbl)))
11381 (org-columns-quit)))
11382 (goto-char pos)
11383 (move-marker pos nil)
11384 (when tbl
11385 (when (plist-get params :hlines)
11386 (setq tmp nil)
11387 (while tbl
11388 (if (eq (car tbl) 'hline)
11389 (push (pop tbl) tmp)
11390 (if (string-match "\\` *\\(\\*+\\)" (caar tbl))
11391 (if (and (not (eq (car tmp) 'hline))
11392 (or (eq hlines t)
11393 (and (numberp hlines) (<= (- (match-end 1) (match-beginning 1)) hlines))))
11394 (push 'hline tmp)))
11395 (push (pop tbl) tmp)))
11396 (setq tbl (nreverse tmp)))
11397 (when vlines
11398 (setq tbl (mapcar (lambda (x)
11399 (if (eq 'hline x) x (cons "" x)))
11400 tbl))
11401 (setq tbl (append tbl (list (cons "/" (make-list nfields "<>"))))))
11402 (setq pos (point))
11403 (insert (org-listtable-to-string tbl))
11404 (when (plist-get params :width)
11405 (insert "\n|" (mapconcat (lambda (x) (format "<%d>" (max 3 x)))
11406 org-columns-current-widths "|")))
11407 (goto-char pos)
11408 (org-table-align))))
11410 (defun org-listtable-to-string (tbl)
11411 "Convert a listtable TBL to a string that contains the Org-mode table.
11412 The table still need to be alligned. The resulting string has no leading
11413 and tailing newline characters."
11414 (mapconcat
11415 (lambda (x)
11416 (cond
11417 ((listp x)
11418 (concat "|" (mapconcat 'identity x "|") "|"))
11419 ((eq x 'hline) "|-|")
11420 (t (error "Garbage in listtable: %s" x))))
11421 tbl "\n"))
11423 (defun org-insert-columns-dblock ()
11424 "Create a dynamic block capturing a column view table."
11425 (interactive)
11426 (let ((defaults '(:name "columnview" :hlines 1))
11427 (id (completing-read
11428 "Capture columns (local, global, entry with :ID: property) [local]: "
11429 (append '(("global") ("local"))
11430 (mapcar 'list (org-property-values "ID"))))))
11431 (if (equal id "") (setq id 'local))
11432 (if (equal id "global") (setq id 'global))
11433 (setq defaults (append defaults (list :id id)))
11434 (org-create-dblock defaults)
11435 (org-update-dblock)))
11437 ;;;; Timestamps
11439 (defvar org-last-changed-timestamp nil)
11440 (defvar org-time-was-given) ; dynamically scoped parameter
11441 (defvar org-end-time-was-given) ; dynamically scoped parameter
11442 (defvar org-ts-what) ; dynamically scoped parameter
11444 (defun org-time-stamp (arg)
11445 "Prompt for a date/time and insert a time stamp.
11446 If the user specifies a time like HH:MM, or if this command is called
11447 with a prefix argument, the time stamp will contain date and time.
11448 Otherwise, only the date will be included. All parts of a date not
11449 specified by the user will be filled in from the current date/time.
11450 So if you press just return without typing anything, the time stamp
11451 will represent the current date/time. If there is already a timestamp
11452 at the cursor, it will be modified."
11453 (interactive "P")
11454 (let* ((ts nil)
11455 (default-time
11456 ;; Default time is either today, or, when entering a range,
11457 ;; the range start.
11458 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
11459 (save-excursion
11460 (re-search-backward
11461 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
11462 (- (point) 20) t)))
11463 (apply 'encode-time (org-parse-time-string (match-string 1)))
11464 (current-time)))
11465 (default-input (and ts (org-get-compact-tod ts)))
11466 org-time-was-given org-end-time-was-given time)
11467 (cond
11468 ((and (org-at-timestamp-p)
11469 (eq last-command 'org-time-stamp)
11470 (eq this-command 'org-time-stamp))
11471 (insert "--")
11472 (setq time (let ((this-command this-command))
11473 (org-read-date arg 'totime nil nil default-time default-input)))
11474 (org-insert-time-stamp time (or org-time-was-given arg)))
11475 ((org-at-timestamp-p)
11476 (setq time (let ((this-command this-command))
11477 (org-read-date arg 'totime nil nil default-time default-input)))
11478 (when (org-at-timestamp-p) ; just to get the match data
11479 (replace-match "")
11480 (setq org-last-changed-timestamp
11481 (org-insert-time-stamp
11482 time (or org-time-was-given arg)
11483 nil nil nil (list org-end-time-was-given))))
11484 (message "Timestamp updated"))
11486 (setq time (let ((this-command this-command))
11487 (org-read-date arg 'totime nil nil default-time default-input)))
11488 (org-insert-time-stamp time (or org-time-was-given arg)
11489 nil nil nil (list org-end-time-was-given))))))
11491 ;; FIXME: can we use this for something else, like computing time differences?
11492 (defun org-get-compact-tod (s)
11493 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
11494 (let* ((t1 (match-string 1 s))
11495 (h1 (string-to-number (match-string 2 s)))
11496 (m1 (string-to-number (match-string 3 s)))
11497 (t2 (and (match-end 4) (match-string 5 s)))
11498 (h2 (and t2 (string-to-number (match-string 6 s))))
11499 (m2 (and t2 (string-to-number (match-string 7 s))))
11500 dh dm)
11501 (if (not t2)
11503 (setq dh (- h2 h1) dm (- m2 m1))
11504 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
11505 (concat t1 "+" (number-to-string dh)
11506 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
11508 (defun org-time-stamp-inactive (&optional arg)
11509 "Insert an inactive time stamp.
11510 An inactive time stamp is enclosed in square brackets instead of angle
11511 brackets. It is inactive in the sense that it does not trigger agenda entries,
11512 does not link to the calendar and cannot be changed with the S-cursor keys.
11513 So these are more for recording a certain time/date."
11514 (interactive "P")
11515 (let (org-time-was-given org-end-time-was-given time)
11516 (setq time (org-read-date arg 'totime))
11517 (org-insert-time-stamp time (or org-time-was-given arg) 'inactive
11518 nil nil (list org-end-time-was-given))))
11520 (defvar org-date-ovl (org-make-overlay 1 1))
11521 (org-overlay-put org-date-ovl 'face 'org-warning)
11522 (org-detach-overlay org-date-ovl)
11524 (defvar org-ans1) ; dynamically scoped parameter
11525 (defvar org-ans2) ; dynamically scoped parameter
11527 (defvar org-plain-time-of-day-regexp) ; defined below
11529 (defvar org-read-date-overlay nil)
11530 (defvar org-dcst nil) ; dynamically scoped
11532 (defun org-read-date (&optional with-time to-time from-string prompt
11533 default-time default-input)
11534 "Read a date, possibly a time, and make things smooth for the user.
11535 The prompt will suggest to enter an ISO date, but you can also enter anything
11536 which will at least partially be understood by `parse-time-string'.
11537 Unrecognized parts of the date will default to the current day, month, year,
11538 hour and minute. If this command is called to replace a timestamp at point,
11539 of to enter the second timestamp of a range, the default time is taken from the
11540 existing stamp. For example,
11541 3-2-5 --> 2003-02-05
11542 feb 15 --> currentyear-02-15
11543 sep 12 9 --> 2009-09-12
11544 12:45 --> today 12:45
11545 22 sept 0:34 --> currentyear-09-22 0:34
11546 12 --> currentyear-currentmonth-12
11547 Fri --> nearest Friday (today or later)
11548 etc.
11550 Furthermore you can specify a relative date by giving, as the *first* thing
11551 in the input: a plus/minus sign, a number and a letter [dwmy] to indicate
11552 change in days weeks, months, years.
11553 With a single plus or minus, the date is relative to today. With a double
11554 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
11555 +4d --> four days from today
11556 +4 --> same as above
11557 +2w --> two weeks from today
11558 ++5 --> five days from default date
11560 The function understands only English month and weekday abbreviations,
11561 but this can be configured with the variables `parse-time-months' and
11562 `parse-time-weekdays'.
11564 While prompting, a calendar is popped up - you can also select the
11565 date with the mouse (button 1). The calendar shows a period of three
11566 months. To scroll it to other months, use the keys `>' and `<'.
11567 If you don't like the calendar, turn it off with
11568 \(setq org-read-date-popup-calendar nil)
11570 With optional argument TO-TIME, the date will immediately be converted
11571 to an internal time.
11572 With an optional argument WITH-TIME, the prompt will suggest to also
11573 insert a time. Note that when WITH-TIME is not set, you can still
11574 enter a time, and this function will inform the calling routine about
11575 this change. The calling routine may then choose to change the format
11576 used to insert the time stamp into the buffer to include the time.
11577 With optional argument FROM-STRING, read from this string instead from
11578 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
11579 the time/date that is used for everything that is not specified by the
11580 user."
11581 (require 'parse-time)
11582 (let* ((org-time-stamp-rounding-minutes
11583 (if (equal with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
11584 (org-dcst org-display-custom-times)
11585 (ct (org-current-time))
11586 (def (or default-time ct))
11587 (defdecode (decode-time def))
11588 (dummy (progn
11589 (when (< (nth 2 defdecode) org-extend-today-until)
11590 (setcar (nthcdr 2 defdecode) -1)
11591 (setcar (nthcdr 1 defdecode) 59)
11592 (setq def (apply 'encode-time defdecode)
11593 defdecode (decode-time def)))))
11594 (calendar-move-hook nil)
11595 (view-diary-entries-initially nil)
11596 (view-calendar-holidays-initially nil)
11597 (timestr (format-time-string
11598 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") def))
11599 (prompt (concat (if prompt (concat prompt " ") "")
11600 (format "Date+time [%s]: " timestr)))
11601 ans (org-ans0 "") org-ans1 org-ans2 final)
11603 (cond
11604 (from-string (setq ans from-string))
11605 (org-read-date-popup-calendar
11606 (save-excursion
11607 (save-window-excursion
11608 (calendar)
11609 (calendar-forward-day (- (time-to-days def)
11610 (calendar-absolute-from-gregorian
11611 (calendar-current-date))))
11612 (org-eval-in-calendar nil t)
11613 (let* ((old-map (current-local-map))
11614 (map (copy-keymap calendar-mode-map))
11615 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
11616 (org-defkey map (kbd "RET") 'org-calendar-select)
11617 (org-defkey map (if (featurep 'xemacs) [button1] [mouse-1])
11618 'org-calendar-select-mouse)
11619 (org-defkey map (if (featurep 'xemacs) [button2] [mouse-2])
11620 'org-calendar-select-mouse)
11621 (org-defkey minibuffer-local-map [(meta shift left)]
11622 (lambda () (interactive)
11623 (org-eval-in-calendar '(calendar-backward-month 1))))
11624 (org-defkey minibuffer-local-map [(meta shift right)]
11625 (lambda () (interactive)
11626 (org-eval-in-calendar '(calendar-forward-month 1))))
11627 (org-defkey minibuffer-local-map [(meta shift up)]
11628 (lambda () (interactive)
11629 (org-eval-in-calendar '(calendar-backward-year 1))))
11630 (org-defkey minibuffer-local-map [(meta shift down)]
11631 (lambda () (interactive)
11632 (org-eval-in-calendar '(calendar-forward-year 1))))
11633 (org-defkey minibuffer-local-map [(shift up)]
11634 (lambda () (interactive)
11635 (org-eval-in-calendar '(calendar-backward-week 1))))
11636 (org-defkey minibuffer-local-map [(shift down)]
11637 (lambda () (interactive)
11638 (org-eval-in-calendar '(calendar-forward-week 1))))
11639 (org-defkey minibuffer-local-map [(shift left)]
11640 (lambda () (interactive)
11641 (org-eval-in-calendar '(calendar-backward-day 1))))
11642 (org-defkey minibuffer-local-map [(shift right)]
11643 (lambda () (interactive)
11644 (org-eval-in-calendar '(calendar-forward-day 1))))
11645 (org-defkey minibuffer-local-map ">"
11646 (lambda () (interactive)
11647 (org-eval-in-calendar '(scroll-calendar-left 1))))
11648 (org-defkey minibuffer-local-map "<"
11649 (lambda () (interactive)
11650 (org-eval-in-calendar '(scroll-calendar-right 1))))
11651 (unwind-protect
11652 (progn
11653 (use-local-map map)
11654 (add-hook 'post-command-hook 'org-read-date-display)
11655 (setq org-ans0 (read-string prompt default-input nil nil))
11656 ;; org-ans0: from prompt
11657 ;; org-ans1: from mouse click
11658 ;; org-ans2: from calendar motion
11659 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
11660 (remove-hook 'post-command-hook 'org-read-date-display)
11661 (use-local-map old-map)
11662 (when org-read-date-overlay
11663 (org-delete-overlay org-read-date-overlay)
11664 (setq org-read-date-overlay nil)))))))
11666 (t ; Naked prompt only
11667 (unwind-protect
11668 (setq ans (read-string prompt default-input nil timestr))
11669 (when org-read-date-overlay
11670 (org-delete-overlay org-read-date-overlay)
11671 (setq org-read-date-overlay nil)))))
11673 (setq final (org-read-date-analyze ans def defdecode))
11675 (if to-time
11676 (apply 'encode-time final)
11677 (if (and (boundp 'org-time-was-given) org-time-was-given)
11678 (format "%04d-%02d-%02d %02d:%02d"
11679 (nth 5 final) (nth 4 final) (nth 3 final)
11680 (nth 2 final) (nth 1 final))
11681 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
11682 (defvar def)
11683 (defvar defdecode)
11684 (defvar with-time)
11685 (defun org-read-date-display ()
11686 "Display the currrent date prompt interpretation in the minibuffer."
11687 (when org-read-date-display-live
11688 (when org-read-date-overlay
11689 (org-delete-overlay org-read-date-overlay))
11690 (let ((p (point)))
11691 (end-of-line 1)
11692 (while (not (equal (buffer-substring
11693 (max (point-min) (- (point) 4)) (point))
11694 " "))
11695 (insert " "))
11696 (goto-char p))
11697 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
11698 " " (or org-ans1 org-ans2)))
11699 (org-end-time-was-given nil)
11700 (f (org-read-date-analyze ans def defdecode))
11701 (fmts (if org-dcst
11702 org-time-stamp-custom-formats
11703 org-time-stamp-formats))
11704 (fmt (if (or with-time
11705 (and (boundp 'org-time-was-given) org-time-was-given))
11706 (cdr fmts)
11707 (car fmts)))
11708 (txt (concat "=> " (format-time-string fmt (apply 'encode-time f)))))
11709 (when (and org-end-time-was-given
11710 (string-match org-plain-time-of-day-regexp txt))
11711 (setq txt (concat (substring txt 0 (match-end 0)) "-"
11712 org-end-time-was-given
11713 (substring txt (match-end 0)))))
11714 (setq org-read-date-overlay
11715 (make-overlay (1- (point-at-eol)) (point-at-eol)))
11716 (org-overlay-display org-read-date-overlay txt 'secondary-selection))))
11718 (defun org-read-date-analyze (ans def defdecode)
11719 "Analyze the combined answer of the date prompt."
11720 ;; FIXME: cleanup and comment
11721 (let (delta deltan deltaw deltadef year month day
11722 hour minute second wday pm h2 m2 tl wday1
11723 iso-year iso-weekday iso-week iso-year iso-date)
11725 (when (setq delta (org-read-date-get-relative ans (current-time) def))
11726 (setq ans (replace-match "" t t ans)
11727 deltan (car delta)
11728 deltaw (nth 1 delta)
11729 deltadef (nth 2 delta)))
11731 ;; Check if there is an iso week date in there
11732 ;; If yes, sore the info and ostpone interpreting it until the rest
11733 ;; of the parsing is done
11734 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
11735 (setq iso-year (if (match-end 1) (org-small-year-to-year (string-to-number (match-string 1 ans))))
11736 iso-weekday (if (match-end 3) (string-to-number (match-string 3 ans)))
11737 iso-week (string-to-number (match-string 2 ans)))
11738 (setq ans (replace-match "" t t ans)))
11740 ;; Help matching ISO dates with single digit month ot day, like 2006-8-11.
11741 (when (string-match
11742 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
11743 (setq year (if (match-end 2)
11744 (string-to-number (match-string 2 ans))
11745 (string-to-number (format-time-string "%Y")))
11746 month (string-to-number (match-string 3 ans))
11747 day (string-to-number (match-string 4 ans)))
11748 (if (< year 100) (setq year (+ 2000 year)))
11749 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
11750 t nil ans)))
11751 ;; Help matching am/pm times, because `parse-time-string' does not do that.
11752 ;; If there is a time with am/pm, and *no* time without it, we convert
11753 ;; so that matching will be successful.
11754 (loop for i from 1 to 2 do ; twice, for end time as well
11755 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
11756 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
11757 (setq hour (string-to-number (match-string 1 ans))
11758 minute (if (match-end 3)
11759 (string-to-number (match-string 3 ans))
11761 pm (equal ?p
11762 (string-to-char (downcase (match-string 4 ans)))))
11763 (if (and (= hour 12) (not pm))
11764 (setq hour 0)
11765 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
11766 (setq ans (replace-match (format "%02d:%02d" hour minute)
11767 t t ans))))
11769 ;; Check if a time range is given as a duration
11770 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
11771 (setq hour (string-to-number (match-string 1 ans))
11772 h2 (+ hour (string-to-number (match-string 3 ans)))
11773 minute (string-to-number (match-string 2 ans))
11774 m2 (+ minute (if (match-end 5) (string-to-number
11775 (match-string 5 ans))0)))
11776 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
11777 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
11778 t t ans)))
11780 ;; Check if there is a time range
11781 (when (boundp 'org-end-time-was-given)
11782 (setq org-time-was-given nil)
11783 (when (and (string-match org-plain-time-of-day-regexp ans)
11784 (match-end 8))
11785 (setq org-end-time-was-given (match-string 8 ans))
11786 (setq ans (concat (substring ans 0 (match-beginning 7))
11787 (substring ans (match-end 7))))))
11789 (setq tl (parse-time-string ans)
11790 day (or (nth 3 tl) (nth 3 defdecode))
11791 month (or (nth 4 tl)
11792 (if (and org-read-date-prefer-future
11793 (nth 3 tl) (< (nth 3 tl) (nth 3 defdecode)))
11794 (1+ (nth 4 defdecode))
11795 (nth 4 defdecode)))
11796 year (or (nth 5 tl)
11797 (if (and org-read-date-prefer-future
11798 (nth 4 tl) (< (nth 4 tl) (nth 4 defdecode)))
11799 (1+ (nth 5 defdecode))
11800 (nth 5 defdecode)))
11801 hour (or (nth 2 tl) (nth 2 defdecode))
11802 minute (or (nth 1 tl) (nth 1 defdecode))
11803 second (or (nth 0 tl) 0)
11804 wday (nth 6 tl))
11806 ;; Special date definitions below
11807 (cond
11808 (iso-week
11809 ;; There was an iso week
11810 (setq year (or iso-year year)
11811 day (or iso-weekday wday 1)
11812 wday nil ; to make sure that the trigger below does not match
11813 iso-date (calendar-gregorian-from-absolute
11814 (calendar-absolute-from-iso
11815 (list iso-week day year))))
11816 ; FIXME: Should we also push ISO weeks into the future?
11817 ; (when (and org-read-date-prefer-future
11818 ; (not iso-year)
11819 ; (< (calendar-absolute-from-gregorian iso-date)
11820 ; (time-to-days (current-time))))
11821 ; (setq year (1+ year)
11822 ; iso-date (calendar-gregorian-from-absolute
11823 ; (calendar-absolute-from-iso
11824 ; (list iso-week day year)))))
11825 (setq month (car iso-date)
11826 year (nth 2 iso-date)
11827 day (nth 1 iso-date)))
11828 (deltan
11829 (unless deltadef
11830 (let ((now (decode-time (current-time))))
11831 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
11832 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
11833 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
11834 ((equal deltaw "m") (setq month (+ month deltan)))
11835 ((equal deltaw "y") (setq year (+ year deltan)))))
11836 ((and wday (not (nth 3 tl)))
11837 ;; Weekday was given, but no day, so pick that day in the week
11838 ;; on or after the derived date.
11839 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
11840 (unless (equal wday wday1)
11841 (setq day (+ day (% (- wday wday1 -7) 7))))))
11842 (if (and (boundp 'org-time-was-given)
11843 (nth 2 tl))
11844 (setq org-time-was-given t))
11845 (if (< year 100) (setq year (+ 2000 year)))
11846 (if (< year 1970) (setq year (nth 5 defdecode))) ; not representable
11847 (list second minute hour day month year)))
11849 (defvar parse-time-weekdays)
11851 (defun org-read-date-get-relative (s today default)
11852 "Check string S for special relative date string.
11853 TODAY and DEFAULT are internal times, for today and for a default.
11854 Return shift list (N what def-flag)
11855 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
11856 N is the number of WHATs to shift.
11857 DEF-FLAG is t when a double ++ or -- indicates shift relative to
11858 the DEFAULT date rather than TODAY."
11859 (when (string-match
11860 (concat
11861 "\\`[ \t]*\\([-+]\\{1,2\\}\\)"
11862 "\\([0-9]+\\)?"
11863 "\\([dwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
11864 "\\([ \t]\\|$\\)") s)
11865 (let* ((dir (if (match-end 1)
11866 (string-to-char (substring (match-string 1 s) -1))
11867 ?+))
11868 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
11869 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
11870 (what (if (match-end 3) (match-string 3 s) "d"))
11871 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
11872 (date (if rel default today))
11873 (wday (nth 6 (decode-time date)))
11874 delta)
11875 (if wday1
11876 (progn
11877 (setq delta (mod (+ 7 (- wday1 wday)) 7))
11878 (if (= dir ?-) (setq delta (- delta 7)))
11879 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
11880 (list delta "d" rel))
11881 (list (* n (if (= dir ?-) -1 1)) what rel)))))
11883 (defun org-eval-in-calendar (form &optional keepdate)
11884 "Eval FORM in the calendar window and return to current window.
11885 Also, store the cursor date in variable org-ans2."
11886 (let ((sw (selected-window)))
11887 (select-window (get-buffer-window "*Calendar*"))
11888 (eval form)
11889 (when (and (not keepdate) (calendar-cursor-to-date))
11890 (let* ((date (calendar-cursor-to-date))
11891 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
11892 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
11893 (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
11894 (select-window sw)))
11896 ; ;; Update the prompt to show new default date
11897 ; (save-excursion
11898 ; (goto-char (point-min))
11899 ; (when (and org-ans2
11900 ; (re-search-forward "\\[[-0-9]+\\]" nil t)
11901 ; (get-text-property (match-end 0) 'field))
11902 ; (let ((inhibit-read-only t))
11903 ; (replace-match (concat "[" org-ans2 "]") t t)
11904 ; (add-text-properties (point-min) (1+ (match-end 0))
11905 ; (text-properties-at (1+ (point-min)))))))))
11907 (defun org-calendar-select ()
11908 "Return to `org-read-date' with the date currently selected.
11909 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
11910 (interactive)
11911 (when (calendar-cursor-to-date)
11912 (let* ((date (calendar-cursor-to-date))
11913 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
11914 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
11915 (if (active-minibuffer-window) (exit-minibuffer))))
11917 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
11918 "Insert a date stamp for the date given by the internal TIME.
11919 WITH-HM means, use the stamp format that includes the time of the day.
11920 INACTIVE means use square brackets instead of angular ones, so that the
11921 stamp will not contribute to the agenda.
11922 PRE and POST are optional strings to be inserted before and after the
11923 stamp.
11924 The command returns the inserted time stamp."
11925 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
11926 stamp)
11927 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
11928 (insert-before-markers (or pre ""))
11929 (insert-before-markers (setq stamp (format-time-string fmt time)))
11930 (when (listp extra)
11931 (setq extra (car extra))
11932 (if (and (stringp extra)
11933 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
11934 (setq extra (format "-%02d:%02d"
11935 (string-to-number (match-string 1 extra))
11936 (string-to-number (match-string 2 extra))))
11937 (setq extra nil)))
11938 (when extra
11939 (backward-char 1)
11940 (insert-before-markers extra)
11941 (forward-char 1))
11942 (insert-before-markers (or post ""))
11943 stamp))
11945 (defun org-toggle-time-stamp-overlays ()
11946 "Toggle the use of custom time stamp formats."
11947 (interactive)
11948 (setq org-display-custom-times (not org-display-custom-times))
11949 (unless org-display-custom-times
11950 (let ((p (point-min)) (bmp (buffer-modified-p)))
11951 (while (setq p (next-single-property-change p 'display))
11952 (if (and (get-text-property p 'display)
11953 (eq (get-text-property p 'face) 'org-date))
11954 (remove-text-properties
11955 p (setq p (next-single-property-change p 'display))
11956 '(display t))))
11957 (set-buffer-modified-p bmp)))
11958 (if (featurep 'xemacs)
11959 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
11960 (org-restart-font-lock)
11961 (setq org-table-may-need-update t)
11962 (if org-display-custom-times
11963 (message "Time stamps are overlayed with custom format")
11964 (message "Time stamp overlays removed")))
11966 (defun org-display-custom-time (beg end)
11967 "Overlay modified time stamp format over timestamp between BED and END."
11968 (let* ((ts (buffer-substring beg end))
11969 t1 w1 with-hm tf time str w2 (off 0))
11970 (save-match-data
11971 (setq t1 (org-parse-time-string ts t))
11972 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[dwmy]\\)?\\'" ts)
11973 (setq off (- (match-end 0) (match-beginning 0)))))
11974 (setq end (- end off))
11975 (setq w1 (- end beg)
11976 with-hm (and (nth 1 t1) (nth 2 t1))
11977 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
11978 time (org-fix-decoded-time t1)
11979 str (org-add-props
11980 (format-time-string
11981 (substring tf 1 -1) (apply 'encode-time time))
11982 nil 'mouse-face 'highlight)
11983 w2 (length str))
11984 (if (not (= w2 w1))
11985 (add-text-properties (1+ beg) (+ 2 beg)
11986 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
11987 (if (featurep 'xemacs)
11988 (progn
11989 (put-text-property beg end 'invisible t)
11990 (put-text-property beg end 'end-glyph (make-glyph str)))
11991 (put-text-property beg end 'display str))))
11993 (defun org-translate-time (string)
11994 "Translate all timestamps in STRING to custom format.
11995 But do this only if the variable `org-display-custom-times' is set."
11996 (when org-display-custom-times
11997 (save-match-data
11998 (let* ((start 0)
11999 (re org-ts-regexp-both)
12000 t1 with-hm inactive tf time str beg end)
12001 (while (setq start (string-match re string start))
12002 (setq beg (match-beginning 0)
12003 end (match-end 0)
12004 t1 (save-match-data
12005 (org-parse-time-string (substring string beg end) t))
12006 with-hm (and (nth 1 t1) (nth 2 t1))
12007 inactive (equal (substring string beg (1+ beg)) "[")
12008 tf (funcall (if with-hm 'cdr 'car)
12009 org-time-stamp-custom-formats)
12010 time (org-fix-decoded-time t1)
12011 str (format-time-string
12012 (concat
12013 (if inactive "[" "<") (substring tf 1 -1)
12014 (if inactive "]" ">"))
12015 (apply 'encode-time time))
12016 string (replace-match str t t string)
12017 start (+ start (length str)))))))
12018 string)
12020 (defun org-fix-decoded-time (time)
12021 "Set 0 instead of nil for the first 6 elements of time.
12022 Don't touch the rest."
12023 (let ((n 0))
12024 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
12026 (defun org-days-to-time (timestamp-string)
12027 "Difference between TIMESTAMP-STRING and now in days."
12028 (- (time-to-days (org-time-string-to-time timestamp-string))
12029 (time-to-days (current-time))))
12031 (defun org-deadline-close (timestamp-string &optional ndays)
12032 "Is the time in TIMESTAMP-STRING close to the current date?"
12033 (setq ndays (or ndays (org-get-wdays timestamp-string)))
12034 (and (< (org-days-to-time timestamp-string) ndays)
12035 (not (org-entry-is-done-p))))
12037 (defun org-get-wdays (ts)
12038 "Get the deadline lead time appropriate for timestring TS."
12039 (cond
12040 ((<= org-deadline-warning-days 0)
12041 ;; 0 or negative, enforce this value no matter what
12042 (- org-deadline-warning-days))
12043 ((string-match "-\\([0-9]+\\)\\([dwmy]\\)\\(\\'\\|>\\)" ts)
12044 ;; lead time is specified.
12045 (floor (* (string-to-number (match-string 1 ts))
12046 (cdr (assoc (match-string 2 ts)
12047 '(("d" . 1) ("w" . 7)
12048 ("m" . 30.4) ("y" . 365.25)))))))
12049 ;; go for the default.
12050 (t org-deadline-warning-days)))
12052 (defun org-calendar-select-mouse (ev)
12053 "Return to `org-read-date' with the date currently selected.
12054 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
12055 (interactive "e")
12056 (mouse-set-point ev)
12057 (when (calendar-cursor-to-date)
12058 (let* ((date (calendar-cursor-to-date))
12059 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
12060 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
12061 (if (active-minibuffer-window) (exit-minibuffer))))
12063 (defun org-check-deadlines (ndays)
12064 "Check if there are any deadlines due or past due.
12065 A deadline is considered due if it happens within `org-deadline-warning-days'
12066 days from today's date. If the deadline appears in an entry marked DONE,
12067 it is not shown. The prefix arg NDAYS can be used to test that many
12068 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
12069 (interactive "P")
12070 (let* ((org-warn-days
12071 (cond
12072 ((equal ndays '(4)) 100000)
12073 (ndays (prefix-numeric-value ndays))
12074 (t (abs org-deadline-warning-days))))
12075 (case-fold-search nil)
12076 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
12077 (callback
12078 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
12080 (message "%d deadlines past-due or due within %d days"
12081 (org-occur regexp nil callback)
12082 org-warn-days)))
12084 (defun org-check-before-date (date)
12085 "Check if there are deadlines or scheduled entries before DATE."
12086 (interactive (list (org-read-date)))
12087 (let ((case-fold-search nil)
12088 (regexp (concat "\\<\\(" org-deadline-string
12089 "\\|" org-scheduled-string
12090 "\\) *<\\([^>]+\\)>"))
12091 (callback
12092 (lambda () (time-less-p
12093 (org-time-string-to-time (match-string 2))
12094 (org-time-string-to-time date)))))
12095 (message "%d entries before %s"
12096 (org-occur regexp nil callback) date)))
12098 (defun org-evaluate-time-range (&optional to-buffer)
12099 "Evaluate a time range by computing the difference between start and end.
12100 Normally the result is just printed in the echo area, but with prefix arg
12101 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
12102 If the time range is actually in a table, the result is inserted into the
12103 next column.
12104 For time difference computation, a year is assumed to be exactly 365
12105 days in order to avoid rounding problems."
12106 (interactive "P")
12108 (org-clock-update-time-maybe)
12109 (save-excursion
12110 (unless (org-at-date-range-p t)
12111 (goto-char (point-at-bol))
12112 (re-search-forward org-tr-regexp-both (point-at-eol) t))
12113 (if (not (org-at-date-range-p t))
12114 (error "Not at a time-stamp range, and none found in current line")))
12115 (let* ((ts1 (match-string 1))
12116 (ts2 (match-string 2))
12117 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
12118 (match-end (match-end 0))
12119 (time1 (org-time-string-to-time ts1))
12120 (time2 (org-time-string-to-time ts2))
12121 (t1 (time-to-seconds time1))
12122 (t2 (time-to-seconds time2))
12123 (diff (abs (- t2 t1)))
12124 (negative (< (- t2 t1) 0))
12125 ;; (ys (floor (* 365 24 60 60)))
12126 (ds (* 24 60 60))
12127 (hs (* 60 60))
12128 (fy "%dy %dd %02d:%02d")
12129 (fy1 "%dy %dd")
12130 (fd "%dd %02d:%02d")
12131 (fd1 "%dd")
12132 (fh "%02d:%02d")
12133 y d h m align)
12134 (if havetime
12135 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
12137 d (floor (/ diff ds)) diff (mod diff ds)
12138 h (floor (/ diff hs)) diff (mod diff hs)
12139 m (floor (/ diff 60)))
12140 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
12142 d (floor (+ (/ diff ds) 0.5))
12143 h 0 m 0))
12144 (if (not to-buffer)
12145 (message "%s" (org-make-tdiff-string y d h m))
12146 (if (org-at-table-p)
12147 (progn
12148 (goto-char match-end)
12149 (setq align t)
12150 (and (looking-at " *|") (goto-char (match-end 0))))
12151 (goto-char match-end))
12152 (if (looking-at
12153 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
12154 (replace-match ""))
12155 (if negative (insert " -"))
12156 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
12157 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
12158 (insert " " (format fh h m))))
12159 (if align (org-table-align))
12160 (message "Time difference inserted")))))
12162 (defun org-make-tdiff-string (y d h m)
12163 (let ((fmt "")
12164 (l nil))
12165 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
12166 l (push y l)))
12167 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
12168 l (push d l)))
12169 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
12170 l (push h l)))
12171 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
12172 l (push m l)))
12173 (apply 'format fmt (nreverse l))))
12175 (defun org-time-string-to-time (s)
12176 (apply 'encode-time (org-parse-time-string s)))
12178 (defun org-time-string-to-absolute (s &optional daynr prefer show-all)
12179 "Convert a time stamp to an absolute day number.
12180 If there is a specifyer for a cyclic time stamp, get the closest date to
12181 DAYNR.
12182 PREFER and SHOW_ALL are passed through to `org-closest-date'."
12183 (cond
12184 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
12185 (if (org-diary-sexp-entry (match-string 1 s) "" date)
12186 daynr
12187 (+ daynr 1000)))
12188 ((and daynr (string-match "\\+[0-9]+[dwmy]" s))
12189 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
12190 (time-to-days (current-time))) (match-string 0 s)
12191 prefer show-all))
12192 (t (time-to-days (apply 'encode-time (org-parse-time-string s))))))
12194 (defun org-days-to-iso-week (days)
12195 "Return the iso week number."
12196 (require 'cal-iso)
12197 (car (calendar-iso-from-absolute days)))
12199 (defun org-small-year-to-year (year)
12200 "Convert 2-digit years into 4-digit years.
12201 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
12202 The year 2000 cannot be abbreviated. Any year lager than 99
12203 is retrned unchanged."
12204 (if (< year 38)
12205 (setq year (+ 2000 year))
12206 (if (< year 100)
12207 (setq year (+ 1900 year))))
12208 year)
12210 (defun org-time-from-absolute (d)
12211 "Return the time corresponding to date D.
12212 D may be an absolute day number, or a calendar-type list (month day year)."
12213 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
12214 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
12216 (defun org-calendar-holiday ()
12217 "List of holidays, for Diary display in Org-mode."
12218 (require 'holidays)
12219 (let ((hl (funcall
12220 (if (fboundp 'calendar-check-holidays)
12221 'calendar-check-holidays 'check-calendar-holidays) date)))
12222 (if hl (mapconcat 'identity hl "; "))))
12224 (defun org-diary-sexp-entry (sexp entry date)
12225 "Process a SEXP diary ENTRY for DATE."
12226 (require 'diary-lib)
12227 (let ((result (if calendar-debug-sexp
12228 (let ((stack-trace-on-error t))
12229 (eval (car (read-from-string sexp))))
12230 (condition-case nil
12231 (eval (car (read-from-string sexp)))
12232 (error
12233 (beep)
12234 (message "Bad sexp at line %d in %s: %s"
12235 (org-current-line)
12236 (buffer-file-name) sexp)
12237 (sleep-for 2))))))
12238 (cond ((stringp result) result)
12239 ((and (consp result)
12240 (stringp (cdr result))) (cdr result))
12241 (result entry)
12242 (t nil))))
12244 (defun org-diary-to-ical-string (frombuf)
12245 "Get iCalendar entries from diary entries in buffer FROMBUF.
12246 This uses the icalendar.el library."
12247 (let* ((tmpdir (if (featurep 'xemacs)
12248 (temp-directory)
12249 temporary-file-directory))
12250 (tmpfile (make-temp-name
12251 (expand-file-name "orgics" tmpdir)))
12252 buf rtn b e)
12253 (save-excursion
12254 (set-buffer frombuf)
12255 (icalendar-export-region (point-min) (point-max) tmpfile)
12256 (setq buf (find-buffer-visiting tmpfile))
12257 (set-buffer buf)
12258 (goto-char (point-min))
12259 (if (re-search-forward "^BEGIN:VEVENT" nil t)
12260 (setq b (match-beginning 0)))
12261 (goto-char (point-max))
12262 (if (re-search-backward "^END:VEVENT" nil t)
12263 (setq e (match-end 0)))
12264 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
12265 (kill-buffer buf)
12266 (kill-buffer frombuf)
12267 (delete-file tmpfile)
12268 rtn))
12270 (defun org-closest-date (start current change prefer show-all)
12271 "Find the date closest to CURRENT that is consistent with START and CHANGE.
12272 When PREFER is `past' return a date that is either CURRENT or past.
12273 When PREFER is `future', return a date that is either CURRENT or future.
12274 When SHOW-ALL is nil, only return the current occurence of a time stamp."
12275 ;; Make the proper lists from the dates
12276 (catch 'exit
12277 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
12278 dn dw sday cday n1 n2
12279 d m y y1 y2 date1 date2 nmonths nm ny m2)
12281 (setq start (org-date-to-gregorian start)
12282 current (org-date-to-gregorian
12283 (if show-all
12284 current
12285 (time-to-days (current-time))))
12286 sday (calendar-absolute-from-gregorian start)
12287 cday (calendar-absolute-from-gregorian current))
12289 (if (<= cday sday) (throw 'exit sday))
12291 (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
12292 (setq dn (string-to-number (match-string 1 change))
12293 dw (cdr (assoc (match-string 2 change) a1)))
12294 (error "Invalid change specifyer: %s" change))
12295 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
12296 (cond
12297 ((eq dw 'day)
12298 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
12299 n2 (+ n1 dn)))
12300 ((eq dw 'year)
12301 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
12302 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
12303 (setq date1 (list m d y1)
12304 n1 (calendar-absolute-from-gregorian date1)
12305 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
12306 n2 (calendar-absolute-from-gregorian date2)))
12307 ((eq dw 'month)
12308 ;; approx number of month between the tow dates
12309 (setq nmonths (floor (/ (- cday sday) 30.436875)))
12310 ;; How often does dn fit in there?
12311 (setq d (nth 1 start) m (car start) y (nth 2 start)
12312 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
12313 m (+ m nm)
12314 ny (floor (/ m 12))
12315 y (+ y ny)
12316 m (- m (* ny 12)))
12317 (while (> m 12) (setq m (- m 12) y (1+ y)))
12318 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
12319 (setq m2 (+ m dn) y2 y)
12320 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
12321 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
12322 (while (< n2 cday)
12323 (setq n1 n2 m m2 y y2)
12324 (setq m2 (+ m dn) y2 y)
12325 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
12326 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
12328 (if show-all
12329 (cond
12330 ((eq prefer 'past) n1)
12331 ((eq prefer 'future) (if (= cday n1) n1 n2))
12332 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
12333 (cond
12334 ((eq prefer 'past) n1)
12335 ((eq prefer 'future) (if (= cday n1) n1 n2))
12336 (t (if (= cday n1) n1 n2)))))))
12338 (defun org-date-to-gregorian (date)
12339 "Turn any specification of DATE into a gregorian date for the calendar."
12340 (cond ((integerp date) (calendar-gregorian-from-absolute date))
12341 ((and (listp date) (= (length date) 3)) date)
12342 ((stringp date)
12343 (setq date (org-parse-time-string date))
12344 (list (nth 4 date) (nth 3 date) (nth 5 date)))
12345 ((listp date)
12346 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
12348 (defun org-parse-time-string (s &optional nodefault)
12349 "Parse the standard Org-mode time string.
12350 This should be a lot faster than the normal `parse-time-string'.
12351 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
12352 hour and minute fields will be nil if not given."
12353 (if (string-match org-ts-regexp0 s)
12354 (list 0
12355 (if (or (match-beginning 8) (not nodefault))
12356 (string-to-number (or (match-string 8 s) "0")))
12357 (if (or (match-beginning 7) (not nodefault))
12358 (string-to-number (or (match-string 7 s) "0")))
12359 (string-to-number (match-string 4 s))
12360 (string-to-number (match-string 3 s))
12361 (string-to-number (match-string 2 s))
12362 nil nil nil)
12363 (make-list 9 0)))
12365 (defun org-timestamp-up (&optional arg)
12366 "Increase the date item at the cursor by one.
12367 If the cursor is on the year, change the year. If it is on the month or
12368 the day, change that.
12369 With prefix ARG, change by that many units."
12370 (interactive "p")
12371 (org-timestamp-change (prefix-numeric-value arg)))
12373 (defun org-timestamp-down (&optional arg)
12374 "Decrease the date item at the cursor by one.
12375 If the cursor is on the year, change the year. If it is on the month or
12376 the day, change that.
12377 With prefix ARG, change by that many units."
12378 (interactive "p")
12379 (org-timestamp-change (- (prefix-numeric-value arg))))
12381 (defun org-timestamp-up-day (&optional arg)
12382 "Increase the date in the time stamp by one day.
12383 With prefix ARG, change that many days."
12384 (interactive "p")
12385 (if (and (not (org-at-timestamp-p t))
12386 (org-on-heading-p))
12387 (org-todo 'up)
12388 (org-timestamp-change (prefix-numeric-value arg) 'day)))
12390 (defun org-timestamp-down-day (&optional arg)
12391 "Decrease the date in the time stamp by one day.
12392 With prefix ARG, change that many days."
12393 (interactive "p")
12394 (if (and (not (org-at-timestamp-p t))
12395 (org-on-heading-p))
12396 (org-todo 'down)
12397 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
12399 (defun org-at-timestamp-p (&optional inactive-ok)
12400 "Determine if the cursor is in or at a timestamp."
12401 (interactive)
12402 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
12403 (pos (point))
12404 (ans (or (looking-at tsr)
12405 (save-excursion
12406 (skip-chars-backward "^[<\n\r\t")
12407 (if (> (point) (point-min)) (backward-char 1))
12408 (and (looking-at tsr)
12409 (> (- (match-end 0) pos) -1))))))
12410 (and ans
12411 (boundp 'org-ts-what)
12412 (setq org-ts-what
12413 (cond
12414 ((= pos (match-beginning 0)) 'bracket)
12415 ((= pos (1- (match-end 0))) 'bracket)
12416 ((org-pos-in-match-range pos 2) 'year)
12417 ((org-pos-in-match-range pos 3) 'month)
12418 ((org-pos-in-match-range pos 7) 'hour)
12419 ((org-pos-in-match-range pos 8) 'minute)
12420 ((or (org-pos-in-match-range pos 4)
12421 (org-pos-in-match-range pos 5)) 'day)
12422 ((and (> pos (or (match-end 8) (match-end 5)))
12423 (< pos (match-end 0)))
12424 (- pos (or (match-end 8) (match-end 5))))
12425 (t 'day))))
12426 ans))
12428 (defun org-toggle-timestamp-type ()
12429 "Toggle the type (<active> or [inactive]) of a time stamp."
12430 (interactive)
12431 (when (org-at-timestamp-p t)
12432 (save-excursion
12433 (goto-char (match-beginning 0))
12434 (insert (if (equal (char-after) ?<) "[" "<")) (delete-char 1)
12435 (goto-char (1- (match-end 0)))
12436 (insert (if (equal (char-after) ?>) "]" ">")) (delete-char 1))
12437 (message "Timestamp is now %sactive"
12438 (if (equal (char-before) ?>) "in" ""))))
12440 (defun org-timestamp-change (n &optional what)
12441 "Change the date in the time stamp at point.
12442 The date will be changed by N times WHAT. WHAT can be `day', `month',
12443 `year', `minute', `second'. If WHAT is not given, the cursor position
12444 in the timestamp determines what will be changed."
12445 (let ((pos (point))
12446 with-hm inactive
12447 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
12448 org-ts-what
12449 extra rem
12450 ts time time0)
12451 (if (not (org-at-timestamp-p t))
12452 (error "Not at a timestamp"))
12453 (if (and (not what) (eq org-ts-what 'bracket))
12454 (org-toggle-timestamp-type)
12455 (if (and (not what) (not (eq org-ts-what 'day))
12456 org-display-custom-times
12457 (get-text-property (point) 'display)
12458 (not (get-text-property (1- (point)) 'display)))
12459 (setq org-ts-what 'day))
12460 (setq org-ts-what (or what org-ts-what)
12461 inactive (= (char-after (match-beginning 0)) ?\[)
12462 ts (match-string 0))
12463 (replace-match "")
12464 (if (string-match
12465 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[dwmy]\\)*\\)[]>]"
12467 (setq extra (match-string 1 ts)))
12468 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
12469 (setq with-hm t))
12470 (setq time0 (org-parse-time-string ts))
12471 (when (and (eq org-ts-what 'minute)
12472 (eq current-prefix-arg nil))
12473 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
12474 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
12475 (setcar (cdr time0) (+ (nth 1 time0)
12476 (if (> n 0) (- rem) (- dm rem))))))
12477 (setq time
12478 (encode-time (or (car time0) 0)
12479 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
12480 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
12481 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
12482 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
12483 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
12484 (nthcdr 6 time0)))
12485 (when (integerp org-ts-what)
12486 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
12487 (if (eq what 'calendar)
12488 (let ((cal-date (org-get-date-from-calendar)))
12489 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
12490 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
12491 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
12492 (setcar time0 (or (car time0) 0))
12493 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
12494 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
12495 (setq time (apply 'encode-time time0))))
12496 (setq org-last-changed-timestamp
12497 (org-insert-time-stamp time with-hm inactive nil nil extra))
12498 (org-clock-update-time-maybe)
12499 (goto-char pos)
12500 ;; Try to recenter the calendar window, if any
12501 (if (and org-calendar-follow-timestamp-change
12502 (get-buffer-window "*Calendar*" t)
12503 (memq org-ts-what '(day month year)))
12504 (org-recenter-calendar (time-to-days time))))))
12506 (defun org-modify-ts-extra (s pos n dm)
12507 "Change the different parts of the lead-time and repeat fields in timestamp."
12508 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
12509 ng h m new rem)
12510 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
12511 (cond
12512 ((or (org-pos-in-match-range pos 2)
12513 (org-pos-in-match-range pos 3))
12514 (setq m (string-to-number (match-string 3 s))
12515 h (string-to-number (match-string 2 s)))
12516 (if (org-pos-in-match-range pos 2)
12517 (setq h (+ h n))
12518 (setq n (* dm (org-no-warnings (signum n))))
12519 (when (not (= 0 (setq rem (% m dm))))
12520 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
12521 (setq m (+ m n)))
12522 (if (< m 0) (setq m (+ m 60) h (1- h)))
12523 (if (> m 59) (setq m (- m 60) h (1+ h)))
12524 (setq h (min 24 (max 0 h)))
12525 (setq ng 1 new (format "-%02d:%02d" h m)))
12526 ((org-pos-in-match-range pos 6)
12527 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
12528 ((org-pos-in-match-range pos 5)
12529 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
12531 ((org-pos-in-match-range pos 9)
12532 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
12533 ((org-pos-in-match-range pos 8)
12534 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
12536 (when ng
12537 (setq s (concat
12538 (substring s 0 (match-beginning ng))
12540 (substring s (match-end ng))))))
12543 (defun org-recenter-calendar (date)
12544 "If the calendar is visible, recenter it to DATE."
12545 (let* ((win (selected-window))
12546 (cwin (get-buffer-window "*Calendar*" t))
12547 (calendar-move-hook nil))
12548 (when cwin
12549 (select-window cwin)
12550 (calendar-goto-date (if (listp date) date
12551 (calendar-gregorian-from-absolute date)))
12552 (select-window win))))
12554 (defun org-goto-calendar (&optional arg)
12555 "Go to the Emacs calendar at the current date.
12556 If there is a time stamp in the current line, go to that date.
12557 A prefix ARG can be used to force the current date."
12558 (interactive "P")
12559 (let ((tsr org-ts-regexp) diff
12560 (calendar-move-hook nil)
12561 (view-calendar-holidays-initially nil)
12562 (view-diary-entries-initially nil))
12563 (if (or (org-at-timestamp-p)
12564 (save-excursion
12565 (beginning-of-line 1)
12566 (looking-at (concat ".*" tsr))))
12567 (let ((d1 (time-to-days (current-time)))
12568 (d2 (time-to-days
12569 (org-time-string-to-time (match-string 1)))))
12570 (setq diff (- d2 d1))))
12571 (calendar)
12572 (calendar-goto-today)
12573 (if (and diff (not arg)) (calendar-forward-day diff))))
12575 (defun org-get-date-from-calendar ()
12576 "Return a list (month day year) of date at point in calendar."
12577 (with-current-buffer "*Calendar*"
12578 (save-match-data
12579 (calendar-cursor-to-date))))
12581 (defun org-date-from-calendar ()
12582 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
12583 If there is already a time stamp at the cursor position, update it."
12584 (interactive)
12585 (if (org-at-timestamp-p t)
12586 (org-timestamp-change 0 'calendar)
12587 (let ((cal-date (org-get-date-from-calendar)))
12588 (org-insert-time-stamp
12589 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
12591 (defun org-minutes-to-hours (m)
12592 "Compute H:MM from a number of minutes."
12593 (let ((h (/ m 60)))
12594 (setq m (- m (* 60 h)))
12595 (format "%d:%02d" h m)))
12598 ;;;; Agenda files
12600 ;;;###autoload
12601 (defun org-iswitchb (&optional arg)
12602 "Use `iswitchb-read-buffer' to prompt for an Org buffer to switch to.
12603 With a prefix argument, restrict available to files.
12604 With two prefix arguments, restrict available buffers to agenda files.
12606 Due to some yet unresolved reason, global function
12607 `iswitchb-mode' needs to be active for this function to work."
12608 (interactive "P")
12609 (eval-when-compile
12610 (require 'iswitchb))
12611 (let ((enabled iswitchb-mode) blist)
12612 (or enabled (iswitchb-mode 1))
12613 (setq blist (cond ((equal arg '(4)) (org-buffer-list 'files))
12614 ((equal arg '(16)) (org-buffer-list 'agenda))
12615 (t (org-buffer-list))))
12616 (unwind-protect
12617 (let ((iswitchb-make-buflist-hook
12618 (lambda ()
12619 (setq iswitchb-temp-buflist
12620 (mapcar 'buffer-name blist)))))
12621 (switch-to-buffer
12622 (iswitchb-read-buffer
12623 "Switch-to: " nil t))
12624 (or enabled (iswitchb-mode -1))))))
12626 (defun org-buffer-list (&optional predicate tmp)
12627 "Return a list of Org buffers.
12628 PREDICATE can be either 'export, 'files or 'agenda.
12630 'export restrict the list to Export buffers.
12631 'files restrict the list to buffers visiting Org files.
12632 'agenda restrict the list to buffers visiting agenda files.
12634 If TMP is non-nil, don't include temporary buffers."
12635 (let (filter blist)
12636 (setq filter
12637 (cond ((eq predicate 'files) "\.org$")
12638 ((eq predicate 'export) "\*Org .*Export")
12639 (t "\*Org \\|\.org$")))
12640 (setq blist
12641 (mapcar
12642 (lambda(b)
12643 (let ((bname (buffer-name b))
12644 (bfile (buffer-file-name b)))
12645 (if (and (string-match filter bname)
12646 (if (eq predicate 'agenda)
12647 (member bfile
12648 (mapcar (lambda(f) (file-truename f))
12649 org-agenda-files)) t)
12650 (if tmp (not (string-match "tmp" bname)) t)) b)))
12651 (buffer-list)))
12652 (delete nil blist)))
12654 (defun org-agenda-files (&optional unrestricted)
12655 "Get the list of agenda files.
12656 Optional UNRESTRICTED means return the full list even if a restriction
12657 is currently in place."
12658 (let ((files
12659 (cond
12660 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
12661 ((stringp org-agenda-files) (org-read-agenda-file-list))
12662 ((listp org-agenda-files) org-agenda-files)
12663 (t (error "Invalid value of `org-agenda-files'")))))
12664 (setq files (apply 'append
12665 (mapcar (lambda (f)
12666 (if (file-directory-p f)
12667 (directory-files f t
12668 org-agenda-file-regexp)
12669 (list f)))
12670 files)))
12671 (if org-agenda-skip-unavailable-files
12672 (delq nil
12673 (mapcar (function
12674 (lambda (file)
12675 (and (file-readable-p file) file)))
12676 files))
12677 files))) ; `org-check-agenda-file' will remove them from the list
12679 (defun org-edit-agenda-file-list ()
12680 "Edit the list of agenda files.
12681 Depending on setup, this either uses customize to edit the variable
12682 `org-agenda-files', or it visits the file that is holding the list. In the
12683 latter case, the buffer is set up in a way that saving it automatically kills
12684 the buffer and restores the previous window configuration."
12685 (interactive)
12686 (if (stringp org-agenda-files)
12687 (let ((cw (current-window-configuration)))
12688 (find-file org-agenda-files)
12689 (org-set-local 'org-window-configuration cw)
12690 (org-add-hook 'after-save-hook
12691 (lambda ()
12692 (set-window-configuration
12693 (prog1 org-window-configuration
12694 (kill-buffer (current-buffer))))
12695 (org-install-agenda-files-menu)
12696 (message "New agenda file list installed"))
12697 nil 'local)
12698 (message "%s" (substitute-command-keys
12699 "Edit list and finish with \\[save-buffer]")))
12700 (customize-variable 'org-agenda-files)))
12702 (defun org-store-new-agenda-file-list (list)
12703 "Set new value for the agenda file list and save it correcly."
12704 (if (stringp org-agenda-files)
12705 (let ((f org-agenda-files) b)
12706 (while (setq b (find-buffer-visiting f)) (kill-buffer b))
12707 (with-temp-file f
12708 (insert (mapconcat 'identity list "\n") "\n")))
12709 (let ((org-mode-hook nil) (default-major-mode 'fundamental-mode))
12710 (setq org-agenda-files list)
12711 (customize-save-variable 'org-agenda-files org-agenda-files))))
12713 (defun org-read-agenda-file-list ()
12714 "Read the list of agenda files from a file."
12715 (when (stringp org-agenda-files)
12716 (with-temp-buffer
12717 (insert-file-contents org-agenda-files)
12718 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*"))))
12721 ;;;###autoload
12722 (defun org-cycle-agenda-files ()
12723 "Cycle through the files in `org-agenda-files'.
12724 If the current buffer visits an agenda file, find the next one in the list.
12725 If the current buffer does not, find the first agenda file."
12726 (interactive)
12727 (let* ((fs (org-agenda-files t))
12728 (files (append fs (list (car fs))))
12729 (tcf (if buffer-file-name (file-truename buffer-file-name)))
12730 file)
12731 (unless files (error "No agenda files"))
12732 (catch 'exit
12733 (while (setq file (pop files))
12734 (if (equal (file-truename file) tcf)
12735 (when (car files)
12736 (find-file (car files))
12737 (throw 'exit t))))
12738 (find-file (car fs)))
12739 (if (buffer-base-buffer) (switch-to-buffer (buffer-base-buffer)))))
12741 (defun org-agenda-file-to-front (&optional to-end)
12742 "Move/add the current file to the top of the agenda file list.
12743 If the file is not present in the list, it is added to the front. If it is
12744 present, it is moved there. With optional argument TO-END, add/move to the
12745 end of the list."
12746 (interactive "P")
12747 (let ((org-agenda-skip-unavailable-files nil)
12748 (file-alist (mapcar (lambda (x)
12749 (cons (file-truename x) x))
12750 (org-agenda-files t)))
12751 (ctf (file-truename buffer-file-name))
12752 x had)
12753 (setq x (assoc ctf file-alist) had x)
12755 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
12756 (if to-end
12757 (setq file-alist (append (delq x file-alist) (list x)))
12758 (setq file-alist (cons x (delq x file-alist))))
12759 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
12760 (org-install-agenda-files-menu)
12761 (message "File %s to %s of agenda file list"
12762 (if had "moved" "added") (if to-end "end" "front"))))
12764 (defun org-remove-file (&optional file)
12765 "Remove current file from the list of files in variable `org-agenda-files'.
12766 These are the files which are being checked for agenda entries.
12767 Optional argument FILE means, use this file instead of the current."
12768 (interactive)
12769 (let* ((org-agenda-skip-unavailable-files nil)
12770 (file (or file buffer-file-name))
12771 (true-file (file-truename file))
12772 (afile (abbreviate-file-name file))
12773 (files (delq nil (mapcar
12774 (lambda (x)
12775 (if (equal true-file
12776 (file-truename x))
12777 nil x))
12778 (org-agenda-files t)))))
12779 (if (not (= (length files) (length (org-agenda-files t))))
12780 (progn
12781 (org-store-new-agenda-file-list files)
12782 (org-install-agenda-files-menu)
12783 (message "Removed file: %s" afile))
12784 (message "File was not in list: %s (not removed)" afile))))
12786 (defun org-file-menu-entry (file)
12787 (vector file (list 'find-file file) t))
12789 (defun org-check-agenda-file (file)
12790 "Make sure FILE exists. If not, ask user what to do."
12791 (when (not (file-exists-p file))
12792 (message "non-existent file %s. [R]emove from list or [A]bort?"
12793 (abbreviate-file-name file))
12794 (let ((r (downcase (read-char-exclusive))))
12795 (cond
12796 ((equal r ?r)
12797 (org-remove-file file)
12798 (throw 'nextfile t))
12799 (t (error "Abort"))))))
12801 (defun org-get-agenda-file-buffer (file)
12802 "Get a buffer visiting FILE. If the buffer needs to be created, add
12803 it to the list of buffers which might be released later."
12804 (let ((buf (org-find-base-buffer-visiting file)))
12805 (if buf
12806 buf ; just return it
12807 ;; Make a new buffer and remember it
12808 (setq buf (find-file-noselect file))
12809 (if buf (push buf org-agenda-new-buffers))
12810 buf)))
12812 (defun org-release-buffers (blist)
12813 "Release all buffers in list, asking the user for confirmation when needed.
12814 When a buffer is unmodified, it is just killed. When modified, it is saved
12815 \(if the user agrees) and then killed."
12816 (let (buf file)
12817 (while (setq buf (pop blist))
12818 (setq file (buffer-file-name buf))
12819 (when (and (buffer-modified-p buf)
12820 file
12821 (y-or-n-p (format "Save file %s? " file)))
12822 (with-current-buffer buf (save-buffer)))
12823 (kill-buffer buf))))
12825 (defun org-prepare-agenda-buffers (files)
12826 "Create buffers for all agenda files, protect archived trees and comments."
12827 (interactive)
12828 (let ((pa '(:org-archived t))
12829 (pc '(:org-comment t))
12830 (pall '(:org-archived t :org-comment t))
12831 (inhibit-read-only t)
12832 (rea (concat ":" org-archive-tag ":"))
12833 bmp file re)
12834 (save-excursion
12835 (save-restriction
12836 (while (setq file (pop files))
12837 (if (bufferp file)
12838 (set-buffer file)
12839 (org-check-agenda-file file)
12840 (set-buffer (org-get-agenda-file-buffer file)))
12841 (widen)
12842 (setq bmp (buffer-modified-p))
12843 (org-refresh-category-properties)
12844 (setq org-todo-keywords-for-agenda
12845 (append org-todo-keywords-for-agenda org-todo-keywords-1))
12846 (setq org-done-keywords-for-agenda
12847 (append org-done-keywords-for-agenda org-done-keywords))
12848 (save-excursion
12849 (remove-text-properties (point-min) (point-max) pall)
12850 (when org-agenda-skip-archived-trees
12851 (goto-char (point-min))
12852 (while (re-search-forward rea nil t)
12853 (if (org-on-heading-p t)
12854 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
12855 (goto-char (point-min))
12856 (setq re (concat "^\\*+ +" org-comment-string "\\>"))
12857 (while (re-search-forward re nil t)
12858 (add-text-properties
12859 (match-beginning 0) (org-end-of-subtree t) pc)))
12860 (set-buffer-modified-p bmp))))))
12862 ;;;; Embedded LaTeX
12864 (defvar org-cdlatex-mode-map (make-sparse-keymap)
12865 "Keymap for the minor `org-cdlatex-mode'.")
12867 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
12868 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
12869 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
12870 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
12871 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
12873 (defvar org-cdlatex-texmathp-advice-is-done nil
12874 "Flag remembering if we have applied the advice to texmathp already.")
12876 (define-minor-mode org-cdlatex-mode
12877 "Toggle the minor `org-cdlatex-mode'.
12878 This mode supports entering LaTeX environment and math in LaTeX fragments
12879 in Org-mode.
12880 \\{org-cdlatex-mode-map}"
12881 nil " OCDL" nil
12882 (when org-cdlatex-mode (require 'cdlatex))
12883 (unless org-cdlatex-texmathp-advice-is-done
12884 (setq org-cdlatex-texmathp-advice-is-done t)
12885 (defadvice texmathp (around org-math-always-on activate)
12886 "Always return t in org-mode buffers.
12887 This is because we want to insert math symbols without dollars even outside
12888 the LaTeX math segments. If Orgmode thinks that point is actually inside
12889 en embedded LaTeX fragement, let texmathp do its job.
12890 \\[org-cdlatex-mode-map]"
12891 (interactive)
12892 (let (p)
12893 (cond
12894 ((not (org-mode-p)) ad-do-it)
12895 ((eq this-command 'cdlatex-math-symbol)
12896 (setq ad-return-value t
12897 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
12899 (let ((p (org-inside-LaTeX-fragment-p)))
12900 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
12901 (setq ad-return-value t
12902 texmathp-why '("Org-mode embedded math" . 0))
12903 (if p ad-do-it)))))))))
12905 (defun turn-on-org-cdlatex ()
12906 "Unconditionally turn on `org-cdlatex-mode'."
12907 (org-cdlatex-mode 1))
12909 (defun org-inside-LaTeX-fragment-p ()
12910 "Test if point is inside a LaTeX fragment.
12911 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
12912 sequence appearing also before point.
12913 Even though the matchers for math are configurable, this function assumes
12914 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
12915 delimiters are skipped when they have been removed by customization.
12916 The return value is nil, or a cons cell with the delimiter and
12917 and the position of this delimiter.
12919 This function does a reasonably good job, but can locally be fooled by
12920 for example currency specifications. For example it will assume being in
12921 inline math after \"$22.34\". The LaTeX fragment formatter will only format
12922 fragments that are properly closed, but during editing, we have to live
12923 with the uncertainty caused by missing closing delimiters. This function
12924 looks only before point, not after."
12925 (catch 'exit
12926 (let ((pos (point))
12927 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
12928 (lim (progn
12929 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
12930 (point)))
12931 dd-on str (start 0) m re)
12932 (goto-char pos)
12933 (when dodollar
12934 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
12935 re (nth 1 (assoc "$" org-latex-regexps)))
12936 (while (string-match re str start)
12937 (cond
12938 ((= (match-end 0) (length str))
12939 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
12940 ((= (match-end 0) (- (length str) 5))
12941 (throw 'exit nil))
12942 (t (setq start (match-end 0))))))
12943 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
12944 (goto-char pos)
12945 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
12946 (and (match-beginning 2) (throw 'exit nil))
12947 ;; count $$
12948 (while (re-search-backward "\\$\\$" lim t)
12949 (setq dd-on (not dd-on)))
12950 (goto-char pos)
12951 (if dd-on (cons "$$" m))))))
12954 (defun org-try-cdlatex-tab ()
12955 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
12956 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
12957 - inside a LaTeX fragment, or
12958 - after the first word in a line, where an abbreviation expansion could
12959 insert a LaTeX environment."
12960 (when org-cdlatex-mode
12961 (cond
12962 ((save-excursion
12963 (skip-chars-backward "a-zA-Z0-9*")
12964 (skip-chars-backward " \t")
12965 (bolp))
12966 (cdlatex-tab) t)
12967 ((org-inside-LaTeX-fragment-p)
12968 (cdlatex-tab) t)
12969 (t nil))))
12971 (defun org-cdlatex-underscore-caret (&optional arg)
12972 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
12973 Revert to the normal definition outside of these fragments."
12974 (interactive "P")
12975 (if (org-inside-LaTeX-fragment-p)
12976 (call-interactively 'cdlatex-sub-superscript)
12977 (let (org-cdlatex-mode)
12978 (call-interactively (key-binding (vector last-input-event))))))
12980 (defun org-cdlatex-math-modify (&optional arg)
12981 "Execute `cdlatex-math-modify' in LaTeX fragments.
12982 Revert to the normal definition outside of these fragments."
12983 (interactive "P")
12984 (if (org-inside-LaTeX-fragment-p)
12985 (call-interactively 'cdlatex-math-modify)
12986 (let (org-cdlatex-mode)
12987 (call-interactively (key-binding (vector last-input-event))))))
12989 (defvar org-latex-fragment-image-overlays nil
12990 "List of overlays carrying the images of latex fragments.")
12991 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
12993 (defun org-remove-latex-fragment-image-overlays ()
12994 "Remove all overlays with LaTeX fragment images in current buffer."
12995 (mapc 'org-delete-overlay org-latex-fragment-image-overlays)
12996 (setq org-latex-fragment-image-overlays nil))
12998 (defun org-preview-latex-fragment (&optional subtree)
12999 "Preview the LaTeX fragment at point, or all locally or globally.
13000 If the cursor is in a LaTeX fragment, create the image and overlay
13001 it over the source code. If there is no fragment at point, display
13002 all fragments in the current text, from one headline to the next. With
13003 prefix SUBTREE, display all fragments in the current subtree. With a
13004 double prefix `C-u C-u', or when the cursor is before the first headline,
13005 display all fragments in the buffer.
13006 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
13007 (interactive "P")
13008 (org-remove-latex-fragment-image-overlays)
13009 (save-excursion
13010 (save-restriction
13011 (let (beg end at msg)
13012 (cond
13013 ((or (equal subtree '(16))
13014 (not (save-excursion
13015 (re-search-backward (concat "^" outline-regexp) nil t))))
13016 (setq beg (point-min) end (point-max)
13017 msg "Creating images for buffer...%s"))
13018 ((equal subtree '(4))
13019 (org-back-to-heading)
13020 (setq beg (point) end (org-end-of-subtree t)
13021 msg "Creating images for subtree...%s"))
13023 (if (setq at (org-inside-LaTeX-fragment-p))
13024 (goto-char (max (point-min) (- (cdr at) 2)))
13025 (org-back-to-heading))
13026 (setq beg (point) end (progn (outline-next-heading) (point))
13027 msg (if at "Creating image...%s"
13028 "Creating images for entry...%s"))))
13029 (message msg "")
13030 (narrow-to-region beg end)
13031 (goto-char beg)
13032 (org-format-latex
13033 (concat "ltxpng/" (file-name-sans-extension
13034 (file-name-nondirectory
13035 buffer-file-name)))
13036 default-directory 'overlays msg at 'forbuffer)
13037 (message msg "done. Use `C-c C-c' to remove images.")))))
13039 (defvar org-latex-regexps
13040 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
13041 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
13042 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
13043 ("$" "\\([^$]\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([ .,?;:'\")\000]\\|$\\)" 2 nil)
13044 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
13045 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 t)
13046 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 t))
13047 "Regular expressions for matching embedded LaTeX.")
13049 (defun org-format-latex (prefix &optional dir overlays msg at forbuffer)
13050 "Replace LaTeX fragments with links to an image, and produce images."
13051 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
13052 (let* ((prefixnodir (file-name-nondirectory prefix))
13053 (absprefix (expand-file-name prefix dir))
13054 (todir (file-name-directory absprefix))
13055 (opt org-format-latex-options)
13056 (matchers (plist-get opt :matchers))
13057 (re-list org-latex-regexps)
13058 (cnt 0) txt link beg end re e checkdir
13059 m n block linkfile movefile ov)
13060 ;; Check if there are old images files with this prefix, and remove them
13061 (when (file-directory-p todir)
13062 (mapc 'delete-file
13063 (directory-files
13064 todir 'full
13065 (concat (regexp-quote prefixnodir) "_[0-9]+\\.png$"))))
13066 ;; Check the different regular expressions
13067 (while (setq e (pop re-list))
13068 (setq m (car e) re (nth 1 e) n (nth 2 e)
13069 block (if (nth 3 e) "\n\n" ""))
13070 (when (member m matchers)
13071 (goto-char (point-min))
13072 (while (re-search-forward re nil t)
13073 (when (or (not at) (equal (cdr at) (match-beginning n)))
13074 (setq txt (match-string n)
13075 beg (match-beginning n) end (match-end n)
13076 cnt (1+ cnt)
13077 linkfile (format "%s_%04d.png" prefix cnt)
13078 movefile (format "%s_%04d.png" absprefix cnt)
13079 link (concat block "[[file:" linkfile "]]" block))
13080 (if msg (message msg cnt))
13081 (goto-char beg)
13082 (unless checkdir ; make sure the directory exists
13083 (setq checkdir t)
13084 (or (file-directory-p todir) (make-directory todir)))
13085 (org-create-formula-image
13086 txt movefile opt forbuffer)
13087 (if overlays
13088 (progn
13089 (setq ov (org-make-overlay beg end))
13090 (if (featurep 'xemacs)
13091 (progn
13092 (org-overlay-put ov 'invisible t)
13093 (org-overlay-put
13094 ov 'end-glyph
13095 (make-glyph (vector 'png :file movefile))))
13096 (org-overlay-put
13097 ov 'display
13098 (list 'image :type 'png :file movefile :ascent 'center)))
13099 (push ov org-latex-fragment-image-overlays)
13100 (goto-char end))
13101 (delete-region beg end)
13102 (insert link))))))))
13104 ;; This function borrows from Ganesh Swami's latex2png.el
13105 (defun org-create-formula-image (string tofile options buffer)
13106 (let* ((tmpdir (if (featurep 'xemacs)
13107 (temp-directory)
13108 temporary-file-directory))
13109 (texfilebase (make-temp-name
13110 (expand-file-name "orgtex" tmpdir)))
13111 (texfile (concat texfilebase ".tex"))
13112 (dvifile (concat texfilebase ".dvi"))
13113 (pngfile (concat texfilebase ".png"))
13114 (fnh (face-attribute 'default :height nil))
13115 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
13116 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
13117 (fg (or (plist-get options (if buffer :foreground :html-foreground))
13118 "Black"))
13119 (bg (or (plist-get options (if buffer :background :html-background))
13120 "Transparent")))
13121 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
13122 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
13123 (with-temp-file texfile
13124 (insert org-format-latex-header
13125 "\n\\begin{document}\n" string "\n\\end{document}\n"))
13126 (let ((dir default-directory))
13127 (condition-case nil
13128 (progn
13129 (cd tmpdir)
13130 (call-process "latex" nil nil nil texfile))
13131 (error nil))
13132 (cd dir))
13133 (if (not (file-exists-p dvifile))
13134 (progn (message "Failed to create dvi file from %s" texfile) nil)
13135 (call-process "dvipng" nil nil nil
13136 "-E" "-fg" fg "-bg" bg
13137 "-D" dpi
13138 ;;"-x" scale "-y" scale
13139 "-T" "tight"
13140 "-o" pngfile
13141 dvifile)
13142 (if (not (file-exists-p pngfile))
13143 (progn (message "Failed to create png file from %s" texfile) nil)
13144 ;; Use the requested file name and clean up
13145 (copy-file pngfile tofile 'replace)
13146 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
13147 (delete-file (concat texfilebase e)))
13148 pngfile))))
13150 (defun org-dvipng-color (attr)
13151 "Return an rgb color specification for dvipng."
13152 (apply 'format "rgb %s %s %s"
13153 (mapcar 'org-normalize-color
13154 (color-values (face-attribute 'default attr nil)))))
13156 (defun org-normalize-color (value)
13157 "Return string to be used as color value for an RGB component."
13158 (format "%g" (/ value 65535.0)))
13161 ;;;; Key bindings
13163 ;; Make `C-c C-x' a prefix key
13164 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
13166 ;; TAB key with modifiers
13167 (org-defkey org-mode-map "\C-i" 'org-cycle)
13168 (org-defkey org-mode-map [(tab)] 'org-cycle)
13169 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
13170 (org-defkey org-mode-map [(meta tab)] 'org-complete)
13171 (org-defkey org-mode-map "\M-\t" 'org-complete)
13172 (org-defkey org-mode-map "\M-\C-i" 'org-complete)
13173 ;; The following line is necessary under Suse GNU/Linux
13174 (unless (featurep 'xemacs)
13175 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
13176 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
13177 (define-key org-mode-map [backtab] 'org-shifttab)
13179 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
13180 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
13181 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
13183 ;; Cursor keys with modifiers
13184 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
13185 (org-defkey org-mode-map [(meta right)] 'org-metaright)
13186 (org-defkey org-mode-map [(meta up)] 'org-metaup)
13187 (org-defkey org-mode-map [(meta down)] 'org-metadown)
13189 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
13190 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
13191 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
13192 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
13194 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
13195 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
13196 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
13197 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
13199 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
13200 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
13202 ;;; Extra keys for tty access.
13203 ;; We only set them when really needed because otherwise the
13204 ;; menus don't show the simple keys
13206 (when (or (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
13207 (not window-system))
13208 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
13209 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
13210 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
13211 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
13212 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
13213 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
13214 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
13215 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
13216 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
13217 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
13218 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
13219 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
13220 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
13221 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
13222 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
13223 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
13224 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
13225 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
13226 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
13227 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
13228 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
13229 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft))
13231 ;; All the other keys
13233 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
13234 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
13235 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree)
13236 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
13237 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
13238 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-toggle-archive-tag)
13239 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
13240 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
13241 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
13242 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
13243 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
13244 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
13245 (org-defkey org-mode-map "\C-c\C-v" 'org-show-todo-tree)
13246 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
13247 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
13248 (org-defkey org-mode-map "\C-c\\" 'org-tags-sparse-tree) ; Minor-mode res.
13249 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
13250 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
13251 (org-defkey org-mode-map [(control return)] 'org-insert-heading-after-current)
13252 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
13253 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
13254 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
13255 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
13256 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
13257 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
13258 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
13259 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
13260 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
13261 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
13262 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
13263 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
13264 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
13265 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
13266 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
13267 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
13268 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
13269 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
13270 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
13271 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
13272 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
13273 (org-defkey org-mode-map "\C-c^" 'org-sort)
13274 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
13275 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
13276 (org-defkey org-mode-map "\C-c#" 'org-update-checkbox-count)
13277 (org-defkey org-mode-map "\C-m" 'org-return)
13278 (org-defkey org-mode-map "\C-j" 'org-return-indent)
13279 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
13280 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
13281 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
13282 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
13283 (org-defkey org-mode-map "\C-c'" 'org-table-edit-formulas)
13284 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
13285 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
13286 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
13287 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
13288 (org-defkey org-mode-map "\C-c\C-q" 'org-table-wrap-region)
13289 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
13290 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
13291 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
13292 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
13293 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
13295 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-cut-special)
13296 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
13297 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
13298 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
13300 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
13301 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
13302 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
13303 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
13304 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
13305 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
13306 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
13307 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
13308 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
13309 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
13310 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
13311 (org-defkey org-mode-map "\C-c\C-xr" 'org-insert-columns-dblock)
13313 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
13315 (when (featurep 'xemacs)
13316 (org-defkey org-mode-map 'button3 'popup-mode-menu))
13318 (defvar org-table-auto-blank-field) ; defined in org-table.el
13319 (defun org-self-insert-command (N)
13320 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
13321 If the cursor is in a table looking at whitespace, the whitespace is
13322 overwritten, and the table is not marked as requiring realignment."
13323 (interactive "p")
13324 (if (and (org-table-p)
13325 (progn
13326 ;; check if we blank the field, and if that triggers align
13327 (and (featurep 'org-table) org-table-auto-blank-field
13328 (member last-command
13329 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
13330 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
13331 ;; got extra space, this field does not determine column width
13332 (let (org-table-may-need-update) (org-table-blank-field))
13333 ;; no extra space, this field may determine column width
13334 (org-table-blank-field)))
13336 (eq N 1)
13337 (looking-at "[^|\n]* |"))
13338 (let (org-table-may-need-update)
13339 (goto-char (1- (match-end 0)))
13340 (delete-backward-char 1)
13341 (goto-char (match-beginning 0))
13342 (self-insert-command N))
13343 (setq org-table-may-need-update t)
13344 (self-insert-command N)
13345 (org-fix-tags-on-the-fly)))
13347 (defun org-fix-tags-on-the-fly ()
13348 (when (and (equal (char-after (point-at-bol)) ?*)
13349 (org-on-heading-p))
13350 (org-align-tags-here org-tags-column)))
13352 (defun org-delete-backward-char (N)
13353 "Like `delete-backward-char', insert whitespace at field end in tables.
13354 When deleting backwards, in tables this function will insert whitespace in
13355 front of the next \"|\" separator, to keep the table aligned. The table will
13356 still be marked for re-alignment if the field did fill the entire column,
13357 because, in this case the deletion might narrow the column."
13358 (interactive "p")
13359 (if (and (org-table-p)
13360 (eq N 1)
13361 (string-match "|" (buffer-substring (point-at-bol) (point)))
13362 (looking-at ".*?|"))
13363 (let ((pos (point))
13364 (noalign (looking-at "[^|\n\r]* |"))
13365 (c org-table-may-need-update))
13366 (backward-delete-char N)
13367 (skip-chars-forward "^|")
13368 (insert " ")
13369 (goto-char (1- pos))
13370 ;; noalign: if there were two spaces at the end, this field
13371 ;; does not determine the width of the column.
13372 (if noalign (setq org-table-may-need-update c)))
13373 (backward-delete-char N)
13374 (org-fix-tags-on-the-fly)))
13376 (defun org-delete-char (N)
13377 "Like `delete-char', but insert whitespace at field end in tables.
13378 When deleting characters, in tables this function will insert whitespace in
13379 front of the next \"|\" separator, to keep the table aligned. The table will
13380 still be marked for re-alignment if the field did fill the entire column,
13381 because, in this case the deletion might narrow the column."
13382 (interactive "p")
13383 (if (and (org-table-p)
13384 (not (bolp))
13385 (not (= (char-after) ?|))
13386 (eq N 1))
13387 (if (looking-at ".*?|")
13388 (let ((pos (point))
13389 (noalign (looking-at "[^|\n\r]* |"))
13390 (c org-table-may-need-update))
13391 (replace-match (concat
13392 (substring (match-string 0) 1 -1)
13393 " |"))
13394 (goto-char pos)
13395 ;; noalign: if there were two spaces at the end, this field
13396 ;; does not determine the width of the column.
13397 (if noalign (setq org-table-may-need-update c)))
13398 (delete-char N))
13399 (delete-char N)
13400 (org-fix-tags-on-the-fly)))
13402 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
13403 (put 'org-self-insert-command 'delete-selection t)
13404 (put 'orgtbl-self-insert-command 'delete-selection t)
13405 (put 'org-delete-char 'delete-selection 'supersede)
13406 (put 'org-delete-backward-char 'delete-selection 'supersede)
13408 ;; Make `flyspell-mode' delay after some commands
13409 (put 'org-self-insert-command 'flyspell-delayed t)
13410 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
13411 (put 'org-delete-char 'flyspell-delayed t)
13412 (put 'org-delete-backward-char 'flyspell-delayed t)
13414 ;; Make pabbrev-mode expand after org-mode commands
13415 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
13416 (put 'orgybl-self-insert-command 'pabbrev-expand-after-command t)
13418 ;; How to do this: Measure non-white length of current string
13419 ;; If equal to column width, we should realign.
13421 (defun org-remap (map &rest commands)
13422 "In MAP, remap the functions given in COMMANDS.
13423 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
13424 (let (new old)
13425 (while commands
13426 (setq old (pop commands) new (pop commands))
13427 (if (fboundp 'command-remapping)
13428 (org-defkey map (vector 'remap old) new)
13429 (substitute-key-definition old new map global-map)))))
13431 (when (eq org-enable-table-editor 'optimized)
13432 ;; If the user wants maximum table support, we need to hijack
13433 ;; some standard editing functions
13434 (org-remap org-mode-map
13435 'self-insert-command 'org-self-insert-command
13436 'delete-char 'org-delete-char
13437 'delete-backward-char 'org-delete-backward-char)
13438 (org-defkey org-mode-map "|" 'org-force-self-insert))
13440 (defun org-shiftcursor-error ()
13441 "Throw an error because Shift-Cursor command was applied in wrong context."
13442 (error "This command is active in special context like tables, headlines or timestamps"))
13444 (defun org-shifttab (&optional arg)
13445 "Global visibility cycling or move to previous table field.
13446 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
13447 on context.
13448 See the individual commands for more information."
13449 (interactive "P")
13450 (cond
13451 ((org-at-table-p) (call-interactively 'org-table-previous-field))
13452 (arg (message "Content view to level: ")
13453 (org-content (prefix-numeric-value arg))
13454 (setq org-cycle-global-status 'overview))
13455 (t (call-interactively 'org-global-cycle))))
13457 (defun org-shiftmetaleft ()
13458 "Promote subtree or delete table column.
13459 Calls `org-promote-subtree', `org-outdent-item',
13460 or `org-table-delete-column', depending on context.
13461 See the individual commands for more information."
13462 (interactive)
13463 (cond
13464 ((org-at-table-p) (call-interactively 'org-table-delete-column))
13465 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
13466 ((org-at-item-p) (call-interactively 'org-outdent-item))
13467 (t (org-shiftcursor-error))))
13469 (defun org-shiftmetaright ()
13470 "Demote subtree or insert table column.
13471 Calls `org-demote-subtree', `org-indent-item',
13472 or `org-table-insert-column', depending on context.
13473 See the individual commands for more information."
13474 (interactive)
13475 (cond
13476 ((org-at-table-p) (call-interactively 'org-table-insert-column))
13477 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
13478 ((org-at-item-p) (call-interactively 'org-indent-item))
13479 (t (org-shiftcursor-error))))
13481 (defun org-shiftmetaup (&optional arg)
13482 "Move subtree up or kill table row.
13483 Calls `org-move-subtree-up' or `org-table-kill-row' or
13484 `org-move-item-up' depending on context. See the individual commands
13485 for more information."
13486 (interactive "P")
13487 (cond
13488 ((org-at-table-p) (call-interactively 'org-table-kill-row))
13489 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
13490 ((org-at-item-p) (call-interactively 'org-move-item-up))
13491 (t (org-shiftcursor-error))))
13492 (defun org-shiftmetadown (&optional arg)
13493 "Move subtree down or insert table row.
13494 Calls `org-move-subtree-down' or `org-table-insert-row' or
13495 `org-move-item-down', depending on context. See the individual
13496 commands for more information."
13497 (interactive "P")
13498 (cond
13499 ((org-at-table-p) (call-interactively 'org-table-insert-row))
13500 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
13501 ((org-at-item-p) (call-interactively 'org-move-item-down))
13502 (t (org-shiftcursor-error))))
13504 (defun org-metaleft (&optional arg)
13505 "Promote heading or move table column to left.
13506 Calls `org-do-promote' or `org-table-move-column', depending on context.
13507 With no specific context, calls the Emacs default `backward-word'.
13508 See the individual commands for more information."
13509 (interactive "P")
13510 (cond
13511 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
13512 ((or (org-on-heading-p) (org-region-active-p))
13513 (call-interactively 'org-do-promote))
13514 ((org-at-item-p) (call-interactively 'org-outdent-item))
13515 (t (call-interactively 'backward-word))))
13517 (defun org-metaright (&optional arg)
13518 "Demote subtree or move table column to right.
13519 Calls `org-do-demote' or `org-table-move-column', depending on context.
13520 With no specific context, calls the Emacs default `forward-word'.
13521 See the individual commands for more information."
13522 (interactive "P")
13523 (cond
13524 ((org-at-table-p) (call-interactively 'org-table-move-column))
13525 ((or (org-on-heading-p) (org-region-active-p))
13526 (call-interactively 'org-do-demote))
13527 ((org-at-item-p) (call-interactively 'org-indent-item))
13528 (t (call-interactively 'forward-word))))
13530 (defun org-metaup (&optional arg)
13531 "Move subtree up or move table row up.
13532 Calls `org-move-subtree-up' or `org-table-move-row' or
13533 `org-move-item-up', depending on context. See the individual commands
13534 for more information."
13535 (interactive "P")
13536 (cond
13537 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
13538 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
13539 ((org-at-item-p) (call-interactively 'org-move-item-up))
13540 (t (transpose-lines 1) (beginning-of-line -1))))
13542 (defun org-metadown (&optional arg)
13543 "Move subtree down or move table row down.
13544 Calls `org-move-subtree-down' or `org-table-move-row' or
13545 `org-move-item-down', depending on context. See the individual
13546 commands for more information."
13547 (interactive "P")
13548 (cond
13549 ((org-at-table-p) (call-interactively 'org-table-move-row))
13550 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
13551 ((org-at-item-p) (call-interactively 'org-move-item-down))
13552 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
13554 (defun org-shiftup (&optional arg)
13555 "Increase item in timestamp or increase priority of current headline.
13556 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
13557 depending on context. See the individual commands for more information."
13558 (interactive "P")
13559 (cond
13560 ((org-at-timestamp-p t)
13561 (call-interactively (if org-edit-timestamp-down-means-later
13562 'org-timestamp-down 'org-timestamp-up)))
13563 ((org-on-heading-p) (call-interactively 'org-priority-up))
13564 ((org-at-item-p) (call-interactively 'org-previous-item))
13565 ((org-clocktable-try-shift 'up arg))
13566 (t (call-interactively 'org-beginning-of-item) (beginning-of-line 1))))
13568 (defun org-shiftdown (&optional arg)
13569 "Decrease item in timestamp or decrease priority of current headline.
13570 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
13571 depending on context. See the individual commands for more information."
13572 (interactive "P")
13573 (cond
13574 ((org-at-timestamp-p t)
13575 (call-interactively (if org-edit-timestamp-down-means-later
13576 'org-timestamp-up 'org-timestamp-down)))
13577 ((org-on-heading-p) (call-interactively 'org-priority-down))
13578 ((org-clocktable-try-shift 'down arg))
13579 (t (call-interactively 'org-next-item))))
13581 (defun org-shiftright (&optional arg)
13582 "Next TODO keyword or timestamp one day later, depending on context."
13583 (interactive "P")
13584 (cond
13585 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
13586 ((org-on-heading-p) (org-call-with-arg 'org-todo 'right))
13587 ((org-at-item-p) (org-call-with-arg 'org-cycle-list-bullet nil))
13588 ((org-at-property-p) (call-interactively 'org-property-next-allowed-value))
13589 ((org-clocktable-try-shift 'right arg))
13590 (t (org-shiftcursor-error))))
13592 (defun org-shiftleft (&optional arg)
13593 "Previous TODO keyword or timestamp one day earlier, depending on context."
13594 (interactive "P")
13595 (cond
13596 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
13597 ((org-on-heading-p) (org-call-with-arg 'org-todo 'left))
13598 ((org-at-item-p) (org-call-with-arg 'org-cycle-list-bullet 'previous))
13599 ((org-at-property-p)
13600 (call-interactively 'org-property-previous-allowed-value))
13601 ((org-clocktable-try-shift 'left arg))
13602 (t (org-shiftcursor-error))))
13604 (defun org-shiftcontrolright ()
13605 "Switch to next TODO set."
13606 (interactive)
13607 (cond
13608 ((org-on-heading-p) (org-call-with-arg 'org-todo 'nextset))
13609 (t (org-shiftcursor-error))))
13611 (defun org-shiftcontrolleft ()
13612 "Switch to previous TODO set."
13613 (interactive)
13614 (cond
13615 ((org-on-heading-p) (org-call-with-arg 'org-todo 'previousset))
13616 (t (org-shiftcursor-error))))
13618 (defun org-ctrl-c-ret ()
13619 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
13620 (interactive)
13621 (cond
13622 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
13623 (t (call-interactively 'org-insert-heading))))
13625 (defun org-copy-special ()
13626 "Copy region in table or copy current subtree.
13627 Calls `org-table-copy' or `org-copy-subtree', depending on context.
13628 See the individual commands for more information."
13629 (interactive)
13630 (call-interactively
13631 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
13633 (defun org-cut-special ()
13634 "Cut region in table or cut current subtree.
13635 Calls `org-table-copy' or `org-cut-subtree', depending on context.
13636 See the individual commands for more information."
13637 (interactive)
13638 (call-interactively
13639 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
13641 (defun org-paste-special (arg)
13642 "Paste rectangular region into table, or past subtree relative to level.
13643 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
13644 See the individual commands for more information."
13645 (interactive "P")
13646 (if (org-at-table-p)
13647 (org-table-paste-rectangle)
13648 (org-paste-subtree arg)))
13650 (defun org-ctrl-c-ctrl-c (&optional arg)
13651 "Set tags in headline, or update according to changed information at point.
13653 This command does many different things, depending on context:
13655 - If the cursor is in a headline, prompt for tags and insert them
13656 into the current line, aligned to `org-tags-column'. When called
13657 with prefix arg, realign all tags in the current buffer.
13659 - If the cursor is in one of the special #+KEYWORD lines, this
13660 triggers scanning the buffer for these lines and updating the
13661 information.
13663 - If the cursor is inside a table, realign the table. This command
13664 works even if the automatic table editor has been turned off.
13666 - If the cursor is on a #+TBLFM line, re-apply the formulas to
13667 the entire table.
13669 - If the cursor is a the beginning of a dynamic block, update it.
13671 - If the cursor is inside a table created by the table.el package,
13672 activate that table.
13674 - If the current buffer is a remember buffer, close note and file it.
13675 with a prefix argument, file it without further interaction to the default
13676 location.
13678 - If the cursor is on a <<<target>>>, update radio targets and corresponding
13679 links in this buffer.
13681 - If the cursor is on a numbered item in a plain list, renumber the
13682 ordered list.
13684 - If the cursor is on a checkbox, toggle it."
13685 (interactive "P")
13686 (let ((org-enable-table-editor t))
13687 (cond
13688 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
13689 org-occur-highlights
13690 org-latex-fragment-image-overlays)
13691 (and (boundp 'org-clock-overlays) (org-remove-clock-overlays))
13692 (org-remove-occur-highlights)
13693 (org-remove-latex-fragment-image-overlays)
13694 (message "Temporary highlights/overlays removed from current buffer"))
13695 ((and (local-variable-p 'org-finish-function (current-buffer))
13696 (fboundp org-finish-function))
13697 (funcall org-finish-function))
13698 ((org-at-property-p)
13699 (call-interactively 'org-property-action))
13700 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
13701 ((org-on-heading-p) (call-interactively 'org-set-tags))
13702 ((org-at-table.el-p)
13703 (require 'table)
13704 (beginning-of-line 1)
13705 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
13706 (call-interactively 'table-recognize-table))
13707 ((org-at-table-p)
13708 (org-table-maybe-eval-formula)
13709 (if arg
13710 (call-interactively 'org-table-recalculate)
13711 (org-table-maybe-recalculate-line))
13712 (call-interactively 'org-table-align))
13713 ((org-at-item-checkbox-p)
13714 (call-interactively 'org-toggle-checkbox))
13715 ((org-at-item-p)
13716 (call-interactively 'org-maybe-renumber-ordered-list))
13717 ((save-excursion (beginning-of-line 1) (looking-at "#\\+BEGIN:"))
13718 ;; Dynamic block
13719 (beginning-of-line 1)
13720 (org-update-dblock))
13721 ((save-excursion (beginning-of-line 1) (looking-at "#\\+\\([A-Z]+\\)"))
13722 (cond
13723 ((equal (match-string 1) "TBLFM")
13724 ;; Recalculate the table before this line
13725 (save-excursion
13726 (beginning-of-line 1)
13727 (skip-chars-backward " \r\n\t")
13728 (if (org-at-table-p)
13729 (org-call-with-arg 'org-table-recalculate t))))
13731 (call-interactively 'org-mode-restart))))
13732 (t (error "C-c C-c can do nothing useful at this location.")))))
13734 (defun org-mode-restart ()
13735 "Restart Org-mode, to scan again for special lines.
13736 Also updates the keyword regular expressions."
13737 (interactive)
13738 (let ((org-inhibit-startup t)) (org-mode))
13739 (message "Org-mode restarted to refresh keyword and special line setup"))
13741 (defun org-kill-note-or-show-branches ()
13742 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
13743 (interactive)
13744 (if (not org-finish-function)
13745 (call-interactively 'show-branches)
13746 (let ((org-note-abort t))
13747 (funcall org-finish-function))))
13749 (defun org-return (&optional indent)
13750 "Goto next table row or insert a newline.
13751 Calls `org-table-next-row' or `newline', depending on context.
13752 See the individual commands for more information."
13753 (interactive)
13754 (cond
13755 ((bobp) (if indent (newline-and-indent) (newline)))
13756 ((and (org-at-heading-p)
13757 (looking-at
13758 (org-re "\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$")))
13759 (org-show-entry)
13760 (end-of-line 1)
13761 (newline))
13762 ((org-at-table-p)
13763 (org-table-justify-field-maybe)
13764 (call-interactively 'org-table-next-row))
13765 (t (if indent (newline-and-indent) (newline)))))
13767 (defun org-return-indent ()
13768 "Goto next table row or insert a newline and indent.
13769 Calls `org-table-next-row' or `newline-and-indent', depending on
13770 context. See the individual commands for more information."
13771 (interactive)
13772 (org-return t))
13774 (defun org-ctrl-c-star ()
13775 "Compute table, or change heading status of lines.
13776 Calls `org-table-recalculate' or `org-toggle-region-headlines',
13777 depending on context. This will also turn a plain list item or a normal
13778 line into a subheading."
13779 (interactive)
13780 (cond
13781 ((org-at-table-p)
13782 (call-interactively 'org-table-recalculate))
13783 ((org-region-active-p)
13784 ;; Convert all lines in region to list items
13785 (call-interactively 'org-toggle-region-headings))
13786 ((org-on-heading-p)
13787 (org-toggle-region-headings (point-at-bol)
13788 (min (1+ (point-at-eol)) (point-max))))
13789 ((org-at-item-p)
13790 ;; Convert to heading
13791 (let ((level (save-match-data
13792 (save-excursion
13793 (condition-case nil
13794 (progn
13795 (org-back-to-heading t)
13796 (funcall outline-level))
13797 (error 0))))))
13798 (replace-match
13799 (concat (make-string (org-get-valid-level level 1) ?*) " ") t t)))
13800 (t (org-toggle-region-headings (point-at-bol)
13801 (min (1+ (point-at-eol)) (point-max))))))
13803 (defun org-ctrl-c-minus ()
13804 "Insert separator line in table or modify bullet status of line.
13805 Also turns a plain line or a region of lines into list items.
13806 Calls `org-table-insert-hline', `org-toggle-region-items', or
13807 `org-cycle-list-bullet', depending on context."
13808 (interactive)
13809 (cond
13810 ((org-at-table-p)
13811 (call-interactively 'org-table-insert-hline))
13812 ((org-on-heading-p)
13813 ;; Convert to item
13814 (save-excursion
13815 (beginning-of-line 1)
13816 (if (looking-at "\\*+ ")
13817 (replace-match (concat (make-string (- (match-end 0) (point) 1) ?\ ) "- ")))))
13818 ((org-region-active-p)
13819 ;; Convert all lines in region to list items
13820 (call-interactively 'org-toggle-region-items))
13821 ((org-in-item-p)
13822 (call-interactively 'org-cycle-list-bullet))
13823 (t (org-toggle-region-items (point-at-bol)
13824 (min (1+ (point-at-eol)) (point-max))))))
13826 (defun org-toggle-region-items (beg end)
13827 "Convert all lines in region to list items.
13828 If the first line is already an item, convert all list items in the region
13829 to normal lines."
13830 (interactive "r")
13831 (let (l2 l)
13832 (save-excursion
13833 (goto-char end)
13834 (setq l2 (org-current-line))
13835 (goto-char beg)
13836 (beginning-of-line 1)
13837 (setq l (1- (org-current-line)))
13838 (if (org-at-item-p)
13839 ;; We already have items, de-itemize
13840 (while (< (setq l (1+ l)) l2)
13841 (when (org-at-item-p)
13842 (goto-char (match-beginning 2))
13843 (delete-region (match-beginning 2) (match-end 2))
13844 (and (looking-at "[ \t]+") (replace-match "")))
13845 (beginning-of-line 2))
13846 (while (< (setq l (1+ l)) l2)
13847 (unless (org-at-item-p)
13848 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
13849 (replace-match "\\1- \\2")))
13850 (beginning-of-line 2))))))
13852 (defun org-toggle-region-headings (beg end)
13853 "Convert all lines in region to list items.
13854 If the first line is already an item, convert all list items in the region
13855 to normal lines."
13856 (interactive "r")
13857 (let (l2 l)
13858 (save-excursion
13859 (goto-char end)
13860 (setq l2 (org-current-line))
13861 (goto-char beg)
13862 (beginning-of-line 1)
13863 (setq l (1- (org-current-line)))
13864 (if (org-on-heading-p)
13865 ;; We already have headlines, de-star them
13866 (while (< (setq l (1+ l)) l2)
13867 (when (org-on-heading-p t)
13868 (and (looking-at outline-regexp) (replace-match "")))
13869 (beginning-of-line 2))
13870 (let* ((stars (save-excursion
13871 (re-search-backward org-complex-heading-regexp nil t)
13872 (or (match-string 1) "*")))
13873 (add-stars (if org-odd-levels-only "**" "*"))
13874 (rpl (concat stars add-stars " \\2")))
13875 (while (< (setq l (1+ l)) l2)
13876 (unless (org-on-heading-p)
13877 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
13878 (replace-match rpl)))
13879 (beginning-of-line 2)))))))
13881 (defun org-meta-return (&optional arg)
13882 "Insert a new heading or wrap a region in a table.
13883 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
13884 See the individual commands for more information."
13885 (interactive "P")
13886 (cond
13887 ((org-at-table-p)
13888 (call-interactively 'org-table-wrap-region))
13889 (t (call-interactively 'org-insert-heading))))
13891 ;;; Menu entries
13893 ;; Define the Org-mode menus
13894 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
13895 '("Tbl"
13896 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
13897 ["Next Field" org-cycle (org-at-table-p)]
13898 ["Previous Field" org-shifttab (org-at-table-p)]
13899 ["Next Row" org-return (org-at-table-p)]
13900 "--"
13901 ["Blank Field" org-table-blank-field (org-at-table-p)]
13902 ["Edit Field" org-table-edit-field (org-at-table-p)]
13903 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
13904 "--"
13905 ("Column"
13906 ["Move Column Left" org-metaleft (org-at-table-p)]
13907 ["Move Column Right" org-metaright (org-at-table-p)]
13908 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
13909 ["Insert Column" org-shiftmetaright (org-at-table-p)])
13910 ("Row"
13911 ["Move Row Up" org-metaup (org-at-table-p)]
13912 ["Move Row Down" org-metadown (org-at-table-p)]
13913 ["Delete Row" org-shiftmetaup (org-at-table-p)]
13914 ["Insert Row" org-shiftmetadown (org-at-table-p)]
13915 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
13916 "--"
13917 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
13918 ("Rectangle"
13919 ["Copy Rectangle" org-copy-special (org-at-table-p)]
13920 ["Cut Rectangle" org-cut-special (org-at-table-p)]
13921 ["Paste Rectangle" org-paste-special (org-at-table-p)]
13922 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
13923 "--"
13924 ("Calculate"
13925 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
13926 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
13927 ["Edit Formulas" org-table-edit-formulas (org-at-table-p)]
13928 "--"
13929 ["Recalculate line" org-table-recalculate (org-at-table-p)]
13930 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
13931 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
13932 "--"
13933 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
13934 "--"
13935 ["Sum Column/Rectangle" org-table-sum
13936 (or (org-at-table-p) (org-region-active-p))]
13937 ["Which Column?" org-table-current-column (org-at-table-p)])
13938 ["Debug Formulas"
13939 org-table-toggle-formula-debugger
13940 :style toggle :selected org-table-formula-debug]
13941 ["Show Col/Row Numbers"
13942 org-table-toggle-coordinate-overlays
13943 :style toggle :selected org-table-overlay-coordinates]
13944 "--"
13945 ["Create" org-table-create (and (not (org-at-table-p))
13946 org-enable-table-editor)]
13947 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
13948 ["Import from File" org-table-import (not (org-at-table-p))]
13949 ["Export to File" org-table-export (org-at-table-p)]
13950 "--"
13951 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
13953 (easy-menu-define org-org-menu org-mode-map "Org menu"
13954 '("Org"
13955 ("Show/Hide"
13956 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))
13957 :help "Cycle subtree visibility: folded->children->all->folded"]
13958 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))
13959 :help "Cycle global visibility: overview->content->all"]
13960 ["Sparse Tree..." org-sparse-tree
13961 :help "Create sparse trees using different search criteria"]
13962 ["Reveal Context" org-reveal :active t
13963 :help "Show hidden context around point, including the outline hierarchy"]
13964 ["Show All" show-all :active t
13965 :help "Show all text in the buffer, including drawers"]
13966 "--"
13967 ["Subtree to indirect buffer" org-tree-to-indirect-buffer :active t
13968 :help "Open the subtree at point in a separate window, using an indirect buffer"])
13969 "--"
13970 ["New Heading" org-insert-heading t]
13971 ("Navigate Headings"
13972 ["Up" outline-up-heading t]
13973 ["Next" outline-next-visible-heading t]
13974 ["Previous" outline-previous-visible-heading t]
13975 ["Next Same Level" outline-forward-same-level t]
13976 ["Previous Same Level" outline-backward-same-level t]
13977 "--"
13978 ["Jump" org-goto t])
13979 ("Edit Structure"
13980 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
13981 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
13982 "--"
13983 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
13984 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
13985 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
13986 "--"
13987 ["Promote Heading" org-metaleft (not (org-at-table-p))]
13988 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
13989 ["Demote Heading" org-metaright (not (org-at-table-p))]
13990 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
13991 "--"
13992 ["Sort Region/Children" org-sort (not (org-at-table-p))]
13993 "--"
13994 ["Convert to odd levels" org-convert-to-odd-levels t]
13995 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
13996 ("Editing"
13997 ["Emphasis..." org-emphasize t])
13998 ("Archive"
13999 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
14000 ; ["Check and Tag Children" (org-toggle-archive-tag (4))
14001 ; :active t :keys "C-u C-c C-x C-a"]
14002 ["Sparse trees open ARCHIVE trees"
14003 (setq org-sparse-tree-open-archived-trees
14004 (not org-sparse-tree-open-archived-trees))
14005 :style toggle :selected org-sparse-tree-open-archived-trees]
14006 ["Cycling opens ARCHIVE trees"
14007 (setq org-cycle-open-archived-trees (not org-cycle-open-archived-trees))
14008 :style toggle :selected org-cycle-open-archived-trees]
14009 ["Agenda includes ARCHIVE trees"
14010 (setq org-agenda-skip-archived-trees (not org-agenda-skip-archived-trees))
14011 :style toggle :selected (not org-agenda-skip-archived-trees)]
14012 "--"
14013 ["Move Subtree to Archive" org-advertized-archive-subtree t]
14014 ; ["Check and Move Children" (org-archive-subtree '(4))
14015 ; :active t :keys "C-u C-c C-x C-s"]
14017 "--"
14018 ("TODO Lists"
14019 ["TODO/DONE/-" org-todo t]
14020 ("Select keyword"
14021 ["Next keyword" org-shiftright (org-on-heading-p)]
14022 ["Previous keyword" org-shiftleft (org-on-heading-p)]
14023 ["Complete Keyword" org-complete (assq :todo-keyword (org-context))]
14024 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))]
14025 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))])
14026 ["Show TODO Tree" org-show-todo-tree t]
14027 ["Global TODO list" org-todo-list t]
14028 "--"
14029 ["Set Priority" org-priority t]
14030 ["Priority Up" org-shiftup t]
14031 ["Priority Down" org-shiftdown t])
14032 ("TAGS and Properties"
14033 ["Set Tags" 'org-ctrl-c-ctrl-c (org-at-heading-p)]
14034 ["Change tag in region" 'org-change-tag-in-region (org-region-active-p)]
14035 "--"
14036 ["Set property" 'org-set-property t]
14037 ["Column view of properties" org-columns t]
14038 ["Insert Column View DBlock" org-insert-columns-dblock t])
14039 ("Dates and Scheduling"
14040 ["Timestamp" org-time-stamp t]
14041 ["Timestamp (inactive)" org-time-stamp-inactive t]
14042 ("Change Date"
14043 ["1 Day Later" org-shiftright t]
14044 ["1 Day Earlier" org-shiftleft t]
14045 ["1 ... Later" org-shiftup t]
14046 ["1 ... Earlier" org-shiftdown t])
14047 ["Compute Time Range" org-evaluate-time-range t]
14048 ["Schedule Item" org-schedule t]
14049 ["Deadline" org-deadline t]
14050 "--"
14051 ["Custom time format" org-toggle-time-stamp-overlays
14052 :style radio :selected org-display-custom-times]
14053 "--"
14054 ["Goto Calendar" org-goto-calendar t]
14055 ["Date from Calendar" org-date-from-calendar t])
14056 ("Logging work"
14057 ["Clock in" org-clock-in t]
14058 ["Clock out" org-clock-out t]
14059 ["Clock cancel" org-clock-cancel t]
14060 ["Goto running clock" org-clock-goto t]
14061 ["Display times" org-clock-display t]
14062 ["Create clock table" org-clock-report t]
14063 "--"
14064 ["Record DONE time"
14065 (progn (setq org-log-done (not org-log-done))
14066 (message "Switching to %s will %s record a timestamp"
14067 (car org-done-keywords)
14068 (if org-log-done "automatically" "not")))
14069 :style toggle :selected org-log-done])
14070 "--"
14071 ["Agenda Command..." org-agenda t]
14072 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
14073 ("File List for Agenda")
14074 ("Special views current file"
14075 ["TODO Tree" org-show-todo-tree t]
14076 ["Check Deadlines" org-check-deadlines t]
14077 ["Timeline" org-timeline t]
14078 ["Tags Tree" org-tags-sparse-tree t])
14079 "--"
14080 ("Hyperlinks"
14081 ["Store Link (Global)" org-store-link t]
14082 ["Insert Link" org-insert-link t]
14083 ["Follow Link" org-open-at-point t]
14084 "--"
14085 ["Next link" org-next-link :help "Move forward to next link in the buffer"]
14086 ["Previous link" org-previous-link t]
14087 "--"
14088 ["Descriptive Links"
14089 (progn (org-add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
14090 :style radio :help "Hide link part of links, only show the description"
14091 :selected (member '(org-link) buffer-invisibility-spec)]
14092 ["Literal Links"
14093 (progn
14094 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
14095 :style radio :help "Show full links without hiding anything"
14096 :selected (not (member '(org-link) buffer-invisibility-spec))])
14097 "--"
14098 ["Export/Publish..." org-export t]
14099 ("LaTeX"
14100 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
14101 :selected org-cdlatex-mode]
14102 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
14103 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
14104 ["Modify math symbol" org-cdlatex-math-modify
14105 (org-inside-LaTeX-fragment-p)]
14106 ["Export LaTeX fragments as images"
14107 (if (featurep 'org-exp)
14108 (setq org-export-with-LaTeX-fragments
14109 (not org-export-with-LaTeX-fragments))
14110 (require 'org-exp))
14111 :style toggle :selected (and (boundp 'org-export-with-LaTeX-fragments)
14112 org-export-with-LaTeX-fragments)])
14113 "--"
14114 ("Documentation"
14115 ["Show Version" org-version t]
14116 ["Info Documentation" org-info t])
14117 ("Customize"
14118 ["Browse Org Group" org-customize t]
14119 "--"
14120 ["Expand This Menu" org-create-customize-menu
14121 (fboundp 'customize-menu-create)])
14122 "--"
14123 ["Refresh setup" org-mode-restart t]
14126 (defun org-info (&optional node)
14127 "Read documentation for Org-mode in the info system.
14128 With optional NODE, go directly to that node."
14129 (interactive)
14130 (info (format "(org)%s" (or node ""))))
14132 (defun org-install-agenda-files-menu ()
14133 (let ((bl (buffer-list)))
14134 (save-excursion
14135 (while bl
14136 (set-buffer (pop bl))
14137 (if (org-mode-p) (setq bl nil)))
14138 (when (org-mode-p)
14139 (easy-menu-change
14140 '("Org") "File List for Agenda"
14141 (append
14142 (list
14143 ["Edit File List" (org-edit-agenda-file-list) t]
14144 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
14145 ["Remove Current File from List" org-remove-file t]
14146 ["Cycle through agenda files" org-cycle-agenda-files t]
14147 ["Occur in all agenda files" org-occur-in-agenda-files t]
14148 "--")
14149 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
14151 ;;;; Documentation
14153 (defun org-customize ()
14154 "Call the customize function with org as argument."
14155 (interactive)
14156 (customize-browse 'org))
14158 (defun org-create-customize-menu ()
14159 "Create a full customization menu for Org-mode, insert it into the menu."
14160 (interactive)
14161 (if (fboundp 'customize-menu-create)
14162 (progn
14163 (easy-menu-change
14164 '("Org") "Customize"
14165 `(["Browse Org group" org-customize t]
14166 "--"
14167 ,(customize-menu-create 'org)
14168 ["Set" Custom-set t]
14169 ["Save" Custom-save t]
14170 ["Reset to Current" Custom-reset-current t]
14171 ["Reset to Saved" Custom-reset-saved t]
14172 ["Reset to Standard Settings" Custom-reset-standard t]))
14173 (message "\"Org\"-menu now contains full customization menu"))
14174 (error "Cannot expand menu (outdated version of cus-edit.el)")))
14176 ;;;; Miscellaneous stuff
14178 ;;; Generally useful functions
14180 (defun org-force-self-insert (N)
14181 "Needed to enforce self-insert under remapping."
14182 (interactive "p")
14183 (self-insert-command N))
14185 (defun org-string-width (s)
14186 "Compute width of string, ignoring invisible characters.
14187 This ignores character with invisibility property `org-link', and also
14188 characters with property `org-cwidth', because these will become invisible
14189 upon the next fontification round."
14190 (let (b l)
14191 (when (or (eq t buffer-invisibility-spec)
14192 (assq 'org-link buffer-invisibility-spec))
14193 (while (setq b (text-property-any 0 (length s)
14194 'invisible 'org-link s))
14195 (setq s (concat (substring s 0 b)
14196 (substring s (or (next-single-property-change
14197 b 'invisible s) (length s)))))))
14198 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
14199 (setq s (concat (substring s 0 b)
14200 (substring s (or (next-single-property-change
14201 b 'org-cwidth s) (length s))))))
14202 (setq l (string-width s) b -1)
14203 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
14204 (setq l (- l (get-text-property b 'org-dwidth-n s))))
14208 (defun org-trim (s)
14209 "Remove whitespace at beginning and end of string."
14210 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
14211 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
14214 (defun org-wrap (string &optional width lines)
14215 "Wrap string to either a number of lines, or a width in characters.
14216 If WIDTH is non-nil, the string is wrapped to that width, however many lines
14217 that costs. If there is a word longer than WIDTH, the text is actually
14218 wrapped to the length of that word.
14219 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
14220 many lines, whatever width that takes.
14221 The return value is a list of lines, without newlines at the end."
14222 (let* ((words (org-split-string string "[ \t\n]+"))
14223 (maxword (apply 'max (mapcar 'org-string-width words)))
14224 w ll)
14225 (cond (width
14226 (org-do-wrap words (max maxword width)))
14227 (lines
14228 (setq w maxword)
14229 (setq ll (org-do-wrap words maxword))
14230 (if (<= (length ll) lines)
14232 (setq ll words)
14233 (while (> (length ll) lines)
14234 (setq w (1+ w))
14235 (setq ll (org-do-wrap words w)))
14236 ll))
14237 (t (error "Cannot wrap this")))))
14239 (defun org-do-wrap (words width)
14240 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
14241 (let (lines line)
14242 (while words
14243 (setq line (pop words))
14244 (while (and words (< (+ (length line) (length (car words))) width))
14245 (setq line (concat line " " (pop words))))
14246 (setq lines (push line lines)))
14247 (nreverse lines)))
14249 (defun org-split-string (string &optional separators)
14250 "Splits STRING into substrings at SEPARATORS.
14251 No empty strings are returned if there are matches at the beginning
14252 and end of string."
14253 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
14254 (start 0)
14255 notfirst
14256 (list nil))
14257 (while (and (string-match rexp string
14258 (if (and notfirst
14259 (= start (match-beginning 0))
14260 (< start (length string)))
14261 (1+ start) start))
14262 (< (match-beginning 0) (length string)))
14263 (setq notfirst t)
14264 (or (eq (match-beginning 0) 0)
14265 (and (eq (match-beginning 0) (match-end 0))
14266 (eq (match-beginning 0) start))
14267 (setq list
14268 (cons (substring string start (match-beginning 0))
14269 list)))
14270 (setq start (match-end 0)))
14271 (or (eq start (length string))
14272 (setq list
14273 (cons (substring string start)
14274 list)))
14275 (nreverse list)))
14277 (defun org-context ()
14278 "Return a list of contexts of the current cursor position.
14279 If several contexts apply, all are returned.
14280 Each context entry is a list with a symbol naming the context, and
14281 two positions indicating start and end of the context. Possible
14282 contexts are:
14284 :headline anywhere in a headline
14285 :headline-stars on the leading stars in a headline
14286 :todo-keyword on a TODO keyword (including DONE) in a headline
14287 :tags on the TAGS in a headline
14288 :priority on the priority cookie in a headline
14289 :item on the first line of a plain list item
14290 :item-bullet on the bullet/number of a plain list item
14291 :checkbox on the checkbox in a plain list item
14292 :table in an org-mode table
14293 :table-special on a special filed in a table
14294 :table-table in a table.el table
14295 :link on a hyperlink
14296 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
14297 :target on a <<target>>
14298 :radio-target on a <<<radio-target>>>
14299 :latex-fragment on a LaTeX fragment
14300 :latex-preview on a LaTeX fragment with overlayed preview image
14302 This function expects the position to be visible because it uses font-lock
14303 faces as a help to recognize the following contexts: :table-special, :link,
14304 and :keyword."
14305 (let* ((f (get-text-property (point) 'face))
14306 (faces (if (listp f) f (list f)))
14307 (p (point)) clist o)
14308 ;; First the large context
14309 (cond
14310 ((org-on-heading-p t)
14311 (push (list :headline (point-at-bol) (point-at-eol)) clist)
14312 (when (progn
14313 (beginning-of-line 1)
14314 (looking-at org-todo-line-tags-regexp))
14315 (push (org-point-in-group p 1 :headline-stars) clist)
14316 (push (org-point-in-group p 2 :todo-keyword) clist)
14317 (push (org-point-in-group p 4 :tags) clist))
14318 (goto-char p)
14319 (skip-chars-backward "^[\n\r \t") (or (eobp) (backward-char 1))
14320 (if (looking-at "\\[#[A-Z0-9]\\]")
14321 (push (org-point-in-group p 0 :priority) clist)))
14323 ((org-at-item-p)
14324 (push (org-point-in-group p 2 :item-bullet) clist)
14325 (push (list :item (point-at-bol)
14326 (save-excursion (org-end-of-item) (point)))
14327 clist)
14328 (and (org-at-item-checkbox-p)
14329 (push (org-point-in-group p 0 :checkbox) clist)))
14331 ((org-at-table-p)
14332 (push (list :table (org-table-begin) (org-table-end)) clist)
14333 (if (memq 'org-formula faces)
14334 (push (list :table-special
14335 (previous-single-property-change p 'face)
14336 (next-single-property-change p 'face)) clist)))
14337 ((org-at-table-p 'any)
14338 (push (list :table-table) clist)))
14339 (goto-char p)
14341 ;; Now the small context
14342 (cond
14343 ((org-at-timestamp-p)
14344 (push (org-point-in-group p 0 :timestamp) clist))
14345 ((memq 'org-link faces)
14346 (push (list :link
14347 (previous-single-property-change p 'face)
14348 (next-single-property-change p 'face)) clist))
14349 ((memq 'org-special-keyword faces)
14350 (push (list :keyword
14351 (previous-single-property-change p 'face)
14352 (next-single-property-change p 'face)) clist))
14353 ((org-on-target-p)
14354 (push (org-point-in-group p 0 :target) clist)
14355 (goto-char (1- (match-beginning 0)))
14356 (if (looking-at org-radio-target-regexp)
14357 (push (org-point-in-group p 0 :radio-target) clist))
14358 (goto-char p))
14359 ((setq o (car (delq nil
14360 (mapcar
14361 (lambda (x)
14362 (if (memq x org-latex-fragment-image-overlays) x))
14363 (org-overlays-at (point))))))
14364 (push (list :latex-fragment
14365 (org-overlay-start o) (org-overlay-end o)) clist)
14366 (push (list :latex-preview
14367 (org-overlay-start o) (org-overlay-end o)) clist))
14368 ((org-inside-LaTeX-fragment-p)
14369 ;; FIXME: positions wrong.
14370 (push (list :latex-fragment (point) (point)) clist)))
14372 (setq clist (nreverse (delq nil clist)))
14373 clist))
14375 ;; FIXME: Compare with at-regexp-p Do we need both?
14376 (defun org-in-regexp (re &optional nlines visually)
14377 "Check if point is inside a match of regexp.
14378 Normally only the current line is checked, but you can include NLINES extra
14379 lines both before and after point into the search.
14380 If VISUALLY is set, require that the cursor is not after the match but
14381 really on, so that the block visually is on the match."
14382 (catch 'exit
14383 (let ((pos (point))
14384 (eol (point-at-eol (+ 1 (or nlines 0))))
14385 (inc (if visually 1 0)))
14386 (save-excursion
14387 (beginning-of-line (- 1 (or nlines 0)))
14388 (while (re-search-forward re eol t)
14389 (if (and (<= (match-beginning 0) pos)
14390 (>= (+ inc (match-end 0)) pos))
14391 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
14393 (defun org-at-regexp-p (regexp)
14394 "Is point inside a match of REGEXP in the current line?"
14395 (catch 'exit
14396 (save-excursion
14397 (let ((pos (point)) (end (point-at-eol)))
14398 (beginning-of-line 1)
14399 (while (re-search-forward regexp end t)
14400 (if (and (<= (match-beginning 0) pos)
14401 (>= (match-end 0) pos))
14402 (throw 'exit t)))
14403 nil))))
14405 (defun org-occur-in-agenda-files (regexp &optional nlines)
14406 "Call `multi-occur' with buffers for all agenda files."
14407 (interactive "sOrg-files matching: \np")
14408 (let* ((files (org-agenda-files))
14409 (tnames (mapcar 'file-truename files))
14410 (extra org-agenda-text-search-extra-files)
14412 (while (setq f (pop extra))
14413 (unless (member (file-truename f) tnames)
14414 (add-to-list 'files f 'append)
14415 (add-to-list 'tnames (file-truename f) 'append)))
14416 (multi-occur
14417 (mapcar (lambda (x) (or (get-file-buffer x) (find-file-noselect x))) files)
14418 regexp)))
14420 (if (boundp 'occur-mode-find-occurrence-hook)
14421 ;; Emacs 23
14422 (add-hook 'occur-mode-find-occurrence-hook
14423 (lambda ()
14424 (when (org-mode-p)
14425 (org-reveal))))
14426 ;; Emacs 22
14427 (defadvice occur-mode-goto-occurrence
14428 (after org-occur-reveal activate)
14429 (and (org-mode-p) (org-reveal)))
14430 (defadvice occur-mode-goto-occurrence-other-window
14431 (after org-occur-reveal activate)
14432 (and (org-mode-p) (org-reveal)))
14433 (defadvice occur-mode-display-occurrence
14434 (after org-occur-reveal activate)
14435 (when (org-mode-p)
14436 (let ((pos (occur-mode-find-occurrence)))
14437 (with-current-buffer (marker-buffer pos)
14438 (save-excursion
14439 (goto-char pos)
14440 (org-reveal)))))))
14442 (defun org-uniquify (list)
14443 "Remove duplicate elements from LIST."
14444 (let (res)
14445 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
14446 res))
14448 (defun org-delete-all (elts list)
14449 "Remove all elements in ELTS from LIST."
14450 (while elts
14451 (setq list (delete (pop elts) list)))
14452 list)
14454 (defun org-back-over-empty-lines ()
14455 "Move backwards over witespace, to the beginning of the first empty line.
14456 Returns the number of empty lines passed."
14457 (let ((pos (point)))
14458 (skip-chars-backward " \t\n\r")
14459 (beginning-of-line 2)
14460 (goto-char (min (point) pos))
14461 (count-lines (point) pos)))
14463 (defun org-skip-whitespace ()
14464 (skip-chars-forward " \t\n\r"))
14466 (defun org-point-in-group (point group &optional context)
14467 "Check if POINT is in match-group GROUP.
14468 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
14469 match. If the match group does ot exist or point is not inside it,
14470 return nil."
14471 (and (match-beginning group)
14472 (>= point (match-beginning group))
14473 (<= point (match-end group))
14474 (if context
14475 (list context (match-beginning group) (match-end group))
14476 t)))
14478 (defun org-switch-to-buffer-other-window (&rest args)
14479 "Switch to buffer in a second window on the current frame.
14480 In particular, do not allow pop-up frames."
14481 (let (pop-up-frames special-display-buffer-names special-display-regexps
14482 special-display-function)
14483 (apply 'switch-to-buffer-other-window args)))
14485 (defun org-combine-plists (&rest plists)
14486 "Create a single property list from all plists in PLISTS.
14487 The process starts by copying the first list, and then setting properties
14488 from the other lists. Settings in the last list are the most significant
14489 ones and overrule settings in the other lists."
14490 (let ((rtn (copy-sequence (pop plists)))
14491 p v ls)
14492 (while plists
14493 (setq ls (pop plists))
14494 (while ls
14495 (setq p (pop ls) v (pop ls))
14496 (setq rtn (plist-put rtn p v))))
14497 rtn))
14499 (defun org-move-line-down (arg)
14500 "Move the current line down. With prefix argument, move it past ARG lines."
14501 (interactive "p")
14502 (let ((col (current-column))
14503 beg end pos)
14504 (beginning-of-line 1) (setq beg (point))
14505 (beginning-of-line 2) (setq end (point))
14506 (beginning-of-line (+ 1 arg))
14507 (setq pos (move-marker (make-marker) (point)))
14508 (insert (delete-and-extract-region beg end))
14509 (goto-char pos)
14510 (move-to-column col)))
14512 (defun org-move-line-up (arg)
14513 "Move the current line up. With prefix argument, move it past ARG lines."
14514 (interactive "p")
14515 (let ((col (current-column))
14516 beg end pos)
14517 (beginning-of-line 1) (setq beg (point))
14518 (beginning-of-line 2) (setq end (point))
14519 (beginning-of-line (- arg))
14520 (setq pos (move-marker (make-marker) (point)))
14521 (insert (delete-and-extract-region beg end))
14522 (goto-char pos)
14523 (move-to-column col)))
14525 (defun org-replace-escapes (string table)
14526 "Replace %-escapes in STRING with values in TABLE.
14527 TABLE is an association list with keys like \"%a\" and string values.
14528 The sequences in STRING may contain normal field width and padding information,
14529 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
14530 so values can contain further %-escapes if they are define later in TABLE."
14531 (let ((case-fold-search nil)
14532 e re rpl)
14533 (while (setq e (pop table))
14534 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
14535 (while (string-match re string)
14536 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
14537 (cdr e)))
14538 (setq string (replace-match rpl t t string))))
14539 string))
14542 (defun org-sublist (list start end)
14543 "Return a section of LIST, from START to END.
14544 Counting starts at 1."
14545 (let (rtn (c start))
14546 (setq list (nthcdr (1- start) list))
14547 (while (and list (<= c end))
14548 (push (pop list) rtn)
14549 (setq c (1+ c)))
14550 (nreverse rtn)))
14552 (defun org-find-base-buffer-visiting (file)
14553 "Like `find-buffer-visiting' but alway return the base buffer and
14554 not an indirect buffer."
14555 (let ((buf (find-buffer-visiting file)))
14556 (if buf
14557 (or (buffer-base-buffer buf) buf)
14558 nil)))
14560 (defun org-image-file-name-regexp ()
14561 "Return regexp matching the file names of images."
14562 (if (fboundp 'image-file-name-regexp)
14563 (image-file-name-regexp)
14564 (let ((image-file-name-extensions
14565 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
14566 "xbm" "xpm" "pbm" "pgm" "ppm")))
14567 (concat "\\."
14568 (regexp-opt (nconc (mapcar 'upcase
14569 image-file-name-extensions)
14570 image-file-name-extensions)
14572 "\\'"))))
14574 (defun org-file-image-p (file)
14575 "Return non-nil if FILE is an image."
14576 (save-match-data
14577 (string-match (org-image-file-name-regexp) file)))
14579 ;;; Paragraph filling stuff.
14580 ;; We want this to be just right, so use the full arsenal.
14582 (defun org-indent-line-function ()
14583 "Indent line like previous, but further if previous was headline or item."
14584 (interactive)
14585 (let* ((pos (point))
14586 (itemp (org-at-item-p))
14587 column bpos bcol tpos tcol bullet btype bullet-type)
14588 ;; Find the previous relevant line
14589 (beginning-of-line 1)
14590 (cond
14591 ((looking-at "#") (setq column 0))
14592 ((looking-at "\\*+ ") (setq column 0))
14594 (beginning-of-line 0)
14595 (while (and (not (bobp)) (looking-at "[ \t]*[\n:#|]"))
14596 (beginning-of-line 0))
14597 (cond
14598 ((looking-at "\\*+[ \t]+")
14599 (goto-char (match-end 0))
14600 (setq column (current-column)))
14601 ((org-in-item-p)
14602 (org-beginning-of-item)
14603 ; (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
14604 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*\\(\\[[- X]\\][ \t]*\\)?")
14605 (setq bpos (match-beginning 1) tpos (match-end 0)
14606 bcol (progn (goto-char bpos) (current-column))
14607 tcol (progn (goto-char tpos) (current-column))
14608 bullet (match-string 1)
14609 bullet-type (if (string-match "[0-9]" bullet) "n" bullet))
14610 (if (not itemp)
14611 (setq column tcol)
14612 (goto-char pos)
14613 (beginning-of-line 1)
14614 (if (looking-at "\\S-")
14615 (progn
14616 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
14617 (setq bullet (match-string 1)
14618 btype (if (string-match "[0-9]" bullet) "n" bullet))
14619 (setq column (if (equal btype bullet-type) bcol tcol)))
14620 (setq column (org-get-indentation)))))
14621 (t (setq column (org-get-indentation))))))
14622 (goto-char pos)
14623 (if (<= (current-column) (current-indentation))
14624 (indent-line-to column)
14625 (save-excursion (indent-line-to column)))
14626 (setq column (current-column))
14627 (beginning-of-line 1)
14628 (if (looking-at
14629 "\\([ \t]+\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
14630 (replace-match (concat "\\1" (format org-property-format
14631 (match-string 2) (match-string 3)))
14632 t nil))
14633 (move-to-column column)))
14635 (defun org-set-autofill-regexps ()
14636 (interactive)
14637 ;; In the paragraph separator we include headlines, because filling
14638 ;; text in a line directly attached to a headline would otherwise
14639 ;; fill the headline as well.
14640 (org-set-local 'comment-start-skip "^#+[ \t]*")
14641 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|]")
14642 ;; The paragraph starter includes hand-formatted lists.
14643 (org-set-local 'paragraph-start
14644 "\f\\|[ ]*$\\|\\*+ \\|\f\\|[ \t]*\\([-+*][ \t]+\\|[0-9]+[.)][ \t]+\\)\\|[ \t]*[:|]")
14645 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
14646 ;; But only if the user has not turned off tables or fixed-width regions
14647 (org-set-local
14648 'auto-fill-inhibit-regexp
14649 (concat "\\*+ \\|#\\+"
14650 "\\|[ \t]*" org-keyword-time-regexp
14651 (if (or org-enable-table-editor org-enable-fixed-width-editor)
14652 (concat
14653 "\\|[ \t]*["
14654 (if org-enable-table-editor "|" "")
14655 (if org-enable-fixed-width-editor ":" "")
14656 "]"))))
14657 ;; We use our own fill-paragraph function, to make sure that tables
14658 ;; and fixed-width regions are not wrapped. That function will pass
14659 ;; through to `fill-paragraph' when appropriate.
14660 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
14661 ; Adaptive filling: To get full control, first make sure that
14662 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
14663 (org-set-local 'adaptive-fill-regexp "\000")
14664 (org-set-local 'adaptive-fill-function
14665 'org-adaptive-fill-function)
14666 (org-set-local
14667 'align-mode-rules-list
14668 '((org-in-buffer-settings
14669 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
14670 (modes . '(org-mode))))))
14672 (defun org-fill-paragraph (&optional justify)
14673 "Re-align a table, pass through to fill-paragraph if no table."
14674 (let ((table-p (org-at-table-p))
14675 (table.el-p (org-at-table.el-p)))
14676 (cond ((and (equal (char-after (point-at-bol)) ?*)
14677 (save-excursion (goto-char (point-at-bol))
14678 (looking-at outline-regexp)))
14679 t) ; skip headlines
14680 (table.el-p t) ; skip table.el tables
14681 (table-p (org-table-align) t) ; align org-mode tables
14682 (t nil)))) ; call paragraph-fill
14684 ;; For reference, this is the default value of adaptive-fill-regexp
14685 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
14687 (defun org-adaptive-fill-function ()
14688 "Return a fill prefix for org-mode files.
14689 In particular, this makes sure hanging paragraphs for hand-formatted lists
14690 work correctly."
14691 (cond ((looking-at "#[ \t]+")
14692 (match-string 0))
14693 ((looking-at "[ \t]*\\([-*+] \\|[0-9]+[.)] \\)?")
14694 (save-excursion
14695 (goto-char (match-end 0))
14696 (make-string (current-column) ?\ )))
14697 (t nil)))
14699 ;;; Other stuff.
14701 (defun org-toggle-fixed-width-section (arg)
14702 "Toggle the fixed-width export.
14703 If there is no active region, the QUOTE keyword at the current headline is
14704 inserted or removed. When present, it causes the text between this headline
14705 and the next to be exported as fixed-width text, and unmodified.
14706 If there is an active region, this command adds or removes a colon as the
14707 first character of this line. If the first character of a line is a colon,
14708 this line is also exported in fixed-width font."
14709 (interactive "P")
14710 (let* ((cc 0)
14711 (regionp (org-region-active-p))
14712 (beg (if regionp (region-beginning) (point)))
14713 (end (if regionp (region-end)))
14714 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
14715 (case-fold-search nil)
14716 (re "[ \t]*\\(:\\)")
14717 off)
14718 (if regionp
14719 (save-excursion
14720 (goto-char beg)
14721 (setq cc (current-column))
14722 (beginning-of-line 1)
14723 (setq off (looking-at re))
14724 (while (> nlines 0)
14725 (setq nlines (1- nlines))
14726 (beginning-of-line 1)
14727 (cond
14728 (arg
14729 (move-to-column cc t)
14730 (insert ":\n")
14731 (forward-line -1))
14732 ((and off (looking-at re))
14733 (replace-match "" t t nil 1))
14734 ((not off) (move-to-column cc t) (insert ":")))
14735 (forward-line 1)))
14736 (save-excursion
14737 (org-back-to-heading)
14738 (if (looking-at (concat outline-regexp
14739 "\\( *\\<" org-quote-string "\\>[ \t]*\\)"))
14740 (replace-match "" t t nil 1)
14741 (if (looking-at outline-regexp)
14742 (progn
14743 (goto-char (match-end 0))
14744 (insert org-quote-string " "))))))))
14746 ;;;; Functions extending outline functionality
14748 (defun org-beginning-of-line (&optional arg)
14749 "Go to the beginning of the current line. If that is invisible, continue
14750 to a visible line beginning. This makes the function of C-a more intuitive.
14751 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
14752 first attempt, and only move to after the tags when the cursor is already
14753 beyond the end of the headline."
14754 (interactive "P")
14755 (let ((pos (point)))
14756 (beginning-of-line 1)
14757 (if (bobp)
14759 (backward-char 1)
14760 (if (org-invisible-p)
14761 (while (and (not (bobp)) (org-invisible-p))
14762 (backward-char 1)
14763 (beginning-of-line 1))
14764 (forward-char 1)))
14765 (when org-special-ctrl-a/e
14766 (cond
14767 ((and (looking-at org-todo-line-regexp)
14768 (= (char-after (match-end 1)) ?\ ))
14769 (goto-char
14770 (if (eq org-special-ctrl-a/e t)
14771 (cond ((> pos (match-beginning 3)) (match-beginning 3))
14772 ((= pos (point)) (match-beginning 3))
14773 (t (point)))
14774 (cond ((> pos (point)) (point))
14775 ((not (eq last-command this-command)) (point))
14776 (t (match-beginning 3))))))
14777 ((org-at-item-p)
14778 (goto-char
14779 (if (eq org-special-ctrl-a/e t)
14780 (cond ((> pos (match-end 4)) (match-end 4))
14781 ((= pos (point)) (match-end 4))
14782 (t (point)))
14783 (cond ((> pos (point)) (point))
14784 ((not (eq last-command this-command)) (point))
14785 (t (match-end 4))))))))))
14787 (defun org-end-of-line (&optional arg)
14788 "Go to the end of the line.
14789 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
14790 first attempt, and only move to after the tags when the cursor is already
14791 beyond the end of the headline."
14792 (interactive "P")
14793 (if (or (not org-special-ctrl-a/e)
14794 (not (org-on-heading-p)))
14795 (end-of-line arg)
14796 (let ((pos (point)))
14797 (beginning-of-line 1)
14798 (if (looking-at (org-re ".*?\\([ \t]*\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
14799 (if (eq org-special-ctrl-a/e t)
14800 (if (or (< pos (match-beginning 1))
14801 (= pos (match-end 0)))
14802 (goto-char (match-beginning 1))
14803 (goto-char (match-end 0)))
14804 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
14805 (goto-char (match-end 0))
14806 (goto-char (match-beginning 1))))
14807 (end-of-line arg)))))
14809 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
14810 (define-key org-mode-map "\C-e" 'org-end-of-line)
14812 (defun org-kill-line (&optional arg)
14813 "Kill line, to tags or end of line."
14814 (interactive "P")
14815 (cond
14816 ((or (not org-special-ctrl-k)
14817 (bolp)
14818 (not (org-on-heading-p)))
14819 (call-interactively 'kill-line))
14820 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$"))
14821 (kill-region (point) (match-beginning 1))
14822 (org-set-tags nil t))
14823 (t (kill-region (point) (point-at-eol)))))
14825 (define-key org-mode-map "\C-k" 'org-kill-line)
14827 (defun org-invisible-p ()
14828 "Check if point is at a character currently not visible."
14829 ;; Early versions of noutline don't have `outline-invisible-p'.
14830 (if (fboundp 'outline-invisible-p)
14831 (outline-invisible-p)
14832 (get-char-property (point) 'invisible)))
14834 (defun org-invisible-p2 ()
14835 "Check if point is at a character currently not visible."
14836 (save-excursion
14837 (if (and (eolp) (not (bobp))) (backward-char 1))
14838 ;; Early versions of noutline don't have `outline-invisible-p'.
14839 (if (fboundp 'outline-invisible-p)
14840 (outline-invisible-p)
14841 (get-char-property (point) 'invisible))))
14843 (defalias 'org-back-to-heading 'outline-back-to-heading)
14844 (defalias 'org-on-heading-p 'outline-on-heading-p)
14845 (defalias 'org-at-heading-p 'outline-on-heading-p)
14846 (defun org-at-heading-or-item-p ()
14847 (or (org-on-heading-p) (org-at-item-p)))
14849 (defun org-on-target-p ()
14850 (or (org-in-regexp org-radio-target-regexp)
14851 (org-in-regexp org-target-regexp)))
14853 (defun org-up-heading-all (arg)
14854 "Move to the heading line of which the present line is a subheading.
14855 This function considers both visible and invisible heading lines.
14856 With argument, move up ARG levels."
14857 (if (fboundp 'outline-up-heading-all)
14858 (outline-up-heading-all arg) ; emacs 21 version of outline.el
14859 (outline-up-heading arg t))) ; emacs 22 version of outline.el
14861 (defun org-up-heading-safe ()
14862 "Move to the heading line of which the present line is a subheading.
14863 This version will not throw an error. It will return the level of the
14864 headline found, or nil if no higher level is found."
14865 (let ((pos (point)) start-level level
14866 (re (concat "^" outline-regexp)))
14867 (catch 'exit
14868 (outline-back-to-heading t)
14869 (setq start-level (funcall outline-level))
14870 (if (equal start-level 1) (throw 'exit nil))
14871 (while (re-search-backward re nil t)
14872 (setq level (funcall outline-level))
14873 (if (< level start-level) (throw 'exit level)))
14874 nil)))
14876 (defun org-first-sibling-p ()
14877 "Is this heading the first child of its parents?"
14878 (interactive)
14879 (let ((re (concat "^" outline-regexp))
14880 level l)
14881 (unless (org-at-heading-p t)
14882 (error "Not at a heading"))
14883 (setq level (funcall outline-level))
14884 (save-excursion
14885 (if (not (re-search-backward re nil t))
14887 (setq l (funcall outline-level))
14888 (< l level)))))
14890 (defun org-goto-sibling (&optional previous)
14891 "Goto the next sibling, even if it is invisible.
14892 When PREVIOUS is set, go to the previous sibling instead. Returns t
14893 when a sibling was found. When none is found, return nil and don't
14894 move point."
14895 (let ((fun (if previous 're-search-backward 're-search-forward))
14896 (pos (point))
14897 (re (concat "^" outline-regexp))
14898 level l)
14899 (when (condition-case nil (org-back-to-heading t) (error nil))
14900 (setq level (funcall outline-level))
14901 (catch 'exit
14902 (or previous (forward-char 1))
14903 (while (funcall fun re nil t)
14904 (setq l (funcall outline-level))
14905 (when (< l level) (goto-char pos) (throw 'exit nil))
14906 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
14907 (goto-char pos)
14908 nil))))
14910 (defun org-show-siblings ()
14911 "Show all siblings of the current headline."
14912 (save-excursion
14913 (while (org-goto-sibling) (org-flag-heading nil)))
14914 (save-excursion
14915 (while (org-goto-sibling 'previous)
14916 (org-flag-heading nil))))
14918 (defun org-show-hidden-entry ()
14919 "Show an entry where even the heading is hidden."
14920 (save-excursion
14921 (org-show-entry)))
14923 (defun org-flag-heading (flag &optional entry)
14924 "Flag the current heading. FLAG non-nil means make invisible.
14925 When ENTRY is non-nil, show the entire entry."
14926 (save-excursion
14927 (org-back-to-heading t)
14928 ;; Check if we should show the entire entry
14929 (if entry
14930 (progn
14931 (org-show-entry)
14932 (save-excursion
14933 (and (outline-next-heading)
14934 (org-flag-heading nil))))
14935 (outline-flag-region (max (point-min) (1- (point)))
14936 (save-excursion (outline-end-of-heading) (point))
14937 flag))))
14939 (defun org-end-of-subtree (&optional invisible-OK to-heading)
14940 ;; This is an exact copy of the original function, but it uses
14941 ;; `org-back-to-heading', to make it work also in invisible
14942 ;; trees. And is uses an invisible-OK argument.
14943 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
14944 (org-back-to-heading invisible-OK)
14945 (let ((first t)
14946 (level (funcall outline-level)))
14947 (while (and (not (eobp))
14948 (or first (> (funcall outline-level) level)))
14949 (setq first nil)
14950 (outline-next-heading))
14951 (unless to-heading
14952 (if (memq (preceding-char) '(?\n ?\^M))
14953 (progn
14954 ;; Go to end of line before heading
14955 (forward-char -1)
14956 (if (memq (preceding-char) '(?\n ?\^M))
14957 ;; leave blank line before heading
14958 (forward-char -1))))))
14959 (point))
14961 (defun org-show-subtree ()
14962 "Show everything after this heading at deeper levels."
14963 (outline-flag-region
14964 (point)
14965 (save-excursion
14966 (outline-end-of-subtree) (outline-next-heading) (point))
14967 nil))
14969 (defun org-show-entry ()
14970 "Show the body directly following this heading.
14971 Show the heading too, if it is currently invisible."
14972 (interactive)
14973 (save-excursion
14974 (condition-case nil
14975 (progn
14976 (org-back-to-heading t)
14977 (outline-flag-region
14978 (max (point-min) (1- (point)))
14979 (save-excursion
14980 (re-search-forward
14981 (concat "[\r\n]\\(" outline-regexp "\\)") nil 'move)
14982 (or (match-beginning 1) (point-max)))
14983 nil))
14984 (error nil))))
14986 (defun org-make-options-regexp (kwds)
14987 "Make a regular expression for keyword lines."
14988 (concat
14990 "#?[ \t]*\\+\\("
14991 (mapconcat 'regexp-quote kwds "\\|")
14992 "\\):[ \t]*"
14993 "\\(.+\\)"))
14995 ;; Make isearch reveal the necessary context
14996 (defun org-isearch-end ()
14997 "Reveal context after isearch exits."
14998 (when isearch-success ; only if search was successful
14999 (if (featurep 'xemacs)
15000 ;; Under XEmacs, the hook is run in the correct place,
15001 ;; we directly show the context.
15002 (org-show-context 'isearch)
15003 ;; In Emacs the hook runs *before* restoring the overlays.
15004 ;; So we have to use a one-time post-command-hook to do this.
15005 ;; (Emacs 22 has a special variable, see function `org-mode')
15006 (unless (and (boundp 'isearch-mode-end-hook-quit)
15007 isearch-mode-end-hook-quit)
15008 ;; Only when the isearch was not quitted.
15009 (org-add-hook 'post-command-hook 'org-isearch-post-command
15010 'append 'local)))))
15012 (defun org-isearch-post-command ()
15013 "Remove self from hook, and show context."
15014 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
15015 (org-show-context 'isearch))
15018 ;;;; Integration with and fixes for other packages
15020 ;;; Imenu support
15022 (defvar org-imenu-markers nil
15023 "All markers currently used by Imenu.")
15024 (make-variable-buffer-local 'org-imenu-markers)
15026 (defun org-imenu-new-marker (&optional pos)
15027 "Return a new marker for use by Imenu, and remember the marker."
15028 (let ((m (make-marker)))
15029 (move-marker m (or pos (point)))
15030 (push m org-imenu-markers)
15033 (defun org-imenu-get-tree ()
15034 "Produce the index for Imenu."
15035 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
15036 (setq org-imenu-markers nil)
15037 (let* ((n org-imenu-depth)
15038 (re (concat "^" outline-regexp))
15039 (subs (make-vector (1+ n) nil))
15040 (last-level 0)
15041 m tree level head)
15042 (save-excursion
15043 (save-restriction
15044 (widen)
15045 (goto-char (point-max))
15046 (while (re-search-backward re nil t)
15047 (setq level (org-reduced-level (funcall outline-level)))
15048 (when (<= level n)
15049 (looking-at org-complex-heading-regexp)
15050 (setq head (org-match-string-no-properties 4)
15051 m (org-imenu-new-marker))
15052 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
15053 (if (>= level last-level)
15054 (push (cons head m) (aref subs level))
15055 (push (cons head (aref subs (1+ level))) (aref subs level))
15056 (loop for i from (1+ level) to n do (aset subs i nil)))
15057 (setq last-level level)))))
15058 (aref subs 1)))
15060 (eval-after-load "imenu"
15061 '(progn
15062 (add-hook 'imenu-after-jump-hook
15063 (lambda () (org-show-context 'org-goto)))))
15065 ;; Speedbar support
15067 (defvar org-speedbar-restriction-lock-overlay (org-make-overlay 1 1)
15068 "Overlay marking the agenda restriction line in speedbar.")
15069 (org-overlay-put org-speedbar-restriction-lock-overlay
15070 'face 'org-agenda-restriction-lock)
15071 (org-overlay-put org-speedbar-restriction-lock-overlay
15072 'help-echo "Agendas are currently limited to this item.")
15073 (org-detach-overlay org-speedbar-restriction-lock-overlay)
15075 (defun org-speedbar-set-agenda-restriction ()
15076 "Restrict future agenda commands to the location at point in speedbar.
15077 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
15078 (interactive)
15079 (require 'org-agenda)
15080 (let (p m tp np dir txt w)
15081 (cond
15082 ((setq p (text-property-any (point-at-bol) (point-at-eol)
15083 'org-imenu t))
15084 (setq m (get-text-property p 'org-imenu-marker))
15085 (save-excursion
15086 (save-restriction
15087 (set-buffer (marker-buffer m))
15088 (goto-char m)
15089 (org-agenda-set-restriction-lock 'subtree))))
15090 ((setq p (text-property-any (point-at-bol) (point-at-eol)
15091 'speedbar-function 'speedbar-find-file))
15092 (setq tp (previous-single-property-change
15093 (1+ p) 'speedbar-function)
15094 np (next-single-property-change
15095 tp 'speedbar-function)
15096 dir (speedbar-line-directory)
15097 txt (buffer-substring-no-properties (or tp (point-min))
15098 (or np (point-max))))
15099 (save-excursion
15100 (save-restriction
15101 (set-buffer (find-file-noselect
15102 (let ((default-directory dir))
15103 (expand-file-name txt))))
15104 (unless (org-mode-p)
15105 (error "Cannot restrict to non-Org-mode file"))
15106 (org-agenda-set-restriction-lock 'file))))
15107 (t (error "Don't know how to restrict Org-mode's agenda")))
15108 (org-move-overlay org-speedbar-restriction-lock-overlay
15109 (point-at-bol) (point-at-eol))
15110 (setq current-prefix-arg nil)
15111 (org-agenda-maybe-redo)))
15113 (eval-after-load "speedbar"
15114 '(progn
15115 (speedbar-add-supported-extension ".org")
15116 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
15117 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
15118 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
15119 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
15120 (add-hook 'speedbar-visiting-tag-hook
15121 (lambda () (org-show-context 'org-goto)))))
15124 ;;; Fixes and Hacks for problems with other packages
15126 ;; Make flyspell not check words in links, to not mess up our keymap
15127 (defun org-mode-flyspell-verify ()
15128 "Don't let flyspell put overlays at active buttons."
15129 (not (get-text-property (point) 'keymap)))
15131 ;; Make `bookmark-jump' show the jump location if it was hidden.
15132 (eval-after-load "bookmark"
15133 '(if (boundp 'bookmark-after-jump-hook)
15134 ;; We can use the hook
15135 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
15136 ;; Hook not available, use advice
15137 (defadvice bookmark-jump (after org-make-visible activate)
15138 "Make the position visible."
15139 (org-bookmark-jump-unhide))))
15141 (defun org-bookmark-jump-unhide ()
15142 "Unhide the current position, to show the bookmark location."
15143 (and (org-mode-p)
15144 (or (org-invisible-p)
15145 (save-excursion (goto-char (max (point-min) (1- (point))))
15146 (org-invisible-p)))
15147 (org-show-context 'bookmark-jump)))
15149 ;; Make session.el ignore our circular variable
15150 (eval-after-load "session"
15151 '(add-to-list 'session-globals-exclude 'org-mark-ring))
15153 ;;;; Experimental code
15155 (defun org-closed-in-range ()
15156 "Sparse tree of items closed in a certain time range.
15157 Still experimental, may disappear in the future."
15158 (interactive)
15159 ;; Get the time interval from the user.
15160 (let* ((time1 (time-to-seconds
15161 (org-read-date nil 'to-time nil "Starting date: ")))
15162 (time2 (time-to-seconds
15163 (org-read-date nil 'to-time nil "End date:")))
15164 ;; callback function
15165 (callback (lambda ()
15166 (let ((time
15167 (time-to-seconds
15168 (apply 'encode-time
15169 (org-parse-time-string
15170 (match-string 1))))))
15171 ;; check if time in interval
15172 (and (>= time time1) (<= time time2))))))
15173 ;; make tree, check each match with the callback
15174 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
15177 ;;;; Finish up
15179 (provide 'org)
15181 (run-hooks 'org-load-hook)
15183 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
15184 ;;; org.el ends here
15186 (defun org-plist-delete (plist property)
15187 "Delete PROPERTY from PLIST.
15188 This is in contrast to merely setting it to 0."
15189 (let (p)
15190 (while plist
15191 (if (not (eq property (car plist)))
15192 (setq p (plist-put p (car plist) (nth 1 plist))))
15193 (setq plist (cddr plist)))