Make dot an alias for today in the date prompt.
[org-mode.git] / lisp / org.el
blobacb9db0ec7a315788776c32592df7952165c8796
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.02b
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)
90 (require 'org-faces)
92 ;;;; Customization variables
94 ;;; Version
96 (defconst org-version "6.02b"
97 "The version number of the file org.el.")
99 (defun org-version (&optional here)
100 "Show the org-mode version in the echo area.
101 With prefix arg HERE, insert it at point."
102 (interactive "P")
103 (let ((version (format "Org-mode version %s" org-version)))
104 (message version)
105 (if here
106 (insert version))))
108 ;;; Compatibility constants
110 ;;; The custom variables
112 (defgroup org nil
113 "Outline-based notes management and organizer."
114 :tag "Org"
115 :group 'outlines
116 :group 'hypermedia
117 :group 'calendar)
119 (defcustom org-load-hook nil
120 "Hook that is run after org.el has been loaded."
121 :group 'org
122 :type 'hook)
124 (defvar org-modules) ; defined below
125 (defvar org-modules-loaded nil
126 "Have the modules been loaded already?")
128 (defun org-load-modules-maybe (&optional force)
129 "Load all extensions listed in `org-default-extensions'."
130 (when (or force (not org-modules-loaded))
131 (mapc (lambda (ext)
132 (condition-case nil (require ext)
133 (error (message "Problems while trying to load feature `%s'" ext))))
134 org-modules)
135 (setq org-modules-loaded t)))
137 (defun org-set-modules (var value)
138 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
139 (set var value)
140 (when (featurep 'org)
141 (org-load-modules-maybe 'force)))
143 (defcustom org-modules '(org-bbdb org-bibtex org-gnus org-info org-infojs org-irc org-mew org-mhe org-rmail org-vm org-wl)
144 "Modules that should always be loaded together with org.el.
145 If a description starts with <C>, the file is not part of emacs
146 and loading it will require that you have downloaded and properly installed
147 the org-mode distribution.
149 You can also use this system to load external packages (i.e. neither Org
150 core modules, not modules from the CONTRIB directory). Just add symbols
151 to the end of the list. If the package is called org-xyz.e, then you need
152 to add the symbol `xyz', and the package must have a call to
154 (provide 'org-xyz)"
155 :group 'org
156 :set 'org-set-modules
157 :type
158 '(set :greedy t
159 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
160 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
161 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
162 (const :tag " info: Links to Info nodes" org-info)
163 (const :tag " infojs: Set up Sebastian Rose's JavaScript org-info.js" org-infojs)
164 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
165 (const :tag " mac-message: Links to messages in Apple Mail" org-mac-message)
166 (const :tag " mew Links to Mew folders/messages" org-mew)
167 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
168 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
169 (const :tag " vm: Links to VM folders/messages" org-vm)
170 (const :tag " wl: Links to Wanderlust folders/messages" org-wl)
171 (const :tag " mouse: Additional mouse support" org-mouse)
173 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
174 (const :tag "C bookmark: Org links to bookmarks" org-bookmark)
175 (const :tag "C depend: TODO dependencies for Org-mode" org-depend)
176 (const :tag "C elisp-symbol: Org links to emacs-lisp symbols" org-elisp-symbol)
177 (const :tag "C eval: Include command output as text" org-eval)
178 (const :tag "C expiry: Expiry mechanism for Org entries" org-expiry)
179 (const :tag "C id: Global id's for identifying entries" org-id)
180 (const :tag "C interactive-query: Interactive modification of tags query" org-interactive-query)
181 (const :tag "C mairix: Hook mairix search into Org for different MUAs" org-mairix)
182 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
183 (const :tag "C mew: Support for links to messages in Mew" org-mew)
184 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
185 (const :tag "C registry: A registry for Org links" org-registry)
186 (const :tag "C org2rem: Convert org appointments into reminders" org2rem)
187 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
188 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)
189 (const :tag "C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert)
190 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
193 (defgroup org-startup nil
194 "Options concerning startup of Org-mode."
195 :tag "Org Startup"
196 :group 'org)
198 (defcustom org-startup-folded t
199 "Non-nil means, entering Org-mode will switch to OVERVIEW.
200 This can also be configured on a per-file basis by adding one of
201 the following lines anywhere in the buffer:
203 #+STARTUP: fold
204 #+STARTUP: nofold
205 #+STARTUP: content"
206 :group 'org-startup
207 :type '(choice
208 (const :tag "nofold: show all" nil)
209 (const :tag "fold: overview" t)
210 (const :tag "content: all headlines" content)))
212 (defcustom org-startup-truncated t
213 "Non-nil means, entering Org-mode will set `truncate-lines'.
214 This is useful since some lines containing links can be very long and
215 uninteresting. Also tables look terrible when wrapped."
216 :group 'org-startup
217 :type 'boolean)
219 (defcustom org-startup-align-all-tables nil
220 "Non-nil means, align all tables when visiting a file.
221 This is useful when the column width in tables is forced with <N> cookies
222 in table fields. Such tables will look correct only after the first re-align.
223 This can also be configured on a per-file basis by adding one of
224 the following lines anywhere in the buffer:
225 #+STARTUP: align
226 #+STARTUP: noalign"
227 :group 'org-startup
228 :type 'boolean)
230 (defcustom org-insert-mode-line-in-empty-file nil
231 "Non-nil means insert the first line setting Org-mode in empty files.
232 When the function `org-mode' is called interactively in an empty file, this
233 normally means that the file name does not automatically trigger Org-mode.
234 To ensure that the file will always be in Org-mode in the future, a
235 line enforcing Org-mode will be inserted into the buffer, if this option
236 has been set."
237 :group 'org-startup
238 :type 'boolean)
240 (defcustom org-replace-disputed-keys nil
241 "Non-nil means use alternative key bindings for some keys.
242 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
243 These keys are also used by other packages like `CUA-mode' or `windmove.el'.
244 If you want to use Org-mode together with one of these other modes,
245 or more generally if you would like to move some Org-mode commands to
246 other keys, set this variable and configure the keys with the variable
247 `org-disputed-keys'.
249 This option is only relevant at load-time of Org-mode, and must be set
250 *before* org.el is loaded. Changing it requires a restart of Emacs to
251 become effective."
252 :group 'org-startup
253 :type 'boolean)
255 (if (fboundp 'defvaralias)
256 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys))
258 (defcustom org-disputed-keys
259 '(([(shift up)] . [(meta p)])
260 ([(shift down)] . [(meta n)])
261 ([(shift left)] . [(meta -)])
262 ([(shift right)] . [(meta +)])
263 ([(control shift right)] . [(meta shift +)])
264 ([(control shift left)] . [(meta shift -)]))
265 "Keys for which Org-mode and other modes compete.
266 This is an alist, cars are the default keys, second element specifies
267 the alternative to use when `org-replace-disputed-keys' is t.
269 Keys can be specified in any syntax supported by `define-key'.
270 The value of this option takes effect only at Org-mode's startup,
271 therefore you'll have to restart Emacs to apply it after changing."
272 :group 'org-startup
273 :type 'alist)
275 (defun org-key (key)
276 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
277 Or return the original if not disputed."
278 (if org-replace-disputed-keys
279 (let* ((nkey (key-description key))
280 (x (org-find-if (lambda (x)
281 (equal (key-description (car x)) nkey))
282 org-disputed-keys)))
283 (if x (cdr x) key))
284 key))
286 (defun org-find-if (predicate seq)
287 (catch 'exit
288 (while seq
289 (if (funcall predicate (car seq))
290 (throw 'exit (car seq))
291 (pop seq)))))
293 (defun org-defkey (keymap key def)
294 "Define a key, possibly translated, as returned by `org-key'."
295 (define-key keymap (org-key key) def))
297 (defcustom org-ellipsis nil
298 "The ellipsis to use in the Org-mode outline.
299 When nil, just use the standard three dots. When a string, use that instead,
300 When a face, use the standart 3 dots, but with the specified face.
301 The change affects only Org-mode (which will then use its own display table).
302 Changing this requires executing `M-x org-mode' in a buffer to become
303 effective."
304 :group 'org-startup
305 :type '(choice (const :tag "Default" nil)
306 (face :tag "Face" :value org-warning)
307 (string :tag "String" :value "...#")))
309 (defvar org-display-table nil
310 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
312 (defgroup org-keywords nil
313 "Keywords in Org-mode."
314 :tag "Org Keywords"
315 :group 'org)
317 (defcustom org-deadline-string "DEADLINE:"
318 "String to mark deadline entries.
319 A deadline is this string, followed by a time stamp. Should be a word,
320 terminated by a colon. You can insert a schedule keyword and
321 a timestamp with \\[org-deadline].
322 Changes become only effective after restarting Emacs."
323 :group 'org-keywords
324 :type 'string)
326 (defcustom org-scheduled-string "SCHEDULED:"
327 "String to mark scheduled TODO entries.
328 A schedule is this string, followed by a time stamp. Should be a word,
329 terminated by a colon. You can insert a schedule keyword and
330 a timestamp with \\[org-schedule].
331 Changes become only effective after restarting Emacs."
332 :group 'org-keywords
333 :type 'string)
335 (defcustom org-closed-string "CLOSED:"
336 "String used as the prefix for timestamps logging closing a TODO entry."
337 :group 'org-keywords
338 :type 'string)
340 (defcustom org-clock-string "CLOCK:"
341 "String used as prefix for timestamps clocking work hours on an item."
342 :group 'org-keywords
343 :type 'string)
345 (defcustom org-comment-string "COMMENT"
346 "Entries starting with this keyword will never be exported.
347 An entry can be toggled between COMMENT and normal with
348 \\[org-toggle-comment].
349 Changes become only effective after restarting Emacs."
350 :group 'org-keywords
351 :type 'string)
353 (defcustom org-quote-string "QUOTE"
354 "Entries starting with this keyword will be exported in fixed-width font.
355 Quoting applies only to the text in the entry following the headline, and does
356 not extend beyond the next headline, even if that is lower level.
357 An entry can be toggled between QUOTE and normal with
358 \\[org-toggle-fixed-width-section]."
359 :group 'org-keywords
360 :type 'string)
362 (defconst org-repeat-re
363 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*\\([.+]?\\+[0-9]+[dwmy]\\)"
364 "Regular expression for specifying repeated events.
365 After a match, group 1 contains the repeat expression.")
367 (defgroup org-structure nil
368 "Options concerning the general structure of Org-mode files."
369 :tag "Org Structure"
370 :group 'org)
372 (defgroup org-reveal-location nil
373 "Options about how to make context of a location visible."
374 :tag "Org Reveal Location"
375 :group 'org-structure)
377 (defconst org-context-choice
378 '(choice
379 (const :tag "Always" t)
380 (const :tag "Never" nil)
381 (repeat :greedy t :tag "Individual contexts"
382 (cons
383 (choice :tag "Context"
384 (const agenda)
385 (const org-goto)
386 (const occur-tree)
387 (const tags-tree)
388 (const link-search)
389 (const mark-goto)
390 (const bookmark-jump)
391 (const isearch)
392 (const default))
393 (boolean))))
394 "Contexts for the reveal options.")
396 (defcustom org-show-hierarchy-above '((default . t))
397 "Non-nil means, show full hierarchy when revealing a location.
398 Org-mode often shows locations in an org-mode file which might have
399 been invisible before. When this is set, the hierarchy of headings
400 above the exposed location is shown.
401 Turning this off for example for sparse trees makes them very compact.
402 Instead of t, this can also be an alist specifying this option for different
403 contexts. Valid contexts are
404 agenda when exposing an entry from the agenda
405 org-goto when using the command `org-goto' on key C-c C-j
406 occur-tree when using the command `org-occur' on key C-c /
407 tags-tree when constructing a sparse tree based on tags matches
408 link-search when exposing search matches associated with a link
409 mark-goto when exposing the jump goal of a mark
410 bookmark-jump when exposing a bookmark location
411 isearch when exiting from an incremental search
412 default default for all contexts not set explicitly"
413 :group 'org-reveal-location
414 :type org-context-choice)
416 (defcustom org-show-following-heading '((default . nil))
417 "Non-nil means, show following heading when revealing a location.
418 Org-mode often shows locations in an org-mode file which might have
419 been invisible before. When this is set, the heading following the
420 match is shown.
421 Turning this off for example for sparse trees makes them very compact,
422 but makes it harder to edit the location of the match. In such a case,
423 use the command \\[org-reveal] to show more context.
424 Instead of t, this can also be an alist specifying this option for different
425 contexts. See `org-show-hierarchy-above' for valid contexts."
426 :group 'org-reveal-location
427 :type org-context-choice)
429 (defcustom org-show-siblings '((default . nil) (isearch t))
430 "Non-nil means, show all sibling heading when revealing a location.
431 Org-mode often shows locations in an org-mode file which might have
432 been invisible before. When this is set, the sibling of the current entry
433 heading are all made visible. If `org-show-hierarchy-above' is t,
434 the same happens on each level of the hierarchy above the current entry.
436 By default this is on for the isearch context, off for all other contexts.
437 Turning this off for example for sparse trees makes them very compact,
438 but makes it harder to edit the location of the match. In such a case,
439 use the command \\[org-reveal] to show more context.
440 Instead of t, this can also be an alist specifying this option for different
441 contexts. See `org-show-hierarchy-above' for valid contexts."
442 :group 'org-reveal-location
443 :type org-context-choice)
445 (defcustom org-show-entry-below '((default . nil))
446 "Non-nil means, show the entry below a headline when revealing a location.
447 Org-mode often shows locations in an org-mode file which might have
448 been invisible before. When this is set, the text below the headline that is
449 exposed is also shown.
451 By default this is off for all contexts.
452 Instead of t, this can also be an alist specifying this option for different
453 contexts. See `org-show-hierarchy-above' for valid contexts."
454 :group 'org-reveal-location
455 :type org-context-choice)
457 (defcustom org-indirect-buffer-display 'other-window
458 "How should indirect tree buffers be displayed?
459 This applies to indirect buffers created with the commands
460 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
461 Valid values are:
462 current-window Display in the current window
463 other-window Just display in another window.
464 dedicated-frame Create one new frame, and re-use it each time.
465 new-frame Make a new frame each time. Note that in this case
466 previously-made indirect buffers are kept, and you need to
467 kill these buffers yourself."
468 :group 'org-structure
469 :group 'org-agenda-windows
470 :type '(choice
471 (const :tag "In current window" current-window)
472 (const :tag "In current frame, other window" other-window)
473 (const :tag "Each time a new frame" new-frame)
474 (const :tag "One dedicated frame" dedicated-frame)))
476 (defgroup org-cycle nil
477 "Options concerning visibility cycling in Org-mode."
478 :tag "Org Cycle"
479 :group 'org-structure)
481 (defcustom org-drawers '("PROPERTIES" "CLOCK")
482 "Names of drawers. Drawers are not opened by cycling on the headline above.
483 Drawers only open with a TAB on the drawer line itself. A drawer looks like
484 this:
485 :DRAWERNAME:
486 .....
487 :END:
488 The drawer \"PROPERTIES\" is special for capturing properties through
489 the property API.
491 Drawers can be defined on the per-file basis with a line like:
493 #+DRAWERS: HIDDEN STATE PROPERTIES"
494 :group 'org-structure
495 :type '(repeat (string :tag "Drawer Name")))
497 (defcustom org-cycle-global-at-bob nil
498 "Cycle globally if cursor is at beginning of buffer and not at a headline.
499 This makes it possible to do global cycling without having to use S-TAB or
500 C-u TAB. For this special case to work, the first line of the buffer
501 must not be a headline - it may be empty ot some other text. When used in
502 this way, `org-cycle-hook' is disables temporarily, to make sure the
503 cursor stays at the beginning of the buffer.
504 When this option is nil, don't do anything special at the beginning
505 of the buffer."
506 :group 'org-cycle
507 :type 'boolean)
509 (defcustom org-cycle-emulate-tab t
510 "Where should `org-cycle' emulate TAB.
511 nil Never
512 white Only in completely white lines
513 whitestart Only at the beginning of lines, before the first non-white char
514 t Everywhere except in headlines
515 exc-hl-bol Everywhere except at the start of a headline
516 If TAB is used in a place where it does not emulate TAB, the current subtree
517 visibility is cycled."
518 :group 'org-cycle
519 :type '(choice (const :tag "Never" nil)
520 (const :tag "Only in completely white lines" white)
521 (const :tag "Before first char in a line" whitestart)
522 (const :tag "Everywhere except in headlines" t)
523 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)
526 (defcustom org-cycle-separator-lines 2
527 "Number of empty lines needed to keep an empty line between collapsed trees.
528 If you leave an empty line between the end of a subtree and the following
529 headline, this empty line is hidden when the subtree is folded.
530 Org-mode will leave (exactly) one empty line visible if the number of
531 empty lines is equal or larger to the number given in this variable.
532 So the default 2 means, at least 2 empty lines after the end of a subtree
533 are needed to produce free space between a collapsed subtree and the
534 following headline.
536 Special case: when 0, never leave empty lines in collapsed view."
537 :group 'org-cycle
538 :type 'integer)
540 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
541 org-cycle-hide-drawers
542 org-cycle-show-empty-lines
543 org-optimize-window-after-visibility-change)
544 "Hook that is run after `org-cycle' has changed the buffer visibility.
545 The function(s) in this hook must accept a single argument which indicates
546 the new state that was set by the most recent `org-cycle' command. The
547 argument is a symbol. After a global state change, it can have the values
548 `overview', `content', or `all'. After a local state change, it can have
549 the values `folded', `children', or `subtree'."
550 :group 'org-cycle
551 :type 'hook)
553 (defgroup org-edit-structure nil
554 "Options concerning structure editing in Org-mode."
555 :tag "Org Edit Structure"
556 :group 'org-structure)
558 (defcustom org-odd-levels-only nil
559 "Non-nil means, skip even levels and only use odd levels for the outline.
560 This has the effect that two stars are being added/taken away in
561 promotion/demotion commands. It also influences how levels are
562 handled by the exporters.
563 Changing it requires restart of `font-lock-mode' to become effective
564 for fontification also in regions already fontified.
565 You may also set this on a per-file basis by adding one of the following
566 lines to the buffer:
568 #+STARTUP: odd
569 #+STARTUP: oddeven"
570 :group 'org-edit-structure
571 :group 'org-font-lock
572 :type 'boolean)
574 (defcustom org-adapt-indentation t
575 "Non-nil means, adapt indentation when promoting and demoting.
576 When this is set and the *entire* text in an entry is indented, the
577 indentation is increased by one space in a demotion command, and
578 decreased by one in a promotion command. If any line in the entry
579 body starts at column 0, indentation is not changed at all."
580 :group 'org-edit-structure
581 :type 'boolean)
583 (defcustom org-special-ctrl-a/e nil
584 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
585 When t, `C-a' will bring back the cursor to the beginning of the
586 headline text, i.e. after the stars and after a possible TODO keyword.
587 In an item, this will be the position after the bullet.
588 When the cursor is already at that position, another `C-a' will bring
589 it to the beginning of the line.
590 `C-e' will jump to the end of the headline, ignoring the presence of tags
591 in the headline. A second `C-e' will then jump to the true end of the
592 line, after any tags.
593 When set to the symbol `reversed', the first `C-a' or `C-e' works normally,
594 and only a directly following, identical keypress will bring the cursor
595 to the special positions."
596 :group 'org-edit-structure
597 :type '(choice
598 (const :tag "off" nil)
599 (const :tag "after bullet first" t)
600 (const :tag "border first" reversed)))
602 (if (fboundp 'defvaralias)
603 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e))
605 (defcustom org-special-ctrl-k nil
606 "Non-nil means `C-k' will behave specially in headlines.
607 When nil, `C-k' will call the default `kill-line' command.
608 When t, the following will happen while the cursor is in the headline:
610 - When the cursor is at the beginning of a headline, kill the entire
611 line and possible the folded subtree below the line.
612 - When in the middle of the headline text, kill the headline up to the tags.
613 - When after the headline text, kill the tags."
614 :group 'org-edit-structure
615 :type 'boolean)
617 (defcustom org-M-RET-may-split-line '((default . t))
618 "Non-nil means, M-RET will split the line at the cursor position.
619 When nil, it will go to the end of the line before making a
620 new line.
621 You may also set this option in a different way for different
622 contexts. Valid contexts are:
624 headline when creating a new headline
625 item when creating a new item
626 table in a table field
627 default the value to be used for all contexts not explicitly
628 customized"
629 :group 'org-structure
630 :group 'org-table
631 :type '(choice
632 (const :tag "Always" t)
633 (const :tag "Never" nil)
634 (repeat :greedy t :tag "Individual contexts"
635 (cons
636 (choice :tag "Context"
637 (const headline)
638 (const item)
639 (const table)
640 (const default))
641 (boolean)))))
644 (defcustom org-blank-before-new-entry '((heading . nil)
645 (plain-list-item . nil))
646 "Should `org-insert-heading' leave a blank line before new heading/item?
647 The value is an alist, with `heading' and `plain-list-item' as car,
648 and a boolean flag as cdr."
649 :group 'org-edit-structure
650 :type '(list
651 (cons (const heading) (boolean))
652 (cons (const plain-list-item) (boolean))))
654 (defcustom org-insert-heading-hook nil
655 "Hook being run after inserting a new heading."
656 :group 'org-edit-structure
657 :type 'hook)
659 (defcustom org-enable-fixed-width-editor t
660 "Non-nil means, lines starting with \":\" are treated as fixed-width.
661 This currently only means, they are never auto-wrapped.
662 When nil, such lines will be treated like ordinary lines.
663 See also the QUOTE keyword."
664 :group 'org-edit-structure
665 :type 'boolean)
667 (defcustom org-goto-auto-isearch t
668 "Non-nil means, typing characters in org-goto starts incremental search."
669 :group 'org-edit-structure
670 :type 'boolean)
672 (defgroup org-sparse-trees nil
673 "Options concerning sparse trees in Org-mode."
674 :tag "Org Sparse Trees"
675 :group 'org-structure)
677 (defcustom org-highlight-sparse-tree-matches t
678 "Non-nil means, highlight all matches that define a sparse tree.
679 The highlights will automatically disappear the next time the buffer is
680 changed by an edit command."
681 :group 'org-sparse-trees
682 :type 'boolean)
684 (defcustom org-remove-highlights-with-change t
685 "Non-nil means, any change to the buffer will remove temporary highlights.
686 Such highlights are created by `org-occur' and `org-clock-display'.
687 When nil, `C-c C-c needs to be used to get rid of the highlights.
688 The highlights created by `org-preview-latex-fragment' always need
689 `C-c C-c' to be removed."
690 :group 'org-sparse-trees
691 :group 'org-time
692 :type 'boolean)
695 (defcustom org-occur-hook '(org-first-headline-recenter)
696 "Hook that is run after `org-occur' has constructed a sparse tree.
697 This can be used to recenter the window to show as much of the structure
698 as possible."
699 :group 'org-sparse-trees
700 :type 'hook)
702 (defgroup org-plain-lists nil
703 "Options concerning plain lists in Org-mode."
704 :tag "Org Plain lists"
705 :group 'org-structure)
707 (defcustom org-cycle-include-plain-lists nil
708 "Non-nil means, include plain lists into visibility cycling.
709 This means that during cycling, plain list items will *temporarily* be
710 interpreted as outline headlines with a level given by 1000+i where i is the
711 indentation of the bullet. In all other operations, plain list items are
712 not seen as headlines. For example, you cannot assign a TODO keyword to
713 such an item."
714 :group 'org-plain-lists
715 :type 'boolean)
717 (defcustom org-plain-list-ordered-item-terminator t
718 "The character that makes a line with leading number an ordered list item.
719 Valid values are ?. and ?\). To get both terminators, use t. While
720 ?. may look nicer, it creates the danger that a line with leading
721 number may be incorrectly interpreted as an item. ?\) therefore is
722 the safe choice."
723 :group 'org-plain-lists
724 :type '(choice (const :tag "dot like in \"2.\"" ?.)
725 (const :tag "paren like in \"2)\"" ?\))
726 (const :tab "both" t)))
728 (defcustom org-empty-line-terminates-plain-lists nil
729 "Non-nil means, an empty line ends all plain list levels.
730 When nil, empty lines are part of the preceeding item."
731 :group 'org-plain-lists
732 :type 'boolean)
734 (defcustom org-auto-renumber-ordered-lists t
735 "Non-nil means, automatically renumber ordered plain lists.
736 Renumbering happens when the sequence have been changed with
737 \\[org-shiftmetaup] or \\[org-shiftmetadown]. After other editing commands,
738 use \\[org-ctrl-c-ctrl-c] to trigger renumbering."
739 :group 'org-plain-lists
740 :type 'boolean)
742 (defcustom org-provide-checkbox-statistics t
743 "Non-nil means, update checkbox statistics after insert and toggle.
744 When this is set, checkbox statistics is updated each time you either insert
745 a new checkbox with \\[org-insert-todo-heading] or toggle a checkbox
746 with \\[org-ctrl-c-ctrl-c\\]."
747 :group 'org-plain-lists
748 :type 'boolean)
751 (defgroup org-imenu-and-speedbar nil
752 "Options concerning imenu and speedbar in Org-mode."
753 :tag "Org Imenu and Speedbar"
754 :group 'org-structure)
756 (defcustom org-imenu-depth 2
757 "The maximum level for Imenu access to Org-mode headlines.
758 This also applied for speedbar access."
759 :group 'org-imenu-and-speedbar
760 :type 'number)
762 (defgroup org-table nil
763 "Options concerning tables in Org-mode."
764 :tag "Org Table"
765 :group 'org)
767 (defcustom org-enable-table-editor 'optimized
768 "Non-nil means, lines starting with \"|\" are handled by the table editor.
769 When nil, such lines will be treated like ordinary lines.
771 When equal to the symbol `optimized', the table editor will be optimized to
772 do the following:
773 - Automatic overwrite mode in front of whitespace in table fields.
774 This makes the structure of the table stay in tact as long as the edited
775 field does not exceed the column width.
776 - Minimize the number of realigns. Normally, the table is aligned each time
777 TAB or RET are pressed to move to another field. With optimization this
778 happens only if changes to a field might have changed the column width.
779 Optimization requires replacing the functions `self-insert-command',
780 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
781 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
782 very good at guessing when a re-align will be necessary, but you can always
783 force one with \\[org-ctrl-c-ctrl-c].
785 If you would like to use the optimized version in Org-mode, but the
786 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
788 This variable can be used to turn on and off the table editor during a session,
789 but in order to toggle optimization, a restart is required.
791 See also the variable `org-table-auto-blank-field'."
792 :group 'org-table
793 :type '(choice
794 (const :tag "off" nil)
795 (const :tag "on" t)
796 (const :tag "on, optimized" optimized)))
798 (defcustom org-table-tab-recognizes-table.el t
799 "Non-nil means, TAB will automatically notice a table.el table.
800 When it sees such a table, it moves point into it and - if necessary -
801 calls `table-recognize-table'."
802 :group 'org-table-editing
803 :type 'boolean)
805 (defgroup org-link nil
806 "Options concerning links in Org-mode."
807 :tag "Org Link"
808 :group 'org)
810 (defvar org-link-abbrev-alist-local nil
811 "Buffer-local version of `org-link-abbrev-alist', which see.
812 The value of this is taken from the #+LINK lines.")
813 (make-variable-buffer-local 'org-link-abbrev-alist-local)
815 (defcustom org-link-abbrev-alist nil
816 "Alist of link abbreviations.
817 The car of each element is a string, to be replaced at the start of a link.
818 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
819 links in Org-mode buffers can have an optional tag after a double colon, e.g.
821 [[linkkey:tag][description]]
823 If REPLACE is a string, the tag will simply be appended to create the link.
824 If the string contains \"%s\", the tag will be inserted there.
826 REPLACE may also be a function that will be called with the tag as the
827 only argument to create the link, which should be returned as a string.
829 See the manual for examples."
830 :group 'org-link
831 :type 'alist)
833 (defcustom org-descriptive-links t
834 "Non-nil means, hide link part and only show description of bracket links.
835 Bracket links are like [[link][descritpion]]. This variable sets the initial
836 state in new org-mode buffers. The setting can then be toggled on a
837 per-buffer basis from the Org->Hyperlinks menu."
838 :group 'org-link
839 :type 'boolean)
841 (defcustom org-link-file-path-type 'adaptive
842 "How the path name in file links should be stored.
843 Valid values are:
845 relative Relative to the current directory, i.e. the directory of the file
846 into which the link is being inserted.
847 absolute Absolute path, if possible with ~ for home directory.
848 noabbrev Absolute path, no abbreviation of home directory.
849 adaptive Use relative path for files in the current directory and sub-
850 directories of it. For other files, use an absolute path."
851 :group 'org-link
852 :type '(choice
853 (const relative)
854 (const absolute)
855 (const noabbrev)
856 (const adaptive)))
858 (defcustom org-activate-links '(bracket angle plain radio tag date)
859 "Types of links that should be activated in Org-mode files.
860 This is a list of symbols, each leading to the activation of a certain link
861 type. In principle, it does not hurt to turn on most link types - there may
862 be a small gain when turning off unused link types. The types are:
864 bracket The recommended [[link][description]] or [[link]] links with hiding.
865 angular Links in angular brackes that may contain whitespace like
866 <bbdb:Carsten Dominik>.
867 plain Plain links in normal text, no whitespace, like http://google.com.
868 radio Text that is matched by a radio target, see manual for details.
869 tag Tag settings in a headline (link to tag search).
870 date Time stamps (link to calendar).
872 Changing this variable requires a restart of Emacs to become effective."
873 :group 'org-link
874 :type '(set (const :tag "Double bracket links (new style)" bracket)
875 (const :tag "Angular bracket links (old style)" angular)
876 (const :tag "Plain text links" plain)
877 (const :tag "Radio target matches" radio)
878 (const :tag "Tags" tag)
879 (const :tag "Timestamps" date)))
881 (defcustom org-make-link-description-function nil
882 "Function to use to generate link descriptions from links. If
883 nil the link location will be used. This function must take two
884 parameters; the first is the link and the second the description
885 org-insert-link has generated, and should return the description
886 to use."
887 :group 'org-link
888 :type 'function)
890 (defgroup org-link-store nil
891 "Options concerning storing links in Org-mode."
892 :tag "Org Store Link"
893 :group 'org-link)
895 (defcustom org-email-link-description-format "Email %c: %.30s"
896 "Format of the description part of a link to an email or usenet message.
897 The following %-excapes will be replaced by corresponding information:
899 %F full \"From\" field
900 %f name, taken from \"From\" field, address if no name
901 %T full \"To\" field
902 %t first name in \"To\" field, address if no name
903 %c correspondent. Unually \"from NAME\", but if you sent it yourself, it
904 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
905 %s subject
906 %m message-id.
908 You may use normal field width specification between the % and the letter.
909 This is for example useful to limit the length of the subject.
911 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
912 :group 'org-link-store
913 :type 'string)
915 (defcustom org-from-is-user-regexp
916 (let (r1 r2)
917 (when (and user-mail-address (not (string= user-mail-address "")))
918 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
919 (when (and user-full-name (not (string= user-full-name "")))
920 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
921 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
922 "Regexp mached against the \"From:\" header of an email or usenet message.
923 It should match if the message is from the user him/herself."
924 :group 'org-link-store
925 :type 'regexp)
927 (defcustom org-context-in-file-links t
928 "Non-nil means, file links from `org-store-link' contain context.
929 A search string will be added to the file name with :: as separator and
930 used to find the context when the link is activated by the command
931 `org-open-at-point'.
932 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
933 negates this setting for the duration of the command."
934 :group 'org-link-store
935 :type 'boolean)
937 (defcustom org-keep-stored-link-after-insertion nil
938 "Non-nil means, keep link in list for entire session.
940 The command `org-store-link' adds a link pointing to the current
941 location to an internal list. These links accumulate during a session.
942 The command `org-insert-link' can be used to insert links into any
943 Org-mode file (offering completion for all stored links). When this
944 option is nil, every link which has been inserted once using \\[org-insert-link]
945 will be removed from the list, to make completing the unused links
946 more efficient."
947 :group 'org-link-store
948 :type 'boolean)
950 (defgroup org-link-follow nil
951 "Options concerning following links in Org-mode."
952 :tag "Org Follow Link"
953 :group 'org-link)
955 (defcustom org-follow-link-hook nil
956 "Hook that is run after a link has been followed."
957 :group 'org-link-follow
958 :type 'hook)
960 (defcustom org-tab-follows-link nil
961 "Non-nil means, on links TAB will follow the link.
962 Needs to be set before org.el is loaded."
963 :group 'org-link-follow
964 :type 'boolean)
966 (defcustom org-return-follows-link nil
967 "Non-nil means, on links RET will follow the link.
968 Needs to be set before org.el is loaded."
969 :group 'org-link-follow
970 :type 'boolean)
972 (defcustom org-mouse-1-follows-link
973 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
974 "Non-nil means, mouse-1 on a link will follow the link.
975 A longer mouse click will still set point. Does not work on XEmacs.
976 Needs to be set before org.el is loaded."
977 :group 'org-link-follow
978 :type 'boolean)
980 (defcustom org-mark-ring-length 4
981 "Number of different positions to be recorded in the ring
982 Changing this requires a restart of Emacs to work correctly."
983 :group 'org-link-follow
984 :type 'interger)
986 (defcustom org-link-frame-setup
987 '((vm . vm-visit-folder-other-frame)
988 (gnus . gnus-other-frame)
989 (file . find-file-other-window))
990 "Setup the frame configuration for following links.
991 When following a link with Emacs, it may often be useful to display
992 this link in another window or frame. This variable can be used to
993 set this up for the different types of links.
994 For VM, use any of
995 `vm-visit-folder'
996 `vm-visit-folder-other-frame'
997 For Gnus, use any of
998 `gnus'
999 `gnus-other-frame'
1000 For FILE, use any of
1001 `find-file'
1002 `find-file-other-window'
1003 `find-file-other-frame'
1004 For the calendar, use the variable `calendar-setup'.
1005 For BBDB, it is currently only possible to display the matches in
1006 another window."
1007 :group 'org-link-follow
1008 :type '(list
1009 (cons (const vm)
1010 (choice
1011 (const vm-visit-folder)
1012 (const vm-visit-folder-other-window)
1013 (const vm-visit-folder-other-frame)))
1014 (cons (const gnus)
1015 (choice
1016 (const gnus)
1017 (const gnus-other-frame)))
1018 (cons (const file)
1019 (choice
1020 (const find-file)
1021 (const find-file-other-window)
1022 (const find-file-other-frame)))))
1024 (defcustom org-display-internal-link-with-indirect-buffer nil
1025 "Non-nil means, use indirect buffer to display infile links.
1026 Activating internal links (from one location in a file to another location
1027 in the same file) normally just jumps to the location. When the link is
1028 activated with a C-u prefix (or with mouse-3), the link is displayed in
1029 another window. When this option is set, the other window actually displays
1030 an indirect buffer clone of the current buffer, to avoid any visibility
1031 changes to the current buffer."
1032 :group 'org-link-follow
1033 :type 'boolean)
1035 (defcustom org-open-non-existing-files nil
1036 "Non-nil means, `org-open-file' will open non-existing files.
1037 When nil, an error will be generated."
1038 :group 'org-link-follow
1039 :type 'boolean)
1041 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1042 "Function and arguments to call for following mailto links.
1043 This is a list with the first element being a lisp function, and the
1044 remaining elements being arguments to the function. In string arguments,
1045 %a will be replaced by the address, and %s will be replaced by the subject
1046 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1047 :group 'org-link-follow
1048 :type '(choice
1049 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1050 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1051 (const :tag "message-mail" (message-mail "%a" "%s"))
1052 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1054 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1055 "Non-nil means, ask for confirmation before executing shell links.
1056 Shell links can be dangerous: just think about a link
1058 [[shell:rm -rf ~/*][Google Search]]
1060 This link would show up in your Org-mode document as \"Google Search\",
1061 but really it would remove your entire home directory.
1062 Therefore we advise against setting this variable to nil.
1063 Just change it to `y-or-n-p' of you want to confirm with a
1064 single keystroke rather than having to type \"yes\"."
1065 :group 'org-link-follow
1066 :type '(choice
1067 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1068 (const :tag "with y-or-n (faster)" y-or-n-p)
1069 (const :tag "no confirmation (dangerous)" nil)))
1071 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1072 "Non-nil means, ask for confirmation before executing Emacs Lisp links.
1073 Elisp links can be dangerous: just think about a link
1075 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1077 This link would show up in your Org-mode document as \"Google Search\",
1078 but really it would remove your entire home directory.
1079 Therefore we advise against setting this variable to nil.
1080 Just change it to `y-or-n-p' of you want to confirm with a
1081 single keystroke rather than having to type \"yes\"."
1082 :group 'org-link-follow
1083 :type '(choice
1084 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1085 (const :tag "with y-or-n (faster)" y-or-n-p)
1086 (const :tag "no confirmation (dangerous)" nil)))
1088 (defconst org-file-apps-defaults-gnu
1089 '((remote . emacs)
1090 (t . mailcap))
1091 "Default file applications on a UNIX or GNU/Linux system.
1092 See `org-file-apps'.")
1094 (defconst org-file-apps-defaults-macosx
1095 '((remote . emacs)
1096 (t . "open %s")
1097 ("ps" . "gv %s")
1098 ("ps.gz" . "gv %s")
1099 ("eps" . "gv %s")
1100 ("eps.gz" . "gv %s")
1101 ("dvi" . "xdvi %s")
1102 ("fig" . "xfig %s"))
1103 "Default file applications on a MacOS X system.
1104 The system \"open\" is known as a default, but we use X11 applications
1105 for some files for which the OS does not have a good default.
1106 See `org-file-apps'.")
1108 (defconst org-file-apps-defaults-windowsnt
1109 (list
1110 '(remote . emacs)
1111 (cons t
1112 (list (if (featurep 'xemacs)
1113 'mswindows-shell-execute
1114 'w32-shell-execute)
1115 "open" 'file)))
1116 "Default file applications on a Windows NT system.
1117 The system \"open\" is used for most files.
1118 See `org-file-apps'.")
1120 (defcustom org-file-apps
1122 ("txt" . emacs)
1123 ("tex" . emacs)
1124 ("ltx" . emacs)
1125 ("org" . emacs)
1126 ("el" . emacs)
1127 ("bib" . emacs)
1129 "External applications for opening `file:path' items in a document.
1130 Org-mode uses system defaults for different file types, but
1131 you can use this variable to set the application for a given file
1132 extension. The entries in this list are cons cells where the car identifies
1133 files and the cdr the corresponding command. Possible values for the
1134 file identifier are
1135 \"ext\" A string identifying an extension
1136 `directory' Matches a directory
1137 `remote' Matches a remote file, accessible through tramp or efs.
1138 Remote files most likely should be visited through Emacs
1139 because external applications cannot handle such paths.
1140 t Default for all remaining files
1142 Possible values for the command are:
1143 `emacs' The file will be visited by the current Emacs process.
1144 `default' Use the default application for this file type.
1145 string A command to be executed by a shell; %s will be replaced
1146 by the path to the file.
1147 sexp A Lisp form which will be evaluated. The file path will
1148 be available in the Lisp variable `file'.
1149 For more examples, see the system specific constants
1150 `org-file-apps-defaults-macosx'
1151 `org-file-apps-defaults-windowsnt'
1152 `org-file-apps-defaults-gnu'."
1153 :group 'org-link-follow
1154 :type '(repeat
1155 (cons (choice :value ""
1156 (string :tag "Extension")
1157 (const :tag "Default for unrecognized files" t)
1158 (const :tag "Remote file" remote)
1159 (const :tag "Links to a directory" directory))
1160 (choice :value ""
1161 (const :tag "Visit with Emacs" emacs)
1162 (const :tag "Use system default" default)
1163 (string :tag "Command")
1164 (sexp :tag "Lisp form")))))
1166 (defgroup org-refile nil
1167 "Options concerning refiling entries in Org-mode."
1168 :tag "Org Remember"
1169 :group 'org)
1171 (defcustom org-directory "~/org"
1172 "Directory with org files.
1173 This directory will be used as default to prompt for org files.
1174 Used by the hooks for remember.el."
1175 :group 'org-refile
1176 :group 'org-remember
1177 :type 'directory)
1179 (defcustom org-default-notes-file "~/.notes"
1180 "Default target for storing notes.
1181 Used by the hooks for remember.el. This can be a string, or nil to mean
1182 the value of `remember-data-file'.
1183 You can set this on a per-template basis with the variable
1184 `org-remember-templates'."
1185 :group 'org-refile
1186 :group 'org-remember
1187 :type '(choice
1188 (const :tag "Default from remember-data-file" nil)
1189 file))
1191 (defcustom org-goto-interface 'outline
1192 "The default interface to be used for `org-goto'.
1193 Allowed vaues are:
1194 outline The interface shows an outline of the relevant file
1195 and the correct heading is found by moving through
1196 the outline or by searching with incremental search.
1197 outline-path-completion Headlines in the current buffer are offered via
1198 completion."
1199 :group 'org-refile
1200 :type '(choice
1201 (const :tag "Outline" outline)
1202 (const :tag "Outline-path-completion" outline-path-completion)))
1204 (defcustom org-reverse-note-order nil
1205 "Non-nil means, store new notes at the beginning of a file or entry.
1206 When nil, new notes will be filed to the end of a file or entry.
1207 This can also be a list with cons cells of regular expressions that
1208 are matched against file names, and values."
1209 :group 'org-remember
1210 :type '(choice
1211 (const :tag "Reverse always" t)
1212 (const :tag "Reverse never" nil)
1213 (repeat :tag "By file name regexp"
1214 (cons regexp boolean))))
1216 (defcustom org-refile-targets nil
1217 "Targets for refiling entries with \\[org-refile].
1218 This is list of cons cells. Each cell contains:
1219 - a specification of the files to be considered, either a list of files,
1220 or a symbol whose function or variable value will be used to retrieve
1221 a file name or a list of file names. Nil means, refile to a different
1222 heading in the current buffer.
1223 - A specification of how to find candidate refile targets. This may be
1224 any of
1225 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
1226 This tag has to be present in all target headlines, inheritance will
1227 not be considered.
1228 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
1229 todo keyword.
1230 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1231 headlines that are refiling targets.
1232 - a cons cell (:level . N). Any headline of level N is considered a target.
1233 - a cons cell (:maxlevel . N). Any headline with level <= N is a target."
1234 :group 'org-remember
1235 :type '(repeat
1236 (cons
1237 (choice :value org-agenda-files
1238 (const :tag "All agenda files" org-agenda-files)
1239 (const :tag "Current buffer" nil)
1240 (function) (variable) (file))
1241 (choice :tag "Identify target headline by"
1242 (cons :tag "Specific tag" (const :tag) (string))
1243 (cons :tag "TODO keyword" (const :todo) (string))
1244 (cons :tag "Regular expression" (const :regexp) (regexp))
1245 (cons :tag "Level number" (const :level) (integer))
1246 (cons :tag "Max Level number" (const :maxlevel) (integer))))))
1248 (defcustom org-refile-use-outline-path nil
1249 "Non-nil means, provide refile targets as paths.
1250 So a level 3 headline will be available as level1/level2/level3.
1251 When the value is `file', also include the file name (without directory)
1252 into the path. When `full-file-path', include the full file path."
1253 :group 'org-remember
1254 :type '(choice
1255 (const :tag "Not" nil)
1256 (const :tag "Yes" t)
1257 (const :tag "Start with file name" file)
1258 (const :tag "Start with full file path" full-file-path)))
1260 (defgroup org-todo nil
1261 "Options concerning TODO items in Org-mode."
1262 :tag "Org TODO"
1263 :group 'org)
1265 (defgroup org-progress nil
1266 "Options concerning Progress logging in Org-mode."
1267 :tag "Org Progress"
1268 :group 'org-time)
1270 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
1271 "List of TODO entry keyword sequences and their interpretation.
1272 \\<org-mode-map>This is a list of sequences.
1274 Each sequence starts with a symbol, either `sequence' or `type',
1275 indicating if the keywords should be interpreted as a sequence of
1276 action steps, or as different types of TODO items. The first
1277 keywords are states requiring action - these states will select a headline
1278 for inclusion into the global TODO list Org-mode produces. If one of
1279 the \"keywords\" is the vertical bat \"|\" the remaining keywords
1280 signify that no further action is necessary. If \"|\" is not found,
1281 the last keyword is treated as the only DONE state of the sequence.
1283 The command \\[org-todo] cycles an entry through these states, and one
1284 additional state where no keyword is present. For details about this
1285 cycling, see the manual.
1287 TODO keywords and interpretation can also be set on a per-file basis with
1288 the special #+SEQ_TODO and #+TYP_TODO lines.
1290 Each keyword can optionally specify a character for fast state selection
1291 \(in combination with the variable `org-use-fast-todo-selection')
1292 and specifiers for state change logging, using the same syntax
1293 that is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says
1294 that the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
1295 indicates to record a time stamp each time this state is selected.
1297 Each keyword may also specify if a timestamp or a note should be
1298 recorded when entering or leaving the state, by adding additional
1299 characters in the parenthesis after the keyword. This looks like this:
1300 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
1301 record only the time of the state change. With X and Y being either
1302 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
1303 Y when leaving the state if and only if the *target* state does not
1304 define X. You may omit any of the fast-selection key or X or /Y,
1305 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
1307 For backward compatibility, this variable may also be just a list
1308 of keywords - in this case the interptetation (sequence or type) will be
1309 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
1310 :group 'org-todo
1311 :group 'org-keywords
1312 :type '(choice
1313 (repeat :tag "Old syntax, just keywords"
1314 (string :tag "Keyword"))
1315 (repeat :tag "New syntax"
1316 (cons
1317 (choice
1318 :tag "Interpretation"
1319 (const :tag "Sequence (cycling hits every state)" sequence)
1320 (const :tag "Type (cycling directly to DONE)" type))
1321 (repeat
1322 (string :tag "Keyword"))))))
1324 (defvar org-todo-keywords-1 nil
1325 "All TODO and DONE keywords active in a buffer.")
1326 (make-variable-buffer-local 'org-todo-keywords-1)
1327 (defvar org-todo-keywords-for-agenda nil)
1328 (defvar org-done-keywords-for-agenda nil)
1329 (defvar org-agenda-contributing-files nil)
1330 (defvar org-not-done-keywords nil)
1331 (make-variable-buffer-local 'org-not-done-keywords)
1332 (defvar org-done-keywords nil)
1333 (make-variable-buffer-local 'org-done-keywords)
1334 (defvar org-todo-heads nil)
1335 (make-variable-buffer-local 'org-todo-heads)
1336 (defvar org-todo-sets nil)
1337 (make-variable-buffer-local 'org-todo-sets)
1338 (defvar org-todo-log-states nil)
1339 (make-variable-buffer-local 'org-todo-log-states)
1340 (defvar org-todo-kwd-alist nil)
1341 (make-variable-buffer-local 'org-todo-kwd-alist)
1342 (defvar org-todo-key-alist nil)
1343 (make-variable-buffer-local 'org-todo-key-alist)
1344 (defvar org-todo-key-trigger nil)
1345 (make-variable-buffer-local 'org-todo-key-trigger)
1347 (defcustom org-todo-interpretation 'sequence
1348 "Controls how TODO keywords are interpreted.
1349 This variable is in principle obsolete and is only used for
1350 backward compatibility, if the interpretation of todo keywords is
1351 not given already in `org-todo-keywords'. See that variable for
1352 more information."
1353 :group 'org-todo
1354 :group 'org-keywords
1355 :type '(choice (const sequence)
1356 (const type)))
1358 (defcustom org-use-fast-todo-selection 'prefix
1359 "Non-nil means, use the fast todo selection scheme with C-c C-t.
1360 This variable describes if and under what circumstances the cycling
1361 mechanism for TODO keywords will be replaced by a single-key, direct
1362 selection scheme.
1364 When nil, fast selection is never used.
1366 When the symbol `prefix', it will be used when `org-todo' is called with
1367 a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and `C-u t'
1368 in an agenda buffer.
1370 When t, fast selection is used by default. In this case, the prefix
1371 argument forces cycling instead.
1373 In all cases, the special interface is only used if access keys have actually
1374 been assigned by the user, i.e. if keywords in the configuration are followed
1375 by a letter in parenthesis, like TODO(t)."
1376 :group 'org-todo
1377 :type '(choice
1378 (const :tag "Never" nil)
1379 (const :tag "By default" t)
1380 (const :tag "Only with C-u C-c C-t" prefix)))
1382 (defcustom org-after-todo-state-change-hook nil
1383 "Hook which is run after the state of a TODO item was changed.
1384 The new state (a string with a TODO keyword, or nil) is available in the
1385 Lisp variable `state'."
1386 :group 'org-todo
1387 :type 'hook)
1389 (defcustom org-log-done nil
1390 "Non-nil means, record a CLOSED timestamp when moving an entry to DONE.
1391 When equal to the list (done), also prompt for a closing note.
1392 This can also be configured on a per-file basis by adding one of
1393 the following lines anywhere in the buffer:
1395 #+STARTUP: logdone
1396 #+STARTUP: lognotedone
1397 #+STARTUP: nologdone"
1398 :group 'org-todo
1399 :group 'org-progress
1400 :type '(choice
1401 (const :tag "No logging" nil)
1402 (const :tag "Record CLOSED timestamp" time)
1403 (const :tag "Record CLOSED timestamp with closing note." note)))
1405 ;; Normalize old uses of org-log-done.
1406 (cond
1407 ((eq org-log-done t) (setq org-log-done 'time))
1408 ((and (listp org-log-done) (memq 'done org-log-done))
1409 (setq org-log-done 'note)))
1411 (defcustom org-log-note-clock-out nil
1412 "Non-nil means, recored a note when clocking out of an item.
1413 This can also be configured on a per-file basis by adding one of
1414 the following lines anywhere in the buffer:
1416 #+STARTUP: lognoteclock-out
1417 #+STARTUP: nolognoteclock-out"
1418 :group 'org-todo
1419 :group 'org-progress
1420 :type 'boolean)
1422 (defcustom org-log-done-with-time t
1423 "Non-nil means, the CLOSED time stamp will contain date and time.
1424 When nil, only the date will be recorded."
1425 :group 'org-progress
1426 :type 'boolean)
1428 (defcustom org-log-note-headings
1429 '((done . "CLOSING NOTE %t")
1430 (state . "State %-12s %t")
1431 (note . "Note taken on %t")
1432 (clock-out . ""))
1433 "Headings for notes added to entries.
1434 The value is an alist, with the car being a symbol indicating the note
1435 context, and the cdr is the heading to be used. The heading may also be the
1436 empty string.
1437 %t in the heading will be replaced by a time stamp.
1438 %s will be replaced by the new TODO state, in double quotes.
1439 %u will be replaced by the user name.
1440 %U will be replaced by the full user name."
1441 :group 'org-todo
1442 :group 'org-progress
1443 :type '(list :greedy t
1444 (cons (const :tag "Heading when closing an item" done) string)
1445 (cons (const :tag
1446 "Heading when changing todo state (todo sequence only)"
1447 state) string)
1448 (cons (const :tag "Heading when just taking a note" note) string)
1449 (cons (const :tag "Heading when clocking out" clock-out) string)))
1451 (unless (assq 'note org-log-note-headings)
1452 (push '(note . "%t") org-log-note-headings))
1454 (defcustom org-log-states-order-reversed t
1455 "Non-nil means, the latest state change note will be directly after heading.
1456 When nil, the notes will be orderer according to time."
1457 :group 'org-todo
1458 :group 'org-progress
1459 :type 'boolean)
1461 (defcustom org-log-repeat 'time
1462 "Non-nil means, record moving through the DONE state when triggering repeat.
1463 An auto-repeating tasks is immediately switched back to TODO when marked
1464 done. If you are not logging state changes (by adding \"@\" or \"!\" to
1465 the TODO keyword definition, or recording a closing note by setting
1466 `org-log-done', there will be no record of the task moving through DONE.
1467 This variable forces taking a note anyway. Possible values are:
1469 nil Don't force a record
1470 time Record a time stamp
1471 note Record a note
1473 This option can also be set with on a per-file-basis with
1475 #+STARTUP: logrepeat
1476 #+STARTUP: lognoterepeat
1477 #+STARTUP: nologrepeat
1479 You can have local logging settings for a subtree by setting the LOGGING
1480 property to one or more of these keywords."
1481 :group 'org-todo
1482 :group 'org-progress
1483 :type '(choice
1484 (const :tag "Don't force a record" nil)
1485 (const :tag "Force recording the DONE state" time)
1486 (const :tag "Force recording a note with the DONE state" note)))
1489 (defgroup org-priorities nil
1490 "Priorities in Org-mode."
1491 :tag "Org Priorities"
1492 :group 'org-todo)
1494 (defcustom org-highest-priority ?A
1495 "The highest priority of TODO items. A character like ?A, ?B etc.
1496 Must have a smaller ASCII number than `org-lowest-priority'."
1497 :group 'org-priorities
1498 :type 'character)
1500 (defcustom org-lowest-priority ?C
1501 "The lowest priority of TODO items. A character like ?A, ?B etc.
1502 Must have a larger ASCII number than `org-highest-priority'."
1503 :group 'org-priorities
1504 :type 'character)
1506 (defcustom org-default-priority ?B
1507 "The default priority of TODO items.
1508 This is the priority an item get if no explicit priority is given."
1509 :group 'org-priorities
1510 :type 'character)
1512 (defcustom org-priority-start-cycle-with-default t
1513 "Non-nil means, start with default priority when starting to cycle.
1514 When this is nil, the first step in the cycle will be (depending on the
1515 command used) one higher or lower that the default priority."
1516 :group 'org-priorities
1517 :type 'boolean)
1519 (defgroup org-time nil
1520 "Options concerning time stamps and deadlines in Org-mode."
1521 :tag "Org Time"
1522 :group 'org)
1524 (defcustom org-insert-labeled-timestamps-at-point nil
1525 "Non-nil means, SCHEDULED and DEADLINE timestamps are inserted at point.
1526 When nil, these labeled time stamps are forces into the second line of an
1527 entry, just after the headline. When scheduling from the global TODO list,
1528 the time stamp will always be forced into the second line."
1529 :group 'org-time
1530 :type 'boolean)
1532 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
1533 "Formats for `format-time-string' which are used for time stamps.
1534 It is not recommended to change this constant.")
1536 (defcustom org-time-stamp-rounding-minutes '(0 5)
1537 "Number of minutes to round time stamps to.
1538 These are two values, the first applies when first creating a time stamp.
1539 The second applies when changing it with the commands `S-up' and `S-down'.
1540 When changing the time stamp, this means that it will change in steps
1541 of N minutes, as given by the second value.
1543 When a setting is 0 or 1, insert the time unmodified. Useful rounding
1544 numbers should be factors of 60, so for example 5, 10, 15.
1546 When this is larger than 1, you can still force an exact time-stamp by using
1547 a double prefix argument to a time-stamp command like `C-c .' or `C-c !',
1548 and by using a prefix arg to `S-up/down' to specify the exact number
1549 of minutes to shift."
1550 :group 'org-time
1551 :get '(lambda (var) ; Make sure all entries have 5 elements
1552 (if (integerp (default-value var))
1553 (list (default-value var) 5)
1554 (default-value var)))
1555 :type '(list
1556 (integer :tag "when inserting times")
1557 (integer :tag "when modifying times")))
1559 ;; Normalize old customizations of this variable.
1560 (when (integerp org-time-stamp-rounding-minutes)
1561 (setq org-time-stamp-rounding-minutes
1562 (list org-time-stamp-rounding-minutes
1563 org-time-stamp-rounding-minutes)))
1565 (defcustom org-display-custom-times nil
1566 "Non-nil means, overlay custom formats over all time stamps.
1567 The formats are defined through the variable `org-time-stamp-custom-formats'.
1568 To turn this on on a per-file basis, insert anywhere in the file:
1569 #+STARTUP: customtime"
1570 :group 'org-time
1571 :set 'set-default
1572 :type 'sexp)
1573 (make-variable-buffer-local 'org-display-custom-times)
1575 (defcustom org-time-stamp-custom-formats
1576 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
1577 "Custom formats for time stamps. See `format-time-string' for the syntax.
1578 These are overlayed over the default ISO format if the variable
1579 `org-display-custom-times' is set. Time like %H:%M should be at the
1580 end of the second format."
1581 :group 'org-time
1582 :type 'sexp)
1584 (defun org-time-stamp-format (&optional long inactive)
1585 "Get the right format for a time string."
1586 (let ((f (if long (cdr org-time-stamp-formats)
1587 (car org-time-stamp-formats))))
1588 (if inactive
1589 (concat "[" (substring f 1 -1) "]")
1590 f)))
1592 (defcustom org-deadline-warning-days 14
1593 "No. of days before expiration during which a deadline becomes active.
1594 This variable governs the display in sparse trees and in the agenda.
1595 When 0 or negative, it means use this number (the absolute value of it)
1596 even if a deadline has a different individual lead time specified."
1597 :group 'org-time
1598 :group 'org-agenda-daily/weekly
1599 :type 'number)
1601 (defcustom org-read-date-prefer-future t
1602 "Non-nil means, assume future for incomplete date input from user.
1603 This affects the following situations:
1604 1. The user gives a day, but no month.
1605 For example, if today is the 15th, and you enter \"3\", Org-mode will
1606 read this as the third of *next* month. However, if you enter \"17\",
1607 it will be considered as *this* month.
1608 2. The user gives a month but not a year.
1609 For example, if it is april and you enter \"feb 2\", this will be read
1610 as feb 2, *next* year. \"May 5\", however, will be this year.
1612 Currently this does not work for ISO week specifications.
1614 When this option is nil, the current month and year will always be used
1615 as defaults."
1616 :group 'org-time
1617 :type 'boolean)
1619 (defcustom org-read-date-display-live t
1620 "Non-nil means, display current interpretation of date prompt live.
1621 This display will be in an overlay, in the minibuffer."
1622 :group 'org-time
1623 :type 'boolean)
1625 (defcustom org-read-date-popup-calendar t
1626 "Non-nil means, pop up a calendar when prompting for a date.
1627 In the calendar, the date can be selected with mouse-1. However, the
1628 minibuffer will also be active, and you can simply enter the date as well.
1629 When nil, only the minibuffer will be available."
1630 :group 'org-time
1631 :type 'boolean)
1632 (if (fboundp 'defvaralias)
1633 (defvaralias 'org-popup-calendar-for-date-prompt
1634 'org-read-date-popup-calendar))
1636 (defcustom org-extend-today-until 0
1637 "The hour when your day really ends.
1638 This has influence for the following applications:
1639 - When switching the agenda to \"today\". It it is still earlier than
1640 the time given here, the day recognized as TODAY is actually yesterday.
1641 - When a date is read from the user and it is still before the time given
1642 here, the current date and time will be assumed to be yesterday, 23:59.
1644 FIXME:
1645 IMPORTANT: This is still a very experimental feature, it may disappear
1646 again or it may be extended to mean more things."
1647 :group 'org-time
1648 :type 'number)
1650 (defcustom org-edit-timestamp-down-means-later nil
1651 "Non-nil means, S-down will increase the time in a time stamp.
1652 When nil, S-up will increase."
1653 :group 'org-time
1654 :type 'boolean)
1656 (defcustom org-calendar-follow-timestamp-change t
1657 "Non-nil means, make the calendar window follow timestamp changes.
1658 When a timestamp is modified and the calendar window is visible, it will be
1659 moved to the new date."
1660 :group 'org-time
1661 :type 'boolean)
1663 (defgroup org-tags nil
1664 "Options concerning tags in Org-mode."
1665 :tag "Org Tags"
1666 :group 'org)
1668 (defcustom org-tag-alist nil
1669 "List of tags allowed in Org-mode files.
1670 When this list is nil, Org-mode will base TAG input on what is already in the
1671 buffer.
1672 The value of this variable is an alist, the car of each entry must be a
1673 keyword as a string, the cdr may be a character that is used to select
1674 that tag through the fast-tag-selection interface.
1675 See the manual for details."
1676 :group 'org-tags
1677 :type '(repeat
1678 (choice
1679 (cons (string :tag "Tag name")
1680 (character :tag "Access char"))
1681 (const :tag "Start radio group" (:startgroup))
1682 (const :tag "End radio group" (:endgroup)))))
1684 (defcustom org-use-fast-tag-selection 'auto
1685 "Non-nil means, use fast tag selection scheme.
1686 This is a special interface to select and deselect tags with single keys.
1687 When nil, fast selection is never used.
1688 When the symbol `auto', fast selection is used if and only if selection
1689 characters for tags have been configured, either through the variable
1690 `org-tag-alist' or through a #+TAGS line in the buffer.
1691 When t, fast selection is always used and selection keys are assigned
1692 automatically if necessary."
1693 :group 'org-tags
1694 :type '(choice
1695 (const :tag "Always" t)
1696 (const :tag "Never" nil)
1697 (const :tag "When selection characters are configured" 'auto)))
1699 (defcustom org-fast-tag-selection-single-key nil
1700 "Non-nil means, fast tag selection exits after first change.
1701 When nil, you have to press RET to exit it.
1702 During fast tag selection, you can toggle this flag with `C-c'.
1703 This variable can also have the value `expert'. In this case, the window
1704 displaying the tags menu is not even shown, until you press C-c again."
1705 :group 'org-tags
1706 :type '(choice
1707 (const :tag "No" nil)
1708 (const :tag "Yes" t)
1709 (const :tag "Expert" expert)))
1711 (defvar org-fast-tag-selection-include-todo nil
1712 "Non-nil means, fast tags selection interface will also offer TODO states.
1713 This is an undocumented feature, you should not rely on it.")
1715 (defcustom org-tags-column (if (featurep 'xemacs) -79 -80)
1716 "The column to which tags should be indented in a headline.
1717 If this number is positive, it specifies the column. If it is negative,
1718 it means that the tags should be flushright to that column. For example,
1719 -80 works well for a normal 80 character screen."
1720 :group 'org-tags
1721 :type 'integer)
1723 (defcustom org-auto-align-tags t
1724 "Non-nil means, realign tags after pro/demotion of TODO state change.
1725 These operations change the length of a headline and therefore shift
1726 the tags around. With this options turned on, after each such operation
1727 the tags are again aligned to `org-tags-column'."
1728 :group 'org-tags
1729 :type 'boolean)
1731 (defcustom org-use-tag-inheritance t
1732 "Non-nil means, tags in levels apply also for sublevels.
1733 When nil, only the tags directly given in a specific line apply there.
1734 If you turn off this option, you very likely want to turn on the
1735 companion option `org-tags-match-list-sublevels'.
1737 This may also be a list of tags that should be inherited, or a regexp that
1738 matches tags that should be inherited."
1739 :group 'org-tags
1740 :type '(choice
1741 (const :tag "Not" nil)
1742 (const :tag "Always" t)
1743 (repeat :tag "Specific tags" (string :tag "Tag"))
1744 (regexp :tag "Tags matched by regexp")))
1746 (defun org-tag-inherit-p (tag)
1747 "Check if TAG is one that should be inherited."
1748 (cond
1749 ((eq org-use-tag-inheritance t) t)
1750 ((not org-use-tag-inheritance) nil)
1751 ((stringp org-use-tag-inheritance)
1752 (string-match org-use-tag-inheritance tag))
1753 ((listp org-use-tag-inheritance)
1754 (member tag org-use-tag-inheritance))
1755 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
1757 (defcustom org-tags-match-list-sublevels nil
1758 "Non-nil means list also sublevels of headlines matching tag search.
1759 Because of tag inheritance (see variable `org-use-tag-inheritance'),
1760 the sublevels of a headline matching a tag search often also match
1761 the same search. Listing all of them can create very long lists.
1762 Setting this variable to nil causes subtrees of a match to be skipped.
1763 This option is off by default, because inheritance in on. If you turn
1764 inheritance off, you very likely want to turn this option on.
1766 As a special case, if the tag search is restricted to TODO items, the
1767 value of this variable is ignored and sublevels are always checked, to
1768 make sure all corresponding TODO items find their way into the list."
1769 :group 'org-tags
1770 :type 'boolean)
1772 (defvar org-tags-history nil
1773 "History of minibuffer reads for tags.")
1774 (defvar org-last-tags-completion-table nil
1775 "The last used completion table for tags.")
1776 (defvar org-after-tags-change-hook nil
1777 "Hook that is run after the tags in a line have changed.")
1779 (defgroup org-properties nil
1780 "Options concerning properties in Org-mode."
1781 :tag "Org Properties"
1782 :group 'org)
1784 (defcustom org-property-format "%-10s %s"
1785 "How property key/value pairs should be formatted by `indent-line'.
1786 When `indent-line' hits a property definition, it will format the line
1787 according to this format, mainly to make sure that the values are
1788 lined-up with respect to each other."
1789 :group 'org-properties
1790 :type 'string)
1792 (defcustom org-use-property-inheritance nil
1793 "Non-nil means, properties apply also for sublevels.
1795 This setting is chiefly used during property searches. Turning it on can
1796 cause significant overhead when doing a search, which is why it is not
1797 on by default.
1799 When nil, only the properties directly given in the current entry count.
1800 When t, every property is inherited. The value may also be a list of
1801 properties that should have inheritance, or a regular expression matching
1802 properties that should be inherited.
1804 However, note that some special properties use inheritance under special
1805 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
1806 and the properties ending in \"_ALL\" when they are used as descriptor
1807 for valid values of a property.
1809 Note for programmers:
1810 When querying an entry with `org-entry-get', you can control if inheritance
1811 should be used. By default, `org-entry-get' looks only at the local
1812 properties. You can request inheritance by setting the inherit argument
1813 to t (to force inheritance) or to `selective' (to respect the setting
1814 in this variable)."
1815 :group 'org-properties
1816 :type '(choice
1817 (const :tag "Not" nil)
1818 (const :tag "Always" t)
1819 (repeat :tag "Specific properties" (string :tag "Property"))
1820 (regexp :tag "Properties matched by regexp")))
1822 (defun org-property-inherit-p (property)
1823 "Check if PROPERTY is one that should be inherited."
1824 (cond
1825 ((eq org-use-property-inheritance t) t)
1826 ((not org-use-property-inheritance) nil)
1827 ((stringp org-use-property-inheritance)
1828 (string-match org-use-property-inheritance property))
1829 ((listp org-use-property-inheritance)
1830 (member property org-use-property-inheritance))
1831 (t (error "Invalid setting of `org-use-property-inheritance'"))))
1833 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
1834 "The default column format, if no other format has been defined.
1835 This variable can be set on the per-file basis by inserting a line
1837 #+COLUMNS: %25ITEM ....."
1838 :group 'org-properties
1839 :type 'string)
1841 (defcustom org-effort-property "Effort"
1842 "The property that is being used to keep track of effort estimates.
1843 Effort estimates given in this property need to have the format H:MM."
1844 :group 'org-properties
1845 :group 'org-progress
1846 :type '(string :tag "Property"))
1848 (defcustom org-global-properties nil
1849 "List of property/value pairs that can be inherited by any entry.
1850 You can set buffer-local values for this by adding lines like
1852 #+PROPERTY: NAME VALUE"
1853 :group 'org-properties
1854 :type '(repeat
1855 (cons (string :tag "Property")
1856 (string :tag "Value"))))
1858 (defvar org-local-properties nil
1859 "List of property/value pairs that can be inherited by any entry.
1860 Valid for the current buffer.
1861 This variable is populated from #+PROPERTY lines.")
1863 (defgroup org-agenda nil
1864 "Options concerning agenda views in Org-mode."
1865 :tag "Org Agenda"
1866 :group 'org)
1868 (defvar org-category nil
1869 "Variable used by org files to set a category for agenda display.
1870 Such files should use a file variable to set it, for example
1872 # -*- mode: org; org-category: \"ELisp\"
1874 or contain a special line
1876 #+CATEGORY: ELisp
1878 If the file does not specify a category, then file's base name
1879 is used instead.")
1880 (make-variable-buffer-local 'org-category)
1882 (defcustom org-agenda-files nil
1883 "The files to be used for agenda display.
1884 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
1885 \\[org-remove-file]. You can also use customize to edit the list.
1887 If an entry is a directory, all files in that directory that are matched by
1888 `org-agenda-file-regexp' will be part of the file list.
1890 If the value of the variable is not a list but a single file name, then
1891 the list of agenda files is actually stored and maintained in that file, one
1892 agenda file per line."
1893 :group 'org-agenda
1894 :type '(choice
1895 (repeat :tag "List of files and directories" file)
1896 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
1898 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
1899 "Regular expression to match files for `org-agenda-files'.
1900 If any element in the list in that variable contains a directory instead
1901 of a normal file, all files in that directory that are matched by this
1902 regular expression will be included."
1903 :group 'org-agenda
1904 :type 'regexp)
1906 (defcustom org-agenda-text-search-extra-files nil
1907 "List of extra files to be searched by text search commands.
1908 These files will be search in addition to the agenda files by the
1909 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
1910 Note that these files will only be searched for text search commands,
1911 not for the other agenda views like todo lists, tag searches or the weekly
1912 agenda. This variable is intended to list notes and possibly archive files
1913 that should also be searched by these two commands.
1914 In fact, if the first element in the list is the symbol `agenda-archives',
1915 than all archive files of all agenda files will be added to the search
1916 scope."
1917 :group 'org-agenda
1918 :type '(set :greedy t
1919 (const :tag "Agenda Archives" agenda-archives)
1920 (repeat :inline t (file))))
1922 (if (fboundp 'defvaralias)
1923 (defvaralias 'org-agenda-multi-occur-extra-files
1924 'org-agenda-text-search-extra-files))
1926 (defcustom org-agenda-skip-unavailable-files nil
1927 "t means to just skip non-reachable files in `org-agenda-files'.
1928 Nil means to remove them, after a query, from the list."
1929 :group 'org-agenda
1930 :type 'boolean)
1932 (defcustom org-calendar-to-agenda-key [?c]
1933 "The key to be installed in `calendar-mode-map' for switching to the agenda.
1934 The command `org-calendar-goto-agenda' will be bound to this key. The
1935 default is the character `c' because then `c' can be used to switch back and
1936 forth between agenda and calendar."
1937 :group 'org-agenda
1938 :type 'sexp)
1940 (eval-after-load "calendar"
1941 '(org-defkey calendar-mode-map org-calendar-to-agenda-key
1942 'org-calendar-goto-agenda))
1944 (defgroup org-latex nil
1945 "Options for embedding LaTeX code into Org-mode."
1946 :tag "Org LaTeX"
1947 :group 'org)
1949 (defcustom org-format-latex-options
1950 '(:foreground default :background default :scale 1.0
1951 :html-foreground "Black" :html-background "Transparent" :html-scale 1.0
1952 :matchers ("begin" "$" "$$" "\\(" "\\["))
1953 "Options for creating images from LaTeX fragments.
1954 This is a property list with the following properties:
1955 :foreground the foreground color for images embedded in emacs, e.g. \"Black\".
1956 `default' means use the forground of the default face.
1957 :background the background color, or \"Transparent\".
1958 `default' means use the background of the default face.
1959 :scale a scaling factor for the size of the images
1960 :html-foreground, :html-background, :html-scale
1961 The same numbers for HTML export.
1962 :matchers a list indicating which matchers should be used to
1963 find LaTeX fragments. Valid members of this list are:
1964 \"begin\" find environments
1965 \"$\" find math expressions surrounded by $...$
1966 \"$$\" find math expressions surrounded by $$....$$
1967 \"\\(\" find math expressions surrounded by \\(...\\)
1968 \"\\ [\" find math expressions surrounded by \\ [...\\]"
1969 :group 'org-latex
1970 :type 'plist)
1972 (defcustom org-format-latex-header "\\documentclass{article}
1973 \\usepackage{fullpage} % do not remove
1974 \\usepackage{amssymb}
1975 \\usepackage[usenames]{color}
1976 \\usepackage{amsmath}
1977 \\usepackage{latexsym}
1978 \\usepackage[mathscr]{eucal}
1979 \\pagestyle{empty} % do not remove"
1980 "The document header used for processing LaTeX fragments."
1981 :group 'org-latex
1982 :type 'string)
1985 (defgroup org-font-lock nil
1986 "Font-lock settings for highlighting in Org-mode."
1987 :tag "Org Font Lock"
1988 :group 'org)
1990 (defcustom org-level-color-stars-only nil
1991 "Non-nil means fontify only the stars in each headline.
1992 When nil, the entire headline is fontified.
1993 Changing it requires restart of `font-lock-mode' to become effective
1994 also in regions already fontified."
1995 :group 'org-font-lock
1996 :type 'boolean)
1998 (defcustom org-hide-leading-stars nil
1999 "Non-nil means, hide the first N-1 stars in a headline.
2000 This works by using the face `org-hide' for these stars. This
2001 face is white for a light background, and black for a dark
2002 background. You may have to customize the face `org-hide' to
2003 make this work.
2004 Changing it requires restart of `font-lock-mode' to become effective
2005 also in regions already fontified.
2006 You may also set this on a per-file basis by adding one of the following
2007 lines to the buffer:
2009 #+STARTUP: hidestars
2010 #+STARTUP: showstars"
2011 :group 'org-font-lock
2012 :type 'boolean)
2014 (defcustom org-fontify-done-headline nil
2015 "Non-nil means, change the face of a headline if it is marked DONE.
2016 Normally, only the TODO/DONE keyword indicates the state of a headline.
2017 When this is non-nil, the headline after the keyword is set to the
2018 `org-headline-done' as an additional indication."
2019 :group 'org-font-lock
2020 :type 'boolean)
2022 (defcustom org-fontify-emphasized-text t
2023 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
2024 Changing this variable requires a restart of Emacs to take effect."
2025 :group 'org-font-lock
2026 :type 'boolean)
2028 (defcustom org-highlight-latex-fragments-and-specials nil
2029 "Non-nil means, fontify what is treated specially by the exporters."
2030 :group 'org-font-lock
2031 :type 'boolean)
2033 (defcustom org-hide-emphasis-markers nil
2034 "Non-nil mean font-lock should hide the emphasis marker characters."
2035 :group 'org-font-lock
2036 :type 'boolean)
2038 (defvar org-emph-re nil
2039 "Regular expression for matching emphasis.")
2040 (defvar org-verbatim-re nil
2041 "Regular expression for matching verbatim text.")
2042 (defvar org-emphasis-regexp-components) ; defined just below
2043 (defvar org-emphasis-alist) ; defined just below
2044 (defun org-set-emph-re (var val)
2045 "Set variable and compute the emphasis regular expression."
2046 (set var val)
2047 (when (and (boundp 'org-emphasis-alist)
2048 (boundp 'org-emphasis-regexp-components)
2049 org-emphasis-alist org-emphasis-regexp-components)
2050 (let* ((e org-emphasis-regexp-components)
2051 (pre (car e))
2052 (post (nth 1 e))
2053 (border (nth 2 e))
2054 (body (nth 3 e))
2055 (nl (nth 4 e))
2056 (stacked (and nil (nth 5 e))) ; stacked is no longer allowed, forced to nil
2057 (body1 (concat body "*?"))
2058 (markers (mapconcat 'car org-emphasis-alist ""))
2059 (vmarkers (mapconcat
2060 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
2061 org-emphasis-alist "")))
2062 ;; make sure special characters appear at the right position in the class
2063 (if (string-match "\\^" markers)
2064 (setq markers (concat (replace-match "" t t markers) "^")))
2065 (if (string-match "-" markers)
2066 (setq markers (concat (replace-match "" t t markers) "-")))
2067 (if (string-match "\\^" vmarkers)
2068 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
2069 (if (string-match "-" vmarkers)
2070 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
2071 (if (> nl 0)
2072 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
2073 (int-to-string nl) "\\}")))
2074 ;; Make the regexp
2075 (setq org-emph-re
2076 (concat "\\([" pre (if (and nil stacked) markers) "]\\|^\\)"
2077 "\\("
2078 "\\([" markers "]\\)"
2079 "\\("
2080 "[^" border "]\\|"
2081 "[^" border (if (and nil stacked) markers) "]"
2082 body1
2083 "[^" border (if (and nil stacked) markers) "]"
2084 "\\)"
2085 "\\3\\)"
2086 "\\([" post (if (and nil stacked) markers) "]\\|$\\)"))
2087 (setq org-verbatim-re
2088 (concat "\\([" pre "]\\|^\\)"
2089 "\\("
2090 "\\([" vmarkers "]\\)"
2091 "\\("
2092 "[^" border "]\\|"
2093 "[^" border "]"
2094 body1
2095 "[^" border "]"
2096 "\\)"
2097 "\\3\\)"
2098 "\\([" post "]\\|$\\)")))))
2100 (defcustom org-emphasis-regexp-components
2101 '(" \t('\"" "- \t.,:?;'\")" " \t\r\n,\"'" "." 1)
2102 "Components used to build the regular expression for emphasis.
2103 This is a list with 6 entries. Terminology: In an emphasis string
2104 like \" *strong word* \", we call the initial space PREMATCH, the final
2105 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
2106 and \"trong wor\" is the body. The different components in this variable
2107 specify what is allowed/forbidden in each part:
2109 pre Chars allowed as prematch. Beginning of line will be allowed too.
2110 post Chars allowed as postmatch. End of line will be allowed too.
2111 border The chars *forbidden* as border characters.
2112 body-regexp A regexp like \".\" to match a body character. Don't use
2113 non-shy groups here, and don't allow newline here.
2114 newline The maximum number of newlines allowed in an emphasis exp.
2116 Use customize to modify this, or restart Emacs after changing it."
2117 :group 'org-font-lock
2118 :set 'org-set-emph-re
2119 :type '(list
2120 (sexp :tag "Allowed chars in pre ")
2121 (sexp :tag "Allowed chars in post ")
2122 (sexp :tag "Forbidden chars in border ")
2123 (sexp :tag "Regexp for body ")
2124 (integer :tag "number of newlines allowed")
2125 (option (boolean :tag "Stacking (DISABLED) "))))
2127 (defcustom org-emphasis-alist
2128 `(("*" bold "<b>" "</b>")
2129 ("/" italic "<i>" "</i>")
2130 ("_" underline "<u>" "</u>")
2131 ("=" org-code "<code>" "</code>" verbatim)
2132 ("~" org-verbatim "" "" verbatim)
2133 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
2134 "<del>" "</del>")
2136 "Special syntax for emphasized text.
2137 Text starting and ending with a special character will be emphasized, for
2138 example *bold*, _underlined_ and /italic/. This variable sets the marker
2139 characters, the face to be used by font-lock for highlighting in Org-mode
2140 Emacs buffers, and the HTML tags to be used for this.
2141 Use customize to modify this, or restart Emacs after changing it."
2142 :group 'org-font-lock
2143 :set 'org-set-emph-re
2144 :type '(repeat
2145 (list
2146 (string :tag "Marker character")
2147 (choice
2148 (face :tag "Font-lock-face")
2149 (plist :tag "Face property list"))
2150 (string :tag "HTML start tag")
2151 (string :tag "HTML end tag")
2152 (option (const verbatim)))))
2154 ;;; Miscellaneous options
2156 (defgroup org-completion nil
2157 "Completion in Org-mode."
2158 :tag "Org Completion"
2159 :group 'org)
2161 (defcustom org-completion-fallback-command 'hippie-expand
2162 "The expansion command called by \\[org-complete] in normal context.
2163 Normal means, no org-mode-specific context."
2164 :group 'org-completion
2165 :type 'function)
2167 ;;; Functions and variables from ther packages
2168 ;; Declared here to avoid compiler warnings
2170 ;; XEmacs only
2171 (defvar outline-mode-menu-heading)
2172 (defvar outline-mode-menu-show)
2173 (defvar outline-mode-menu-hide)
2174 (defvar zmacs-regions) ; XEmacs regions
2176 ;; Emacs only
2177 (defvar mark-active)
2179 ;; Various packages
2180 (declare-function calendar-absolute-from-iso "cal-iso" (date))
2181 (declare-function calendar-forward-day "cal-move" (arg))
2182 (declare-function calendar-goto-date "cal-move" (date))
2183 (declare-function calendar-goto-today "cal-move" ())
2184 (declare-function calendar-iso-from-absolute "cal-iso" (date))
2185 (defvar calc-embedded-close-formula)
2186 (defvar calc-embedded-open-formula)
2187 (declare-function cdlatex-tab "ext:cdlatex" ())
2188 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
2189 (defvar font-lock-unfontify-region-function)
2190 (declare-function iswitchb-mode "iswitchb" (&optional arg))
2191 (declare-function iswitchb-read-buffer (prompt &optional default require-match start matches-set))
2192 (defvar iswitchb-temp-buflist)
2193 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
2194 (declare-function org-agenda-skip "org-agenda" ())
2195 (declare-function org-format-agenda-item "org-agenda"
2196 (extra txt &optional category tags dotime noprefix remove-re))
2197 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
2198 (declare-function org-agenda-change-all-lines "org-agenda"
2199 (newhead hdmarker &optional fixface))
2200 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
2201 (declare-function org-agenda-maybe-redo "org-agenda" ())
2202 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
2203 (beg end))
2204 (declare-function parse-time-string "parse-time" (string))
2205 (declare-function remember "remember" (&optional initial))
2206 (declare-function remember-buffer-desc "remember" ())
2207 (declare-function remember-finalize "remember" ())
2208 (defvar remember-save-after-remembering)
2209 (defvar remember-data-file)
2210 (defvar remember-register)
2211 (defvar remember-buffer)
2212 (defvar remember-handler-functions)
2213 (defvar remember-annotation-functions)
2214 (defvar texmathp-why)
2215 (declare-function speedbar-line-directory "speedbar" (&optional depth))
2216 (declare-function table--at-cell-p "table" (position &optional object at-column))
2218 (defvar w3m-current-url)
2219 (defvar w3m-current-title)
2221 (defvar org-latex-regexps)
2223 ;;; Autoload and prepare some org modules
2225 ;; Some table stuff that needs to be defined here, because it is used
2226 ;; by the functions setting up org-mode or checking for table context.
2228 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
2229 "Detects an org-type or table-type table.")
2230 (defconst org-table-line-regexp "^[ \t]*|"
2231 "Detects an org-type table line.")
2232 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
2233 "Detects an org-type table line.")
2234 (defconst org-table-hline-regexp "^[ \t]*|-"
2235 "Detects an org-type table hline.")
2236 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
2237 "Detects a table-type table hline.")
2238 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
2239 "Searching from within a table (any type) this finds the first line
2240 outside the table.")
2242 ;; Autoload the functions in org-table.el that are needed by functions here.
2244 (eval-and-compile
2245 (org-autoload "org-table"
2246 '(org-table-align org-table-begin org-table-blank-field
2247 org-table-convert org-table-convert-region org-table-copy-down
2248 org-table-copy-region org-table-create
2249 org-table-create-or-convert-from-region
2250 org-table-create-with-table.el org-table-current-dline
2251 org-table-cut-region org-table-delete-column org-table-edit-field
2252 org-table-edit-formulas org-table-end org-table-eval-formula
2253 org-table-export org-table-field-info
2254 org-table-get-stored-formulas org-table-goto-column
2255 org-table-hline-and-move org-table-import org-table-insert-column
2256 org-table-insert-hline org-table-insert-row org-table-iterate
2257 org-table-justify-field-maybe org-table-kill-row
2258 org-table-maybe-eval-formula org-table-maybe-recalculate-line
2259 org-table-move-column org-table-move-column-left
2260 org-table-move-column-right org-table-move-row
2261 org-table-move-row-down org-table-move-row-up
2262 org-table-next-field org-table-next-row org-table-paste-rectangle
2263 org-table-previous-field org-table-recalculate
2264 org-table-rotate-recalc-marks org-table-sort-lines org-table-sum
2265 org-table-toggle-coordinate-overlays
2266 org-table-toggle-formula-debugger org-table-wrap-region
2267 orgtbl-mode turn-on-orgtbl)))
2269 (defun org-at-table-p (&optional table-type)
2270 "Return t if the cursor is inside an org-type table.
2271 If TABLE-TYPE is non-nil, also check for table.el-type tables."
2272 (if org-enable-table-editor
2273 (save-excursion
2274 (beginning-of-line 1)
2275 (looking-at (if table-type org-table-any-line-regexp
2276 org-table-line-regexp)))
2277 nil))
2278 (defsubst org-table-p () (org-at-table-p))
2280 (defun org-at-table.el-p ()
2281 "Return t if and only if we are at a table.el table."
2282 (and (org-at-table-p 'any)
2283 (save-excursion
2284 (goto-char (org-table-begin 'any))
2285 (looking-at org-table1-hline-regexp))))
2286 (defun org-table-recognize-table.el ()
2287 "If there is a table.el table nearby, recognize it and move into it."
2288 (if org-table-tab-recognizes-table.el
2289 (if (org-at-table.el-p)
2290 (progn
2291 (beginning-of-line 1)
2292 (if (looking-at org-table-dataline-regexp)
2294 (if (looking-at org-table1-hline-regexp)
2295 (progn
2296 (beginning-of-line 2)
2297 (if (looking-at org-table-any-border-regexp)
2298 (beginning-of-line -1)))))
2299 (if (re-search-forward "|" (org-table-end t) t)
2300 (progn
2301 (require 'table)
2302 (if (table--at-cell-p (point))
2304 (message "recognizing table.el table...")
2305 (table-recognize-table)
2306 (message "recognizing table.el table...done")))
2307 (error "This should not happen..."))
2309 nil)
2310 nil))
2312 (defun org-at-table-hline-p ()
2313 "Return t if the cursor is inside a hline in a table."
2314 (if org-enable-table-editor
2315 (save-excursion
2316 (beginning-of-line 1)
2317 (looking-at org-table-hline-regexp))
2318 nil))
2320 (defvar org-table-clean-did-remove-column nil)
2322 (defun org-table-map-tables (function)
2323 "Apply FUNCTION to the start of all tables in the buffer."
2324 (save-excursion
2325 (save-restriction
2326 (widen)
2327 (goto-char (point-min))
2328 (while (re-search-forward org-table-any-line-regexp nil t)
2329 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
2330 (beginning-of-line 1)
2331 (if (looking-at org-table-line-regexp)
2332 (save-excursion (funcall function)))
2333 (re-search-forward org-table-any-border-regexp nil 1))))
2334 (message "Mapping tables: done"))
2336 ;; Declare and autoload functions from org-exp.el
2338 (declare-function org-default-export-plist "org-exp")
2339 (declare-function org-infile-export-plist "org-exp")
2340 (declare-function org-get-current-options "org-exp")
2341 (eval-and-compile
2342 (org-autoload "org-exp"
2343 '(org-export org-export-as-ascii org-export-visible
2344 org-insert-export-options-template org-export-as-html-and-open
2345 org-export-as-html-batch org-export-as-html-to-buffer
2346 org-replace-region-by-html org-export-region-as-html
2347 org-export-as-html org-export-icalendar-this-file
2348 org-export-icalendar-all-agenda-files
2349 org-export-icalendar-combine-agenda-files org-export-as-xoxo)))
2351 ;; Declare and autoload functions from org-exp.el
2353 (eval-and-compile
2354 (org-autoload "org-exp"
2355 '(org-agenda org-agenda-list org-search-view
2356 org-todo-list org-tags-view org-agenda-list-stuck-projects
2357 org-diary org-agenda-to-appt)))
2359 ;; Autoload org-remember
2361 (eval-and-compile
2362 (org-autoload "org-remember"
2363 '(org-remember-insinuate org-remember-annotation
2364 org-remember-apply-template org-remember org-remember-handler)))
2366 ;; Autoload org-clock.el
2369 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock"
2370 (beg end))
2371 (defvar org-clock-marker (make-marker)
2372 "Marker recording the last clock-in.")
2374 (eval-and-compile
2375 (org-autoload
2376 "org-clock"
2377 '(org-clock-in org-clock-out org-clock-cancel
2378 org-clock-goto org-clock-sum org-clock-display
2379 org-remove-clock-overlays org-clock-report
2380 org-clocktable-shift org-dblock-write:clocktable
2381 org-get-clocktable)))
2383 (defun org-clock-update-time-maybe ()
2384 "If this is a CLOCK line, update it and return t.
2385 Otherwise, return nil."
2386 (interactive)
2387 (save-excursion
2388 (beginning-of-line 1)
2389 (skip-chars-forward " \t")
2390 (when (looking-at org-clock-string)
2391 (let ((re (concat "[ \t]*" org-clock-string
2392 " *[[<]\\([^]>]+\\)[]>]-+[[<]\\([^]>]+\\)[]>]"
2393 "\\([ \t]*=>.*\\)?"))
2394 ts te h m s)
2395 (if (not (looking-at re))
2397 (and (match-end 3) (delete-region (match-beginning 3) (match-end 3)))
2398 (end-of-line 1)
2399 (setq ts (match-string 1)
2400 te (match-string 2))
2401 (setq s (- (time-to-seconds
2402 (apply 'encode-time (org-parse-time-string te)))
2403 (time-to-seconds
2404 (apply 'encode-time (org-parse-time-string ts))))
2405 h (floor (/ s 3600))
2406 s (- s (* 3600 h))
2407 m (floor (/ s 60))
2408 s (- s (* 60 s)))
2409 (insert " => " (format "%2d:%02d" h m))
2410 t)))))
2412 (defun org-check-running-clock ()
2413 "Check if the current buffer contains the running clock.
2414 If yes, offer to stop it and to save the buffer with the changes."
2415 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
2416 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
2417 (buffer-name))))
2418 (org-clock-out)
2419 (when (y-or-n-p "Save changed buffer?")
2420 (save-buffer))))
2422 (defun org-clocktable-try-shift (dir n)
2423 "Check if this line starts a clock table, if yes, shift the time block."
2424 (when (org-match-line "#\\+BEGIN: clocktable\\>")
2425 (org-clocktable-shift dir n)))
2427 ;; Autoload archiving code
2428 ;; The stuff that is needed for cycling and tags has to be defined here.
2430 (defgroup org-archive nil
2431 "Options concerning archiving in Org-mode."
2432 :tag "Org Archive"
2433 :group 'org-structure)
2435 (defcustom org-archive-location "%s_archive::"
2436 "The location where subtrees should be archived.
2438 Otherwise, the value of this variable is a string, consisting of two
2439 parts, separated by a double-colon.
2441 The first part is a file name - when omitted, archiving happens in the same
2442 file. %s will be replaced by the current file name (without directory part).
2443 Archiving to a different file is useful to keep archived entries from
2444 contributing to the Org-mode Agenda.
2446 The part after the double colon is a headline. The archived entries will be
2447 filed under that headline. When omitted, the subtrees are simply filed away
2448 at the end of the file, as top-level entries.
2450 Here are a few examples:
2451 \"%s_archive::\"
2452 If the current file is Projects.org, archive in file
2453 Projects.org_archive, as top-level trees. This is the default.
2455 \"::* Archived Tasks\"
2456 Archive in the current file, under the top-level headline
2457 \"* Archived Tasks\".
2459 \"~/org/archive.org::\"
2460 Archive in file ~/org/archive.org (absolute path), as top-level trees.
2462 \"basement::** Finished Tasks\"
2463 Archive in file ./basement (relative path), as level 3 trees
2464 below the level 2 heading \"** Finished Tasks\".
2466 You may set this option on a per-file basis by adding to the buffer a
2467 line like
2469 #+ARCHIVE: basement::** Finished Tasks
2471 You may also define it locally for a subtree by setting an ARCHIVE property
2472 in the entry. If such a property is found in an entry, or anywhere up
2473 the hierarchy, it will be used."
2474 :group 'org-archive
2475 :type 'string)
2477 (defcustom org-archive-tag "ARCHIVE"
2478 "The tag that marks a subtree as archived.
2479 An archived subtree does not open during visibility cycling, and does
2480 not contribute to the agenda listings.
2481 After changing this, font-lock must be restarted in the relevant buffers to
2482 get the proper fontification."
2483 :group 'org-archive
2484 :group 'org-keywords
2485 :type 'string)
2487 (defcustom org-agenda-skip-archived-trees t
2488 "Non-nil means, the agenda will skip any items located in archived trees.
2489 An archived tree is a tree marked with the tag ARCHIVE."
2490 :group 'org-archive
2491 :group 'org-agenda-skip
2492 :type 'boolean)
2494 (defcustom org-cycle-open-archived-trees nil
2495 "Non-nil means, `org-cycle' will open archived trees.
2496 An archived tree is a tree marked with the tag ARCHIVE.
2497 When nil, archived trees will stay folded. You can still open them with
2498 normal outline commands like `show-all', but not with the cycling commands."
2499 :group 'org-archive
2500 :group 'org-cycle
2501 :type 'boolean)
2503 (defcustom org-sparse-tree-open-archived-trees nil
2504 "Non-nil means sparse tree construction shows matches in archived trees.
2505 When nil, matches in these trees are highlighted, but the trees are kept in
2506 collapsed state."
2507 :group 'org-archive
2508 :group 'org-sparse-trees
2509 :type 'boolean)
2511 (defun org-cycle-hide-archived-subtrees (state)
2512 "Re-hide all archived subtrees after a visibility state change."
2513 (when (and (not org-cycle-open-archived-trees)
2514 (not (memq state '(overview folded))))
2515 (save-excursion
2516 (let* ((globalp (memq state '(contents all)))
2517 (beg (if globalp (point-min) (point)))
2518 (end (if globalp (point-max) (org-end-of-subtree t))))
2519 (org-hide-archived-subtrees beg end)
2520 (goto-char beg)
2521 (if (looking-at (concat ".*:" org-archive-tag ":"))
2522 (message "%s" (substitute-command-keys
2523 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
2525 (defun org-force-cycle-archived ()
2526 "Cycle subtree even if it is archived."
2527 (interactive)
2528 (setq this-command 'org-cycle)
2529 (let ((org-cycle-open-archived-trees t))
2530 (call-interactively 'org-cycle)))
2532 (defun org-hide-archived-subtrees (beg end)
2533 "Re-hide all archived subtrees after a visibility state change."
2534 (save-excursion
2535 (let* ((re (concat ":" org-archive-tag ":")))
2536 (goto-char beg)
2537 (while (re-search-forward re end t)
2538 (and (org-on-heading-p) (hide-subtree))
2539 (org-end-of-subtree t)))))
2541 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
2543 (eval-and-compile
2544 (org-autoload "org-archive"
2545 '(org-add-archive-files org-archive-subtree
2546 org-archive-to-archive-sibling org-toggle-archive-tag)))
2548 ;; Autoload Column View Code
2550 (declare-function org-columns-number-to-string "org-colview")
2551 (declare-function org-columns-get-format-and-top-level "org-colview")
2552 (declare-function org-columns-compute "org-colview")
2554 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
2555 '(org-columns-number-to-string org-columns-get-format-and-top-level
2556 org-columns-compute org-agenda-columns org-columns-remove-overlays
2557 org-columns org-insert-columns-dblock))
2559 ;;; Variables for pre-computed regular expressions, all buffer local
2561 (defvar org-drawer-regexp nil
2562 "Matches first line of a hidden block.")
2563 (make-variable-buffer-local 'org-drawer-regexp)
2564 (defvar org-todo-regexp nil
2565 "Matches any of the TODO state keywords.")
2566 (make-variable-buffer-local 'org-todo-regexp)
2567 (defvar org-not-done-regexp nil
2568 "Matches any of the TODO state keywords except the last one.")
2569 (make-variable-buffer-local 'org-not-done-regexp)
2570 (defvar org-todo-line-regexp nil
2571 "Matches a headline and puts TODO state into group 2 if present.")
2572 (make-variable-buffer-local 'org-todo-line-regexp)
2573 (defvar org-complex-heading-regexp nil
2574 "Matches a headline and puts everything into groups:
2575 group 1: the stars
2576 group 2: The todo keyword, maybe
2577 group 3: Priority cookie
2578 group 4: True headline
2579 group 5: Tags")
2580 (make-variable-buffer-local 'org-complex-heading-regexp)
2581 (defvar org-todo-line-tags-regexp nil
2582 "Matches a headline and puts TODO state into group 2 if present.
2583 Also put tags into group 4 if tags are present.")
2584 (make-variable-buffer-local 'org-todo-line-tags-regexp)
2585 (defvar org-nl-done-regexp nil
2586 "Matches newline followed by a headline with the DONE keyword.")
2587 (make-variable-buffer-local 'org-nl-done-regexp)
2588 (defvar org-looking-at-done-regexp nil
2589 "Matches the DONE keyword a point.")
2590 (make-variable-buffer-local 'org-looking-at-done-regexp)
2591 (defvar org-ds-keyword-length 12
2592 "Maximum length of the Deadline and SCHEDULED keywords.")
2593 (make-variable-buffer-local 'org-ds-keyword-length)
2594 (defvar org-deadline-regexp nil
2595 "Matches the DEADLINE keyword.")
2596 (make-variable-buffer-local 'org-deadline-regexp)
2597 (defvar org-deadline-time-regexp nil
2598 "Matches the DEADLINE keyword together with a time stamp.")
2599 (make-variable-buffer-local 'org-deadline-time-regexp)
2600 (defvar org-deadline-line-regexp nil
2601 "Matches the DEADLINE keyword and the rest of the line.")
2602 (make-variable-buffer-local 'org-deadline-line-regexp)
2603 (defvar org-scheduled-regexp nil
2604 "Matches the SCHEDULED keyword.")
2605 (make-variable-buffer-local 'org-scheduled-regexp)
2606 (defvar org-scheduled-time-regexp nil
2607 "Matches the SCHEDULED keyword together with a time stamp.")
2608 (make-variable-buffer-local 'org-scheduled-time-regexp)
2609 (defvar org-closed-time-regexp nil
2610 "Matches the CLOSED keyword together with a time stamp.")
2611 (make-variable-buffer-local 'org-closed-time-regexp)
2613 (defvar org-keyword-time-regexp nil
2614 "Matches any of the 4 keywords, together with the time stamp.")
2615 (make-variable-buffer-local 'org-keyword-time-regexp)
2616 (defvar org-keyword-time-not-clock-regexp nil
2617 "Matches any of the 3 keywords, together with the time stamp.")
2618 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
2619 (defvar org-maybe-keyword-time-regexp nil
2620 "Matches a timestamp, possibly preceeded by a keyword.")
2621 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
2622 (defvar org-planning-or-clock-line-re nil
2623 "Matches a line with planning or clock info.")
2624 (make-variable-buffer-local 'org-planning-or-clock-line-re)
2626 (defconst org-plain-time-of-day-regexp
2627 (concat
2628 "\\(\\<[012]?[0-9]"
2629 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
2630 "\\(--?"
2631 "\\(\\<[012]?[0-9]"
2632 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
2633 "\\)?")
2634 "Regular expression to match a plain time or time range.
2635 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
2636 groups carry important information:
2637 0 the full match
2638 1 the first time, range or not
2639 8 the second time, if it is a range.")
2641 (defconst org-plain-time-extension-regexp
2642 (concat
2643 "\\(\\<[012]?[0-9]"
2644 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
2645 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
2646 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
2647 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
2648 groups carry important information:
2649 0 the full match
2650 7 hours of duration
2651 9 minutes of duration")
2653 (defconst org-stamp-time-of-day-regexp
2654 (concat
2655 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
2656 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
2657 "\\(--?"
2658 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
2659 "Regular expression to match a timestamp time or time range.
2660 After a match, the following groups carry important information:
2661 0 the full match
2662 1 date plus weekday, for backreferencing to make sure both times on same day
2663 2 the first time, range or not
2664 4 the second time, if it is a range.")
2666 (defconst org-startup-options
2667 '(("fold" org-startup-folded t)
2668 ("overview" org-startup-folded t)
2669 ("nofold" org-startup-folded nil)
2670 ("showall" org-startup-folded nil)
2671 ("content" org-startup-folded content)
2672 ("hidestars" org-hide-leading-stars t)
2673 ("showstars" org-hide-leading-stars nil)
2674 ("odd" org-odd-levels-only t)
2675 ("oddeven" org-odd-levels-only nil)
2676 ("align" org-startup-align-all-tables t)
2677 ("noalign" org-startup-align-all-tables nil)
2678 ("customtime" org-display-custom-times t)
2679 ("logdone" org-log-done time)
2680 ("lognotedone" org-log-done note)
2681 ("nologdone" org-log-done nil)
2682 ("lognoteclock-out" org-log-note-clock-out t)
2683 ("nolognoteclock-out" org-log-note-clock-out nil)
2684 ("logrepeat" org-log-repeat state)
2685 ("lognoterepeat" org-log-repeat note)
2686 ("nologrepeat" org-log-repeat nil)
2687 ("constcgs" constants-unit-system cgs)
2688 ("constSI" constants-unit-system SI))
2689 "Variable associated with STARTUP options for org-mode.
2690 Each element is a list of three items: The startup options as written
2691 in the #+STARTUP line, the corresponding variable, and the value to
2692 set this variable to if the option is found. An optional forth element PUSH
2693 means to push this value onto the list in the variable.")
2695 (defun org-set-regexps-and-options ()
2696 "Precompute regular expressions for current buffer."
2697 (when (org-mode-p)
2698 (org-set-local 'org-todo-kwd-alist nil)
2699 (org-set-local 'org-todo-key-alist nil)
2700 (org-set-local 'org-todo-key-trigger nil)
2701 (org-set-local 'org-todo-keywords-1 nil)
2702 (org-set-local 'org-done-keywords nil)
2703 (org-set-local 'org-todo-heads nil)
2704 (org-set-local 'org-todo-sets nil)
2705 (org-set-local 'org-todo-log-states nil)
2706 (let ((re (org-make-options-regexp
2707 '("CATEGORY" "SEQ_TODO" "TYP_TODO" "TODO" "COLUMNS"
2708 "STARTUP" "ARCHIVE" "TAGS" "LINK" "PRIORITIES"
2709 "CONSTANTS" "PROPERTY" "DRAWERS")))
2710 (splitre "[ \t]+")
2711 kwds kws0 kwsa key log value cat arch tags const links hw dws
2712 tail sep kws1 prio props drawers)
2713 (save-excursion
2714 (save-restriction
2715 (widen)
2716 (goto-char (point-min))
2717 (while (re-search-forward re nil t)
2718 (setq key (match-string 1) value (org-match-string-no-properties 2))
2719 (cond
2720 ((equal key "CATEGORY")
2721 (if (string-match "[ \t]+$" value)
2722 (setq value (replace-match "" t t value)))
2723 (setq cat value))
2724 ((member key '("SEQ_TODO" "TODO"))
2725 (push (cons 'sequence (org-split-string value splitre)) kwds))
2726 ((equal key "TYP_TODO")
2727 (push (cons 'type (org-split-string value splitre)) kwds))
2728 ((equal key "TAGS")
2729 (setq tags (append tags (org-split-string value splitre))))
2730 ((equal key "COLUMNS")
2731 (org-set-local 'org-columns-default-format value))
2732 ((equal key "LINK")
2733 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
2734 (push (cons (match-string 1 value)
2735 (org-trim (match-string 2 value)))
2736 links)))
2737 ((equal key "PRIORITIES")
2738 (setq prio (org-split-string value " +")))
2739 ((equal key "PROPERTY")
2740 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
2741 (push (cons (match-string 1 value) (match-string 2 value))
2742 props)))
2743 ((equal key "DRAWERS")
2744 (setq drawers (org-split-string value splitre)))
2745 ((equal key "CONSTANTS")
2746 (setq const (append const (org-split-string value splitre))))
2747 ((equal key "STARTUP")
2748 (let ((opts (org-split-string value splitre))
2749 l var val)
2750 (while (setq l (pop opts))
2751 (when (setq l (assoc l org-startup-options))
2752 (setq var (nth 1 l) val (nth 2 l))
2753 (if (not (nth 3 l))
2754 (set (make-local-variable var) val)
2755 (if (not (listp (symbol-value var)))
2756 (set (make-local-variable var) nil))
2757 (set (make-local-variable var) (symbol-value var))
2758 (add-to-list var val))))))
2759 ((equal key "ARCHIVE")
2760 (string-match " *$" value)
2761 (setq arch (replace-match "" t t value))
2762 (remove-text-properties 0 (length arch)
2763 '(face t fontified t) arch)))
2765 (when cat
2766 (org-set-local 'org-category (intern cat))
2767 (push (cons "CATEGORY" cat) props))
2768 (when prio
2769 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
2770 (setq prio (mapcar 'string-to-char prio))
2771 (org-set-local 'org-highest-priority (nth 0 prio))
2772 (org-set-local 'org-lowest-priority (nth 1 prio))
2773 (org-set-local 'org-default-priority (nth 2 prio)))
2774 (and props (org-set-local 'org-local-properties (nreverse props)))
2775 (and drawers (org-set-local 'org-drawers drawers))
2776 (and arch (org-set-local 'org-archive-location arch))
2777 (and links (setq org-link-abbrev-alist-local (nreverse links)))
2778 ;; Process the TODO keywords
2779 (unless kwds
2780 ;; Use the global values as if they had been given locally.
2781 (setq kwds (default-value 'org-todo-keywords))
2782 (if (stringp (car kwds))
2783 (setq kwds (list (cons org-todo-interpretation
2784 (default-value 'org-todo-keywords)))))
2785 (setq kwds (reverse kwds)))
2786 (setq kwds (nreverse kwds))
2787 (let (inter kws kw)
2788 (while (setq kws (pop kwds))
2789 (setq inter (pop kws) sep (member "|" kws)
2790 kws0 (delete "|" (copy-sequence kws))
2791 kwsa nil
2792 kws1 (mapcar
2793 (lambda (x)
2794 ;; 1 2
2795 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
2796 (progn
2797 (setq kw (match-string 1 x)
2798 key (and (match-end 2) (match-string 2 x))
2799 log (org-extract-log-state-settings x))
2800 (push (cons kw (and key (string-to-char key))) kwsa)
2801 (and log (push log org-todo-log-states))
2803 (error "Invalid TODO keyword %s" x)))
2804 kws0)
2805 kwsa (if kwsa (append '((:startgroup))
2806 (nreverse kwsa)
2807 '((:endgroup))))
2808 hw (car kws1)
2809 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
2810 tail (list inter hw (car dws) (org-last dws)))
2811 (add-to-list 'org-todo-heads hw 'append)
2812 (push kws1 org-todo-sets)
2813 (setq org-done-keywords (append org-done-keywords dws nil))
2814 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
2815 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
2816 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
2817 (setq org-todo-sets (nreverse org-todo-sets)
2818 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
2819 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
2820 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
2821 ;; Process the constants
2822 (when const
2823 (let (e cst)
2824 (while (setq e (pop const))
2825 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
2826 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
2827 (setq org-table-formula-constants-local cst)))
2829 ;; Process the tags.
2830 (when tags
2831 (let (e tgs)
2832 (while (setq e (pop tags))
2833 (cond
2834 ((equal e "{") (push '(:startgroup) tgs))
2835 ((equal e "}") (push '(:endgroup) tgs))
2836 ((string-match (org-re "^\\([[:alnum:]_@]+\\)(\\(.\\))$") e)
2837 (push (cons (match-string 1 e)
2838 (string-to-char (match-string 2 e)))
2839 tgs))
2840 (t (push (list e) tgs))))
2841 (org-set-local 'org-tag-alist nil)
2842 (while (setq e (pop tgs))
2843 (or (and (stringp (car e))
2844 (assoc (car e) org-tag-alist))
2845 (push e org-tag-alist))))))
2847 ;; Compute the regular expressions and other local variables
2848 (if (not org-done-keywords)
2849 (setq org-done-keywords (list (org-last org-todo-keywords-1))))
2850 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
2851 (length org-scheduled-string)
2852 (length org-clock-string)
2853 (length org-closed-string)))
2854 org-drawer-regexp
2855 (concat "^[ \t]*:\\("
2856 (mapconcat 'regexp-quote org-drawers "\\|")
2857 "\\):[ \t]*$")
2858 org-not-done-keywords
2859 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
2860 org-todo-regexp
2861 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords-1
2862 "\\|") "\\)\\>")
2863 org-not-done-regexp
2864 (concat "\\<\\("
2865 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
2866 "\\)\\>")
2867 org-todo-line-regexp
2868 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
2869 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
2870 "\\)\\>\\)?[ \t]*\\(.*\\)")
2871 org-complex-heading-regexp
2872 (concat "^\\(\\*+\\)\\(?:[ \t]+\\("
2873 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
2874 "\\)\\>\\)?\\(?:[ \t]*\\(\\[#.\\]\\)\\)?[ \t]*\\(.*?\\)"
2875 "\\(?:[ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
2876 org-nl-done-regexp
2877 (concat "\n\\*+[ \t]+"
2878 "\\(?:" (mapconcat 'regexp-quote org-done-keywords "\\|")
2879 "\\)" "\\>")
2880 org-todo-line-tags-regexp
2881 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
2882 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
2883 (org-re
2884 "\\)\\>\\)? *\\(.*?\\([ \t]:[[:alnum:]:_@]+:[ \t]*\\)?$\\)"))
2885 org-looking-at-done-regexp
2886 (concat "^" "\\(?:"
2887 (mapconcat 'regexp-quote org-done-keywords "\\|") "\\)"
2888 "\\>")
2889 org-deadline-regexp (concat "\\<" org-deadline-string)
2890 org-deadline-time-regexp
2891 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
2892 org-deadline-line-regexp
2893 (concat "\\<\\(" org-deadline-string "\\).*")
2894 org-scheduled-regexp
2895 (concat "\\<" org-scheduled-string)
2896 org-scheduled-time-regexp
2897 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
2898 org-closed-time-regexp
2899 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
2900 org-keyword-time-regexp
2901 (concat "\\<\\(" org-scheduled-string
2902 "\\|" org-deadline-string
2903 "\\|" org-closed-string
2904 "\\|" org-clock-string "\\)"
2905 " *[[<]\\([^]>]+\\)[]>]")
2906 org-keyword-time-not-clock-regexp
2907 (concat "\\<\\(" org-scheduled-string
2908 "\\|" org-deadline-string
2909 "\\|" org-closed-string
2910 "\\)"
2911 " *[[<]\\([^]>]+\\)[]>]")
2912 org-maybe-keyword-time-regexp
2913 (concat "\\(\\<\\(" org-scheduled-string
2914 "\\|" org-deadline-string
2915 "\\|" org-closed-string
2916 "\\|" org-clock-string "\\)\\)?"
2917 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
2918 org-planning-or-clock-line-re
2919 (concat "\\(?:^[ \t]*\\(" org-scheduled-string
2920 "\\|" org-deadline-string
2921 "\\|" org-closed-string "\\|" org-clock-string
2922 "\\)\\>\\)")
2924 (org-compute-latex-and-specials-regexp)
2925 (org-set-font-lock-defaults)))
2927 (defun org-extract-log-state-settings (x)
2928 "Extract the log state setting from a TODO keyword string.
2929 This will extract info from a string like \"WAIT(w@/!)\"."
2930 (let (kw key log1 log2)
2931 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
2932 (setq kw (match-string 1 x)
2933 key (and (match-end 2) (match-string 2 x))
2934 log1 (and (match-end 3) (match-string 3 x))
2935 log2 (and (match-end 4) (match-string 4 x)))
2936 (and (or log1 log2)
2937 (list kw
2938 (and log1 (if (equal log1 "!") 'time 'note))
2939 (and log2 (if (equal log2 "!") 'time 'note)))))))
2941 (defun org-remove-keyword-keys (list)
2942 "Remove a pair of parenthesis at the end of each string in LIST."
2943 (mapcar (lambda (x)
2944 (if (string-match "(.*)$" x)
2945 (substring x 0 (match-beginning 0))
2947 list))
2949 ;; FIXME: this could be done much better, using second characters etc.
2950 (defun org-assign-fast-keys (alist)
2951 "Assign fast keys to a keyword-key alist.
2952 Respect keys that are already there."
2953 (let (new e k c c1 c2 (char ?a))
2954 (while (setq e (pop alist))
2955 (cond
2956 ((equal e '(:startgroup)) (push e new))
2957 ((equal e '(:endgroup)) (push e new))
2959 (setq k (car e) c2 nil)
2960 (if (cdr e)
2961 (setq c (cdr e))
2962 ;; automatically assign a character.
2963 (setq c1 (string-to-char
2964 (downcase (substring
2965 k (if (= (string-to-char k) ?@) 1 0)))))
2966 (if (or (rassoc c1 new) (rassoc c1 alist))
2967 (while (or (rassoc char new) (rassoc char alist))
2968 (setq char (1+ char)))
2969 (setq c2 c1))
2970 (setq c (or c2 char)))
2971 (push (cons k c) new))))
2972 (nreverse new)))
2974 ;;; Some variables used in various places
2976 (defvar org-window-configuration nil
2977 "Used in various places to store a window configuration.")
2978 (defvar org-finish-function nil
2979 "Function to be called when `C-c C-c' is used.
2980 This is for getting out of special buffers like remember.")
2983 ;; FIXME: Occasionally check by commenting these, to make sure
2984 ;; no other functions uses these, forgetting to let-bind them.
2985 (defvar entry)
2986 (defvar state)
2987 (defvar last-state)
2988 (defvar date)
2989 (defvar description)
2991 ;; Defined somewhere in this file, but used before definition.
2992 (defvar org-html-entities)
2993 (defvar org-struct-menu)
2994 (defvar org-org-menu)
2995 (defvar org-tbl-menu)
2996 (defvar org-agenda-keymap)
2998 ;;;; Define the Org-mode
3000 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
3001 (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."))
3004 ;; We use a before-change function to check if a table might need
3005 ;; an update.
3006 (defvar org-table-may-need-update t
3007 "Indicates that a table might need an update.
3008 This variable is set by `org-before-change-function'.
3009 `org-table-align' sets it back to nil.")
3010 (defun org-before-change-function (beg end)
3011 "Every change indicates that a table might need an update."
3012 (setq org-table-may-need-update t))
3013 (defvar org-mode-map)
3014 (defvar org-mode-hook nil)
3015 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
3016 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
3017 (defvar org-table-buffer-is-an nil)
3018 (defconst org-outline-regexp "\\*+ ")
3020 ;;;###autoload
3021 (define-derived-mode org-mode outline-mode "Org"
3022 "Outline-based notes management and organizer, alias
3023 \"Carsten's outline-mode for keeping track of everything.\"
3025 Org-mode develops organizational tasks around a NOTES file which
3026 contains information about projects as plain text. Org-mode is
3027 implemented on top of outline-mode, which is ideal to keep the content
3028 of large files well structured. It supports ToDo items, deadlines and
3029 time stamps, which magically appear in the diary listing of the Emacs
3030 calendar. Tables are easily created with a built-in table editor.
3031 Plain text URL-like links connect to websites, emails (VM), Usenet
3032 messages (Gnus), BBDB entries, and any files related to the project.
3033 For printing and sharing of notes, an Org-mode file (or a part of it)
3034 can be exported as a structured ASCII or HTML file.
3036 The following commands are available:
3038 \\{org-mode-map}"
3040 ;; Get rid of Outline menus, they are not needed
3041 ;; Need to do this here because define-derived-mode sets up
3042 ;; the keymap so late. Still, it is a waste to call this each time
3043 ;; we switch another buffer into org-mode.
3044 (if (featurep 'xemacs)
3045 (when (boundp 'outline-mode-menu-heading)
3046 ;; Assume this is Greg's port, it used easymenu
3047 (easy-menu-remove outline-mode-menu-heading)
3048 (easy-menu-remove outline-mode-menu-show)
3049 (easy-menu-remove outline-mode-menu-hide))
3050 (define-key org-mode-map [menu-bar headings] 'undefined)
3051 (define-key org-mode-map [menu-bar hide] 'undefined)
3052 (define-key org-mode-map [menu-bar show] 'undefined))
3054 (org-load-modules-maybe)
3055 (easy-menu-add org-org-menu)
3056 (easy-menu-add org-tbl-menu)
3057 (org-install-agenda-files-menu)
3058 (if org-descriptive-links (org-add-to-invisibility-spec '(org-link)))
3059 (org-add-to-invisibility-spec '(org-cwidth))
3060 (when (featurep 'xemacs)
3061 (org-set-local 'line-move-ignore-invisible t))
3062 (org-set-local 'outline-regexp org-outline-regexp)
3063 (org-set-local 'outline-level 'org-outline-level)
3064 (when (and org-ellipsis
3065 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
3066 (fboundp 'make-glyph-code))
3067 (unless org-display-table
3068 (setq org-display-table (make-display-table)))
3069 (set-display-table-slot
3070 org-display-table 4
3071 (vconcat (mapcar
3072 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
3073 org-ellipsis)))
3074 (if (stringp org-ellipsis) org-ellipsis "..."))))
3075 (setq buffer-display-table org-display-table))
3076 (org-set-regexps-and-options)
3077 ;; Calc embedded
3078 (org-set-local 'calc-embedded-open-mode "# ")
3079 (modify-syntax-entry ?# "<")
3080 (modify-syntax-entry ?@ "w")
3081 (if org-startup-truncated (setq truncate-lines t))
3082 (org-set-local 'font-lock-unfontify-region-function
3083 'org-unfontify-region)
3084 ;; Activate before-change-function
3085 (org-set-local 'org-table-may-need-update t)
3086 (org-add-hook 'before-change-functions 'org-before-change-function nil
3087 'local)
3088 ;; Check for running clock before killing a buffer
3089 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
3090 ;; Paragraphs and auto-filling
3091 (org-set-autofill-regexps)
3092 (setq indent-line-function 'org-indent-line-function)
3093 (org-update-radio-target-regexp)
3095 ;; Comment characters
3096 ; (org-set-local 'comment-start "#") ;; FIXME: this breaks wrapping
3097 (org-set-local 'comment-padding " ")
3099 ;; Align options lines
3100 (org-set-local
3101 'align-mode-rules-list
3102 '((org-in-buffer-settings
3103 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
3104 (modes . '(org-mode)))))
3106 ;; Imenu
3107 (org-set-local 'imenu-create-index-function
3108 'org-imenu-get-tree)
3110 ;; Make isearch reveal context
3111 (if (or (featurep 'xemacs)
3112 (not (boundp 'outline-isearch-open-invisible-function)))
3113 ;; Emacs 21 and XEmacs make use of the hook
3114 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
3115 ;; Emacs 22 deals with this through a special variable
3116 (org-set-local 'outline-isearch-open-invisible-function
3117 (lambda (&rest ignore) (org-show-context 'isearch))))
3119 ;; If empty file that did not turn on org-mode automatically, make it to.
3120 (if (and org-insert-mode-line-in-empty-file
3121 (interactive-p)
3122 (= (point-min) (point-max)))
3123 (insert "# -*- mode: org -*-\n\n"))
3125 (unless org-inhibit-startup
3126 (when org-startup-align-all-tables
3127 (let ((bmp (buffer-modified-p)))
3128 (org-table-map-tables 'org-table-align)
3129 (set-buffer-modified-p bmp)))
3130 (org-cycle-hide-drawers 'all)
3131 (cond
3132 ((eq org-startup-folded t)
3133 (org-cycle '(4)))
3134 ((eq org-startup-folded 'content)
3135 (let ((this-command 'org-cycle) (last-command 'org-cycle))
3136 (org-cycle '(4)) (org-cycle '(4)))))))
3138 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
3140 (defun org-current-time ()
3141 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
3142 (if (> (car org-time-stamp-rounding-minutes) 1)
3143 (let ((r (car org-time-stamp-rounding-minutes))
3144 (time (decode-time)))
3145 (apply 'encode-time
3146 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
3147 (nthcdr 2 time))))
3148 (current-time)))
3150 ;;;; Font-Lock stuff, including the activators
3152 (defvar org-mouse-map (make-sparse-keymap))
3153 (org-defkey org-mouse-map
3154 (if (featurep 'xemacs) [button2] [mouse-2]) 'org-open-at-mouse)
3155 (org-defkey org-mouse-map
3156 (if (featurep 'xemacs) [button3] [mouse-3]) 'org-find-file-at-mouse)
3157 (when org-mouse-1-follows-link
3158 (org-defkey org-mouse-map [follow-link] 'mouse-face))
3159 (when org-tab-follows-link
3160 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
3161 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
3162 (when org-return-follows-link
3163 (org-defkey org-mouse-map [(return)] 'org-open-at-point)
3164 (org-defkey org-mouse-map "\C-m" 'org-open-at-point))
3166 (require 'font-lock)
3168 (defconst org-non-link-chars "]\t\n\r<>")
3169 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
3170 "shell" "elisp"))
3171 (defvar org-link-types-re nil
3172 "Matches a link that has a url-like prefix like \"http:\"")
3173 (defvar org-link-re-with-space nil
3174 "Matches a link with spaces, optional angular brackets around it.")
3175 (defvar org-link-re-with-space2 nil
3176 "Matches a link with spaces, optional angular brackets around it.")
3177 (defvar org-angle-link-re nil
3178 "Matches link with angular brackets, spaces are allowed.")
3179 (defvar org-plain-link-re nil
3180 "Matches plain link, without spaces.")
3181 (defvar org-bracket-link-regexp nil
3182 "Matches a link in double brackets.")
3183 (defvar org-bracket-link-analytic-regexp nil
3184 "Regular expression used to analyze links.
3185 Here is what the match groups contain after a match:
3186 1: http:
3187 2: http
3188 3: path
3189 4: [desc]
3190 5: desc")
3191 (defvar org-any-link-re nil
3192 "Regular expression matching any link.")
3194 (defun org-make-link-regexps ()
3195 "Update the link regular expressions.
3196 This should be called after the variable `org-link-types' has changed."
3197 (setq org-link-types-re
3198 (concat
3199 "\\`\\(" (mapconcat 'identity org-link-types "\\|") "\\):")
3200 org-link-re-with-space
3201 (concat
3202 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3203 "\\([^" org-non-link-chars " ]"
3204 "[^" org-non-link-chars "]*"
3205 "[^" org-non-link-chars " ]\\)>?")
3206 org-link-re-with-space2
3207 (concat
3208 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3209 "\\([^" org-non-link-chars " ]"
3210 "[^]\t\n\r]*"
3211 "[^" org-non-link-chars " ]\\)>?")
3212 org-angle-link-re
3213 (concat
3214 "<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3215 "\\([^" org-non-link-chars " ]"
3216 "[^" org-non-link-chars "]*"
3217 "\\)>")
3218 org-plain-link-re
3219 (concat
3220 "\\<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3221 "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
3222 org-bracket-link-regexp
3223 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
3224 org-bracket-link-analytic-regexp
3225 (concat
3226 "\\[\\["
3227 "\\(\\(" (mapconcat 'identity org-link-types "\\|") "\\):\\)?"
3228 "\\([^]]+\\)"
3229 "\\]"
3230 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
3231 "\\]")
3232 org-any-link-re
3233 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
3234 org-angle-link-re "\\)\\|\\("
3235 org-plain-link-re "\\)")))
3237 (org-make-link-regexps)
3239 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)>"
3240 "Regular expression for fast time stamp matching.")
3241 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)[]>]"
3242 "Regular expression for fast time stamp matching.")
3243 (defconst org-ts-regexp0 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
3244 "Regular expression matching time strings for analysis.
3245 This one does not require the space after the date, so it can be used
3246 on a string that terminates immediately after the date.")
3247 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) +\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
3248 "Regular expression matching time strings for analysis.")
3249 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
3250 "Regular expression matching time stamps, with groups.")
3251 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
3252 "Regular expression matching time stamps (also [..]), with groups.")
3253 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
3254 "Regular expression matching a time stamp range.")
3255 (defconst org-tr-regexp-both
3256 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
3257 "Regular expression matching a time stamp range.")
3258 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
3259 org-ts-regexp "\\)?")
3260 "Regular expression matching a time stamp or time stamp range.")
3261 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
3262 org-ts-regexp-both "\\)?")
3263 "Regular expression matching a time stamp or time stamp range.
3264 The time stamps may be either active or inactive.")
3266 (defvar org-emph-face nil)
3268 (defun org-do-emphasis-faces (limit)
3269 "Run through the buffer and add overlays to links."
3270 (let (rtn)
3271 (while (and (not rtn) (re-search-forward org-emph-re limit t))
3272 (if (not (= (char-after (match-beginning 3))
3273 (char-after (match-beginning 4))))
3274 (progn
3275 (setq rtn t)
3276 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
3277 'face
3278 (nth 1 (assoc (match-string 3)
3279 org-emphasis-alist)))
3280 (add-text-properties (match-beginning 2) (match-end 2)
3281 '(font-lock-multiline t))
3282 (when org-hide-emphasis-markers
3283 (add-text-properties (match-end 4) (match-beginning 5)
3284 '(invisible org-link))
3285 (add-text-properties (match-beginning 3) (match-end 3)
3286 '(invisible org-link)))))
3287 (backward-char 1))
3288 rtn))
3290 (defun org-emphasize (&optional char)
3291 "Insert or change an emphasis, i.e. a font like bold or italic.
3292 If there is an active region, change that region to a new emphasis.
3293 If there is no region, just insert the marker characters and position
3294 the cursor between them.
3295 CHAR should be either the marker character, or the first character of the
3296 HTML tag associated with that emphasis. If CHAR is a space, the means
3297 to remove the emphasis of the selected region.
3298 If char is not given (for example in an interactive call) it
3299 will be prompted for."
3300 (interactive)
3301 (let ((eal org-emphasis-alist) e det
3302 (erc org-emphasis-regexp-components)
3303 (prompt "")
3304 (string "") beg end move tag c s)
3305 (if (org-region-active-p)
3306 (setq beg (region-beginning) end (region-end)
3307 string (buffer-substring beg end))
3308 (setq move t))
3310 (while (setq e (pop eal))
3311 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
3312 c (aref tag 0))
3313 (push (cons c (string-to-char (car e))) det)
3314 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
3315 (substring tag 1)))))
3316 (unless char
3317 (message "%s" (concat "Emphasis marker or tag:" prompt))
3318 (setq char (read-char-exclusive)))
3319 (setq char (or (cdr (assoc char det)) char))
3320 (if (equal char ?\ )
3321 (setq s "" move nil)
3322 (unless (assoc (char-to-string char) org-emphasis-alist)
3323 (error "No such emphasis marker: \"%c\"" char))
3324 (setq s (char-to-string char)))
3325 (while (and (> (length string) 1)
3326 (equal (substring string 0 1) (substring string -1))
3327 (assoc (substring string 0 1) org-emphasis-alist))
3328 (setq string (substring string 1 -1)))
3329 (setq string (concat s string s))
3330 (if beg (delete-region beg end))
3331 (unless (or (bolp)
3332 (string-match (concat "[" (nth 0 erc) "\n]")
3333 (char-to-string (char-before (point)))))
3334 (insert " "))
3335 (unless (string-match (concat "[" (nth 1 erc) "\n]")
3336 (char-to-string (char-after (point))))
3337 (insert " ") (backward-char 1))
3338 (insert string)
3339 (and move (backward-char 1))))
3341 (defconst org-nonsticky-props
3342 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
3345 (defun org-activate-plain-links (limit)
3346 "Run through the buffer and add overlays to links."
3347 (catch 'exit
3348 (let (f)
3349 (while (re-search-forward org-plain-link-re limit t)
3350 (setq f (get-text-property (match-beginning 0) 'face))
3351 (if (or (eq f 'org-tag)
3352 (and (listp f) (memq 'org-tag f)))
3354 (add-text-properties (match-beginning 0) (match-end 0)
3355 (list 'mouse-face 'highlight
3356 'rear-nonsticky org-nonsticky-props
3357 'keymap org-mouse-map
3359 (throw 'exit t))))))
3361 (defun org-activate-code (limit)
3362 (if (re-search-forward "^[ \t]*\\(:.*\\)" limit t)
3363 (unless (get-text-property (match-beginning 1) 'face)
3364 (remove-text-properties (match-beginning 0) (match-end 0)
3365 '(display t invisible t intangible t))
3366 t)))
3368 (defun org-activate-angle-links (limit)
3369 "Run through the buffer and add overlays to links."
3370 (if (re-search-forward org-angle-link-re limit t)
3371 (progn
3372 (add-text-properties (match-beginning 0) (match-end 0)
3373 (list 'mouse-face 'highlight
3374 'rear-nonsticky org-nonsticky-props
3375 'keymap org-mouse-map
3377 t)))
3379 (defun org-activate-bracket-links (limit)
3380 "Run through the buffer and add overlays to bracketed links."
3381 (if (re-search-forward org-bracket-link-regexp limit t)
3382 (let* ((help (concat "LINK: "
3383 (org-match-string-no-properties 1)))
3384 ;; FIXME: above we should remove the escapes.
3385 ;; but that requires another match, protecting match data,
3386 ;; a lot of overhead for font-lock.
3387 (ip (org-maybe-intangible
3388 (list 'invisible 'org-link 'rear-nonsticky org-nonsticky-props
3389 'keymap org-mouse-map 'mouse-face 'highlight
3390 'font-lock-multiline t 'help-echo help)))
3391 (vp (list 'rear-nonsticky org-nonsticky-props
3392 'keymap org-mouse-map 'mouse-face 'highlight
3393 ' font-lock-multiline t 'help-echo help)))
3394 ;; We need to remove the invisible property here. Table narrowing
3395 ;; may have made some of this invisible.
3396 (remove-text-properties (match-beginning 0) (match-end 0)
3397 '(invisible nil))
3398 (if (match-end 3)
3399 (progn
3400 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
3401 (add-text-properties (match-beginning 3) (match-end 3) vp)
3402 (add-text-properties (match-end 3) (match-end 0) ip))
3403 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
3404 (add-text-properties (match-beginning 1) (match-end 1) vp)
3405 (add-text-properties (match-end 1) (match-end 0) ip))
3406 t)))
3408 (defun org-activate-dates (limit)
3409 "Run through the buffer and add overlays to dates."
3410 (if (re-search-forward org-tsr-regexp-both limit t)
3411 (progn
3412 (add-text-properties (match-beginning 0) (match-end 0)
3413 (list 'mouse-face 'highlight
3414 'rear-nonsticky org-nonsticky-props
3415 'keymap org-mouse-map))
3416 (when org-display-custom-times
3417 (if (match-end 3)
3418 (org-display-custom-time (match-beginning 3) (match-end 3)))
3419 (org-display-custom-time (match-beginning 1) (match-end 1)))
3420 t)))
3422 (defvar org-target-link-regexp nil
3423 "Regular expression matching radio targets in plain text.")
3424 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
3425 "Regular expression matching a link target.")
3426 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
3427 "Regular expression matching a radio target.")
3428 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
3429 "Regular expression matching any target.")
3431 (defun org-activate-target-links (limit)
3432 "Run through the buffer and add overlays to target matches."
3433 (when org-target-link-regexp
3434 (let ((case-fold-search t))
3435 (if (re-search-forward org-target-link-regexp limit t)
3436 (progn
3437 (add-text-properties (match-beginning 0) (match-end 0)
3438 (list 'mouse-face 'highlight
3439 'rear-nonsticky org-nonsticky-props
3440 'keymap org-mouse-map
3441 'help-echo "Radio target link"
3442 'org-linked-text t))
3443 t)))))
3445 (defun org-update-radio-target-regexp ()
3446 "Find all radio targets in this file and update the regular expression."
3447 (interactive)
3448 (when (memq 'radio org-activate-links)
3449 (setq org-target-link-regexp
3450 (org-make-target-link-regexp (org-all-targets 'radio)))
3451 (org-restart-font-lock)))
3453 (defun org-hide-wide-columns (limit)
3454 (let (s e)
3455 (setq s (text-property-any (point) (or limit (point-max))
3456 'org-cwidth t))
3457 (when s
3458 (setq e (next-single-property-change s 'org-cwidth))
3459 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
3460 (goto-char e)
3461 t)))
3463 (defvar org-latex-and-specials-regexp nil
3464 "Regular expression for highlighting export special stuff.")
3465 (defvar org-match-substring-regexp)
3466 (defvar org-match-substring-with-braces-regexp)
3467 (defvar org-export-html-special-string-regexps)
3469 (defun org-compute-latex-and-specials-regexp ()
3470 "Compute regular expression for stuff treated specially by exporters."
3471 (if (not org-highlight-latex-fragments-and-specials)
3472 (org-set-local 'org-latex-and-specials-regexp nil)
3473 (require 'org-exp)
3474 (let*
3475 ((matchers (plist-get org-format-latex-options :matchers))
3476 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
3477 org-latex-regexps)))
3478 (options (org-combine-plists (org-default-export-plist)
3479 (org-infile-export-plist)))
3480 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
3481 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
3482 (org-export-with-TeX-macros (plist-get options :TeX-macros))
3483 (org-export-html-expand (plist-get options :expand-quoted-html))
3484 (org-export-with-special-strings (plist-get options :special-strings))
3485 (re-sub
3486 (cond
3487 ((equal org-export-with-sub-superscripts '{})
3488 (list org-match-substring-with-braces-regexp))
3489 (org-export-with-sub-superscripts
3490 (list org-match-substring-regexp))
3491 (t nil)))
3492 (re-latex
3493 (if org-export-with-LaTeX-fragments
3494 (mapcar (lambda (x) (nth 1 x)) latexs)))
3495 (re-macros
3496 (if org-export-with-TeX-macros
3497 (list (concat "\\\\"
3498 (regexp-opt
3499 (append (mapcar 'car org-html-entities)
3500 (if (boundp 'org-latex-entities)
3501 org-latex-entities nil))
3502 'words))) ; FIXME
3504 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
3505 (re-special (if org-export-with-special-strings
3506 (mapcar (lambda (x) (car x))
3507 org-export-html-special-string-regexps)))
3508 (re-rest
3509 (delq nil
3510 (list
3511 (if org-export-html-expand "@<[^>\n]+>")
3512 ))))
3513 (org-set-local
3514 'org-latex-and-specials-regexp
3515 (mapconcat 'identity (append re-latex re-sub re-macros re-special
3516 re-rest) "\\|")))))
3518 (defun org-do-latex-and-special-faces (limit)
3519 "Run through the buffer and add overlays to links."
3520 (when org-latex-and-specials-regexp
3521 (let (rtn d)
3522 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
3523 limit t))
3524 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
3525 'face))
3526 '(org-code org-verbatim underline)))
3527 (progn
3528 (setq rtn t
3529 d (cond ((member (char-after (1+ (match-beginning 0)))
3530 '(?_ ?^)) 1)
3531 (t 0)))
3532 (font-lock-prepend-text-property
3533 (+ d (match-beginning 0)) (match-end 0)
3534 'face 'org-latex-and-export-specials)
3535 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
3536 '(font-lock-multiline t)))))
3537 rtn)))
3539 (defun org-restart-font-lock ()
3540 "Restart font-lock-mode, to force refontification."
3541 (when (and (boundp 'font-lock-mode) font-lock-mode)
3542 (font-lock-mode -1)
3543 (font-lock-mode 1)))
3545 (defun org-all-targets (&optional radio)
3546 "Return a list of all targets in this file.
3547 With optional argument RADIO, only find radio targets."
3548 (let ((re (if radio org-radio-target-regexp org-target-regexp))
3549 rtn)
3550 (save-excursion
3551 (goto-char (point-min))
3552 (while (re-search-forward re nil t)
3553 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
3554 rtn)))
3556 (defun org-make-target-link-regexp (targets)
3557 "Make regular expression matching all strings in TARGETS.
3558 The regular expression finds the targets also if there is a line break
3559 between words."
3560 (and targets
3561 (concat
3562 "\\<\\("
3563 (mapconcat
3564 (lambda (x)
3565 (while (string-match " +" x)
3566 (setq x (replace-match "\\s-+" t t x)))
3568 targets
3569 "\\|")
3570 "\\)\\>")))
3572 (defun org-activate-tags (limit)
3573 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \r\n]") limit t)
3574 (progn
3575 (add-text-properties (match-beginning 1) (match-end 1)
3576 (list 'mouse-face 'highlight
3577 'rear-nonsticky org-nonsticky-props
3578 'keymap org-mouse-map))
3579 t)))
3581 (defun org-outline-level ()
3582 (save-excursion
3583 (looking-at outline-regexp)
3584 (if (match-beginning 1)
3585 (+ (org-get-string-indentation (match-string 1)) 1000)
3586 (1- (- (match-end 0) (match-beginning 0))))))
3588 (defvar org-font-lock-keywords nil)
3590 (defconst org-property-re (org-re "^[ \t]*\\(:\\([[:alnum:]_]+\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
3591 "Regular expression matching a property line.")
3593 (defvar org-font-lock-hook nil
3594 "Functions to be called for special font loch stuff.")
3596 (defun org-font-lock-hook (limit)
3597 (run-hook-with-args 'org-font-lock-hook limit))
3599 (defun org-set-font-lock-defaults ()
3600 (let* ((em org-fontify-emphasized-text)
3601 (lk org-activate-links)
3602 (org-font-lock-extra-keywords
3603 (list
3604 ;; Call the hook
3605 '(org-font-lock-hook)
3606 ;; Headlines
3607 '("^\\(\\**\\)\\(\\* \\)\\(.*\\)" (1 (org-get-level-face 1))
3608 (2 (org-get-level-face 2)) (3 (org-get-level-face 3)))
3609 ;; Table lines
3610 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
3611 (1 'org-table t))
3612 ;; Table internals
3613 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
3614 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
3615 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
3616 ;; Drawers
3617 (list org-drawer-regexp '(0 'org-special-keyword t))
3618 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
3619 ;; Properties
3620 (list org-property-re
3621 '(1 'org-special-keyword t)
3622 '(3 'org-property-value t))
3623 (if org-format-transports-properties-p
3624 '("| *\\(<[0-9]+>\\) *" (1 'org-formula t)))
3625 ;; Links
3626 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
3627 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
3628 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
3629 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
3630 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
3631 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
3632 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
3633 '(org-hide-wide-columns (0 nil append))
3634 ;; TODO lines
3635 (list (concat "^\\*+[ \t]+" org-todo-regexp)
3636 '(1 (org-get-todo-face 1) t))
3637 ;; DONE
3638 (if org-fontify-done-headline
3639 (list (concat "^[*]+ +\\<\\("
3640 (mapconcat 'regexp-quote org-done-keywords "\\|")
3641 "\\)\\(.*\\)")
3642 '(2 'org-headline-done t))
3643 nil)
3644 ;; Priorities
3645 (list (concat "\\[#[A-Z0-9]\\]") '(0 'org-special-keyword t))
3646 ;; Special keywords
3647 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
3648 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
3649 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
3650 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
3651 ;; Emphasis
3652 (if em
3653 (if (featurep 'xemacs)
3654 '(org-do-emphasis-faces (0 nil append))
3655 '(org-do-emphasis-faces)))
3656 ;; Checkboxes
3657 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)"
3658 2 'bold prepend)
3659 (if org-provide-checkbox-statistics
3660 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
3661 (0 (org-get-checkbox-statistics-face) t)))
3662 (list (concat "^\\*+ \\(.*:" org-archive-tag ":.*\\)")
3663 '(1 'org-archived prepend))
3664 ;; Specials
3665 '(org-do-latex-and-special-faces)
3666 ;; Code
3667 '(org-activate-code (1 'org-code t))
3668 ;; COMMENT
3669 (list (concat "^\\*+[ \t]+\\<\\(" org-comment-string
3670 "\\|" org-quote-string "\\)\\>")
3671 '(1 'org-special-keyword t))
3672 '("^#.*" (0 'font-lock-comment-face t))
3674 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
3675 ;; Now set the full font-lock-keywords
3676 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
3677 (org-set-local 'font-lock-defaults
3678 '(org-font-lock-keywords t nil nil backward-paragraph))
3679 (kill-local-variable 'font-lock-keywords) nil))
3681 (defvar org-m nil)
3682 (defvar org-l nil)
3683 (defvar org-f nil)
3684 (defun org-get-level-face (n)
3685 "Get the right face for match N in font-lock matching of healdines."
3686 (setq org-l (- (match-end 2) (match-beginning 1) 1))
3687 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
3688 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
3689 (cond
3690 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
3691 ((eq n 2) org-f)
3692 (t (if org-level-color-stars-only nil org-f))))
3694 (defun org-get-todo-face (kwd)
3695 "Get the right face for a TODO keyword KWD.
3696 If KWD is a number, get the corresponding match group."
3697 (if (numberp kwd) (setq kwd (match-string kwd)))
3698 (or (cdr (assoc kwd org-todo-keyword-faces))
3699 (and (member kwd org-done-keywords) 'org-done)
3700 'org-todo))
3702 (defun org-unfontify-region (beg end &optional maybe_loudly)
3703 "Remove fontification and activation overlays from links."
3704 (font-lock-default-unfontify-region beg end)
3705 (let* ((buffer-undo-list t)
3706 (inhibit-read-only t) (inhibit-point-motion-hooks t)
3707 (inhibit-modification-hooks t)
3708 deactivate-mark buffer-file-name buffer-file-truename)
3709 (remove-text-properties beg end
3710 '(mouse-face t keymap t org-linked-text t
3711 invisible t intangible t))))
3713 ;;;; Visibility cycling, including org-goto and indirect buffer
3715 ;;; Cycling
3717 (defvar org-cycle-global-status nil)
3718 (make-variable-buffer-local 'org-cycle-global-status)
3719 (defvar org-cycle-subtree-status nil)
3720 (make-variable-buffer-local 'org-cycle-subtree-status)
3722 ;;;###autoload
3723 (defun org-cycle (&optional arg)
3724 "Visibility cycling for Org-mode.
3726 - When this function is called with a prefix argument, rotate the entire
3727 buffer through 3 states (global cycling)
3728 1. OVERVIEW: Show only top-level headlines.
3729 2. CONTENTS: Show all headlines of all levels, but no body text.
3730 3. SHOW ALL: Show everything.
3732 - When point is at the beginning of a headline, rotate the subtree started
3733 by this line through 3 different states (local cycling)
3734 1. FOLDED: Only the main headline is shown.
3735 2. CHILDREN: The main headline and the direct children are shown.
3736 From this state, you can move to one of the children
3737 and zoom in further.
3738 3. SUBTREE: Show the entire subtree, including body text.
3740 - When there is a numeric prefix, go up to a heading with level ARG, do
3741 a `show-subtree' and return to the previous cursor position. If ARG
3742 is negative, go up that many levels.
3744 - When point is not at the beginning of a headline, execute
3745 `indent-relative', like TAB normally does. See the option
3746 `org-cycle-emulate-tab' for details.
3748 - Special case: if point is at the beginning of the buffer and there is
3749 no headline in line 1, this function will act as if called with prefix arg.
3750 But only if also the variable `org-cycle-global-at-bob' is t."
3751 (interactive "P")
3752 (org-load-modules-maybe)
3753 (let* ((outline-regexp
3754 (if (and (org-mode-p) org-cycle-include-plain-lists)
3755 "\\(?:\\*+ \\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) \\)"
3756 outline-regexp))
3757 (bob-special (and org-cycle-global-at-bob (bobp)
3758 (not (looking-at outline-regexp))))
3759 (org-cycle-hook
3760 (if bob-special
3761 (delq 'org-optimize-window-after-visibility-change
3762 (copy-sequence org-cycle-hook))
3763 org-cycle-hook))
3764 (pos (point)))
3766 (if (or bob-special (equal arg '(4)))
3767 ;; special case: use global cycling
3768 (setq arg t))
3770 (cond
3772 ((org-at-table-p 'any)
3773 ;; Enter the table or move to the next field in the table
3774 (or (org-table-recognize-table.el)
3775 (progn
3776 (if arg (org-table-edit-field t)
3777 (org-table-justify-field-maybe)
3778 (call-interactively 'org-table-next-field)))))
3780 ((eq arg t) ;; Global cycling
3782 (cond
3783 ((and (eq last-command this-command)
3784 (eq org-cycle-global-status 'overview))
3785 ;; We just created the overview - now do table of contents
3786 ;; This can be slow in very large buffers, so indicate action
3787 (message "CONTENTS...")
3788 (org-content)
3789 (message "CONTENTS...done")
3790 (setq org-cycle-global-status 'contents)
3791 (run-hook-with-args 'org-cycle-hook 'contents))
3793 ((and (eq last-command this-command)
3794 (eq org-cycle-global-status 'contents))
3795 ;; We just showed the table of contents - now show everything
3796 (show-all)
3797 (message "SHOW ALL")
3798 (setq org-cycle-global-status 'all)
3799 (run-hook-with-args 'org-cycle-hook 'all))
3802 ;; Default action: go to overview
3803 (org-overview)
3804 (message "OVERVIEW")
3805 (setq org-cycle-global-status 'overview)
3806 (run-hook-with-args 'org-cycle-hook 'overview))))
3808 ((and org-drawers org-drawer-regexp
3809 (save-excursion
3810 (beginning-of-line 1)
3811 (looking-at org-drawer-regexp)))
3812 ;; Toggle block visibility
3813 (org-flag-drawer
3814 (not (get-char-property (match-end 0) 'invisible))))
3816 ((integerp arg)
3817 ;; Show-subtree, ARG levels up from here.
3818 (save-excursion
3819 (org-back-to-heading)
3820 (outline-up-heading (if (< arg 0) (- arg)
3821 (- (funcall outline-level) arg)))
3822 (org-show-subtree)))
3824 ((and (save-excursion (beginning-of-line 1) (looking-at outline-regexp))
3825 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
3826 ;; At a heading: rotate between three different views
3827 (org-back-to-heading)
3828 (let ((goal-column 0) eoh eol eos)
3829 ;; First, some boundaries
3830 (save-excursion
3831 (org-back-to-heading)
3832 (save-excursion
3833 (beginning-of-line 2)
3834 (while (and (not (eobp)) ;; this is like `next-line'
3835 (get-char-property (1- (point)) 'invisible))
3836 (beginning-of-line 2)) (setq eol (point)))
3837 (outline-end-of-heading) (setq eoh (point))
3838 (org-end-of-subtree t)
3839 (unless (eobp)
3840 (skip-chars-forward " \t\n")
3841 (beginning-of-line 1) ; in case this is an item
3843 (setq eos (1- (point))))
3844 ;; Find out what to do next and set `this-command'
3845 (cond
3846 ((= eos eoh)
3847 ;; Nothing is hidden behind this heading
3848 (message "EMPTY ENTRY")
3849 (setq org-cycle-subtree-status nil)
3850 (save-excursion
3851 (goto-char eos)
3852 (outline-next-heading)
3853 (if (org-invisible-p) (org-flag-heading nil))))
3854 ((or (>= eol eos)
3855 (not (string-match "\\S-" (buffer-substring eol eos))))
3856 ;; Entire subtree is hidden in one line: open it
3857 (org-show-entry)
3858 (show-children)
3859 (message "CHILDREN")
3860 (save-excursion
3861 (goto-char eos)
3862 (outline-next-heading)
3863 (if (org-invisible-p) (org-flag-heading nil)))
3864 (setq org-cycle-subtree-status 'children)
3865 (run-hook-with-args 'org-cycle-hook 'children))
3866 ((and (eq last-command this-command)
3867 (eq org-cycle-subtree-status 'children))
3868 ;; We just showed the children, now show everything.
3869 (org-show-subtree)
3870 (message "SUBTREE")
3871 (setq org-cycle-subtree-status 'subtree)
3872 (run-hook-with-args 'org-cycle-hook 'subtree))
3874 ;; Default action: hide the subtree.
3875 (hide-subtree)
3876 (message "FOLDED")
3877 (setq org-cycle-subtree-status 'folded)
3878 (run-hook-with-args 'org-cycle-hook 'folded)))))
3880 ;; TAB emulation
3881 (buffer-read-only (org-back-to-heading))
3883 ((org-try-cdlatex-tab))
3885 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
3886 (or (not (bolp))
3887 (not (looking-at outline-regexp))))
3888 (call-interactively (global-key-binding "\t")))
3890 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
3891 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
3892 (or (and (eq org-cycle-emulate-tab 'white)
3893 (= (match-end 0) (point-at-eol)))
3894 (and (eq org-cycle-emulate-tab 'whitestart)
3895 (>= (match-end 0) pos))))
3897 (eq org-cycle-emulate-tab t))
3898 (call-interactively (global-key-binding "\t")))
3900 (t (save-excursion
3901 (org-back-to-heading)
3902 (org-cycle))))))
3904 ;;;###autoload
3905 (defun org-global-cycle (&optional arg)
3906 "Cycle the global visibility. For details see `org-cycle'."
3907 (interactive "P")
3908 (let ((org-cycle-include-plain-lists
3909 (if (org-mode-p) org-cycle-include-plain-lists nil)))
3910 (if (integerp arg)
3911 (progn
3912 (show-all)
3913 (hide-sublevels arg)
3914 (setq org-cycle-global-status 'contents))
3915 (org-cycle '(4)))))
3917 (defun org-overview ()
3918 "Switch to overview mode, shoing only top-level headlines.
3919 Really, this shows all headlines with level equal or greater than the level
3920 of the first headline in the buffer. This is important, because if the
3921 first headline is not level one, then (hide-sublevels 1) gives confusing
3922 results."
3923 (interactive)
3924 (let ((level (save-excursion
3925 (goto-char (point-min))
3926 (if (re-search-forward (concat "^" outline-regexp) nil t)
3927 (progn
3928 (goto-char (match-beginning 0))
3929 (funcall outline-level))))))
3930 (and level (hide-sublevels level))))
3932 (defun org-content (&optional arg)
3933 "Show all headlines in the buffer, like a table of contents.
3934 With numerical argument N, show content up to level N."
3935 (interactive "P")
3936 (save-excursion
3937 ;; Visit all headings and show their offspring
3938 (and (integerp arg) (org-overview))
3939 (goto-char (point-max))
3940 (catch 'exit
3941 (while (and (progn (condition-case nil
3942 (outline-previous-visible-heading 1)
3943 (error (goto-char (point-min))))
3945 (looking-at outline-regexp))
3946 (if (integerp arg)
3947 (show-children (1- arg))
3948 (show-branches))
3949 (if (bobp) (throw 'exit nil))))))
3952 (defun org-optimize-window-after-visibility-change (state)
3953 "Adjust the window after a change in outline visibility.
3954 This function is the default value of the hook `org-cycle-hook'."
3955 (when (get-buffer-window (current-buffer))
3956 (cond
3957 ; ((eq state 'overview) (org-first-headline-recenter 1))
3958 ; ((eq state 'overview) (org-beginning-of-line))
3959 ((eq state 'content) nil)
3960 ((eq state 'all) nil)
3961 ((eq state 'folded) nil)
3962 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
3963 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
3965 (defun org-compact-display-after-subtree-move ()
3966 (let (beg end)
3967 (save-excursion
3968 (if (org-up-heading-safe)
3969 (progn
3970 (hide-subtree)
3971 (show-entry)
3972 (show-children)
3973 (org-cycle-show-empty-lines 'children)
3974 (org-cycle-hide-drawers 'children))
3975 (org-overview)))))
3977 (defun org-cycle-show-empty-lines (state)
3978 "Show empty lines above all visible headlines.
3979 The region to be covered depends on STATE when called through
3980 `org-cycle-hook'. Lisp program can use t for STATE to get the
3981 entire buffer covered. Note that an empty line is only shown if there
3982 are at least `org-cycle-separator-lines' empty lines before the headeline."
3983 (when (> org-cycle-separator-lines 0)
3984 (save-excursion
3985 (let* ((n org-cycle-separator-lines)
3986 (re (cond
3987 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
3988 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
3989 (t (let ((ns (number-to-string (- n 2))))
3990 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
3991 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
3992 beg end)
3993 (cond
3994 ((memq state '(overview contents t))
3995 (setq beg (point-min) end (point-max)))
3996 ((memq state '(children folded))
3997 (setq beg (point) end (progn (org-end-of-subtree t t)
3998 (beginning-of-line 2)
3999 (point)))))
4000 (when beg
4001 (goto-char beg)
4002 (while (re-search-forward re end t)
4003 (if (not (get-char-property (match-end 1) 'invisible))
4004 (outline-flag-region
4005 (match-beginning 1) (match-end 1) nil)))))))
4006 ;; Never hide empty lines at the end of the file.
4007 (save-excursion
4008 (goto-char (point-max))
4009 (outline-previous-heading)
4010 (outline-end-of-heading)
4011 (if (and (looking-at "[ \t\n]+")
4012 (= (match-end 0) (point-max)))
4013 (outline-flag-region (point) (match-end 0) nil))))
4015 (defun org-cycle-hide-drawers (state)
4016 "Re-hide all drawers after a visibility state change."
4017 (when (and (org-mode-p)
4018 (not (memq state '(overview folded))))
4019 (save-excursion
4020 (let* ((globalp (memq state '(contents all)))
4021 (beg (if globalp (point-min) (point)))
4022 (end (if globalp (point-max) (org-end-of-subtree t))))
4023 (goto-char beg)
4024 (while (re-search-forward org-drawer-regexp end t)
4025 (org-flag-drawer t))))))
4027 (defun org-flag-drawer (flag)
4028 (save-excursion
4029 (beginning-of-line 1)
4030 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
4031 (let ((b (match-end 0))
4032 (outline-regexp org-outline-regexp))
4033 (if (re-search-forward
4034 "^[ \t]*:END:"
4035 (save-excursion (outline-next-heading) (point)) t)
4036 (outline-flag-region b (point-at-eol) flag)
4037 (error ":END: line missing"))))))
4041 (defun org-subtree-end-visible-p ()
4042 "Is the end of the current subtree visible?"
4043 (pos-visible-in-window-p
4044 (save-excursion (org-end-of-subtree t) (point))))
4046 (defun org-first-headline-recenter (&optional N)
4047 "Move cursor to the first headline and recenter the headline.
4048 Optional argument N means, put the headline into the Nth line of the window."
4049 (goto-char (point-min))
4050 (when (re-search-forward (concat "^\\(" outline-regexp "\\)") nil t)
4051 (beginning-of-line)
4052 (recenter (prefix-numeric-value N))))
4054 ;;; Org-goto
4056 (defvar org-goto-window-configuration nil)
4057 (defvar org-goto-marker nil)
4058 (defvar org-goto-map
4059 (let ((map (make-sparse-keymap)))
4060 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
4061 (while (setq cmd (pop cmds))
4062 (substitute-key-definition cmd cmd map global-map)))
4063 (suppress-keymap map)
4064 (org-defkey map "\C-m" 'org-goto-ret)
4065 (org-defkey map [(return)] 'org-goto-ret)
4066 (org-defkey map [(left)] 'org-goto-left)
4067 (org-defkey map [(right)] 'org-goto-right)
4068 (org-defkey map [(control ?g)] 'org-goto-quit)
4069 (org-defkey map "\C-i" 'org-cycle)
4070 (org-defkey map [(tab)] 'org-cycle)
4071 (org-defkey map [(down)] 'outline-next-visible-heading)
4072 (org-defkey map [(up)] 'outline-previous-visible-heading)
4073 (if org-goto-auto-isearch
4074 (if (fboundp 'define-key-after)
4075 (define-key-after map [t] 'org-goto-local-auto-isearch)
4076 nil)
4077 (org-defkey map "q" 'org-goto-quit)
4078 (org-defkey map "n" 'outline-next-visible-heading)
4079 (org-defkey map "p" 'outline-previous-visible-heading)
4080 (org-defkey map "f" 'outline-forward-same-level)
4081 (org-defkey map "b" 'outline-backward-same-level)
4082 (org-defkey map "u" 'outline-up-heading))
4083 (org-defkey map "/" 'org-occur)
4084 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
4085 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
4086 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
4087 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
4088 (org-defkey map "\C-c\C-u" 'outline-up-heading)
4089 map))
4091 (defconst org-goto-help
4092 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
4093 RET=jump to location [Q]uit and return to previous location
4094 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
4096 (defvar org-goto-start-pos) ; dynamically scoped parameter
4098 (defun org-goto (&optional alternative-interface)
4099 "Look up a different location in the current file, keeping current visibility.
4101 When you want look-up or go to a different location in a document, the
4102 fastest way is often to fold the entire buffer and then dive into the tree.
4103 This method has the disadvantage, that the previous location will be folded,
4104 which may not be what you want.
4106 This command works around this by showing a copy of the current buffer
4107 in an indirect buffer, in overview mode. You can dive into the tree in
4108 that copy, use org-occur and incremental search to find a location.
4109 When pressing RET or `Q', the command returns to the original buffer in
4110 which the visibility is still unchanged. After RET is will also jump to
4111 the location selected in the indirect buffer and expose the
4112 the headline hierarchy above."
4113 (interactive "P")
4114 (let* ((org-refile-targets '((nil . (:maxlevel . 10))))
4115 (org-refile-use-outline-path t)
4116 (interface
4117 (if (not alternative-interface)
4118 org-goto-interface
4119 (if (eq org-goto-interface 'outline)
4120 'outline-path-completion
4121 'outline)))
4122 (org-goto-start-pos (point))
4123 (selected-point
4124 (if (eq interface 'outline)
4125 (car (org-get-location (current-buffer) org-goto-help))
4126 (nth 3 (org-refile-get-location "Goto: ")))))
4127 (if selected-point
4128 (progn
4129 (org-mark-ring-push org-goto-start-pos)
4130 (goto-char selected-point)
4131 (if (or (org-invisible-p) (org-invisible-p2))
4132 (org-show-context 'org-goto)))
4133 (message "Quit"))))
4135 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
4136 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
4137 (defvar org-goto-local-auto-isearch-map) ; defined below
4139 (defun org-get-location (buf help)
4140 "Let the user select a location in the Org-mode buffer BUF.
4141 This function uses a recursive edit. It returns the selected position
4142 or nil."
4143 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
4144 (isearch-hide-immediately nil)
4145 (isearch-search-fun-function
4146 (lambda () 'org-goto-local-search-forward-headings))
4147 (org-goto-selected-point org-goto-exit-command))
4148 (save-excursion
4149 (save-window-excursion
4150 (delete-other-windows)
4151 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
4152 (switch-to-buffer
4153 (condition-case nil
4154 (make-indirect-buffer (current-buffer) "*org-goto*")
4155 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
4156 (with-output-to-temp-buffer "*Help*"
4157 (princ help))
4158 (shrink-window-if-larger-than-buffer (get-buffer-window "*Help*"))
4159 (setq buffer-read-only nil)
4160 (let ((org-startup-truncated t)
4161 (org-startup-folded nil)
4162 (org-startup-align-all-tables nil))
4163 (org-mode)
4164 (org-overview))
4165 (setq buffer-read-only t)
4166 (if (and (boundp 'org-goto-start-pos)
4167 (integer-or-marker-p org-goto-start-pos))
4168 (let ((org-show-hierarchy-above t)
4169 (org-show-siblings t)
4170 (org-show-following-heading t))
4171 (goto-char org-goto-start-pos)
4172 (and (org-invisible-p) (org-show-context)))
4173 (goto-char (point-min)))
4174 (org-beginning-of-line)
4175 (message "Select location and press RET")
4176 (use-local-map org-goto-map)
4177 (recursive-edit)
4179 (kill-buffer "*org-goto*")
4180 (cons org-goto-selected-point org-goto-exit-command)))
4182 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
4183 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
4184 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
4185 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
4187 (defun org-goto-local-search-forward-headings (string bound noerror)
4188 "Search and make sure that anu matches are in headlines."
4189 (catch 'return
4190 (while (search-forward string bound noerror)
4191 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
4192 (and (member :headline context)
4193 (not (member :tags context))))
4194 (throw 'return (point))))))
4196 (defun org-goto-local-auto-isearch ()
4197 "Start isearch."
4198 (interactive)
4199 (goto-char (point-min))
4200 (let ((keys (this-command-keys)))
4201 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
4202 (isearch-mode t)
4203 (isearch-process-search-char (string-to-char keys)))))
4205 (defun org-goto-ret (&optional arg)
4206 "Finish `org-goto' by going to the new location."
4207 (interactive "P")
4208 (setq org-goto-selected-point (point)
4209 org-goto-exit-command 'return)
4210 (throw 'exit nil))
4212 (defun org-goto-left ()
4213 "Finish `org-goto' by going to the new location."
4214 (interactive)
4215 (if (org-on-heading-p)
4216 (progn
4217 (beginning-of-line 1)
4218 (setq org-goto-selected-point (point)
4219 org-goto-exit-command 'left)
4220 (throw 'exit nil))
4221 (error "Not on a heading")))
4223 (defun org-goto-right ()
4224 "Finish `org-goto' by going to the new location."
4225 (interactive)
4226 (if (org-on-heading-p)
4227 (progn
4228 (setq org-goto-selected-point (point)
4229 org-goto-exit-command 'right)
4230 (throw 'exit nil))
4231 (error "Not on a heading")))
4233 (defun org-goto-quit ()
4234 "Finish `org-goto' without cursor motion."
4235 (interactive)
4236 (setq org-goto-selected-point nil)
4237 (setq org-goto-exit-command 'quit)
4238 (throw 'exit nil))
4240 ;;; Indirect buffer display of subtrees
4242 (defvar org-indirect-dedicated-frame nil
4243 "This is the frame being used for indirect tree display.")
4244 (defvar org-last-indirect-buffer nil)
4246 (defun org-tree-to-indirect-buffer (&optional arg)
4247 "Create indirect buffer and narrow it to current subtree.
4248 With numerical prefix ARG, go up to this level and then take that tree.
4249 If ARG is negative, go up that many levels.
4250 If `org-indirect-buffer-display' is not `new-frame', the command removes the
4251 indirect buffer previously made with this command, to avoid proliferation of
4252 indirect buffers. However, when you call the command with a `C-u' prefix, or
4253 when `org-indirect-buffer-display' is `new-frame', the last buffer
4254 is kept so that you can work with several indirect buffers at the same time.
4255 If `org-indirect-buffer-display' is `dedicated-frame', the C-u prefix also
4256 requests that a new frame be made for the new buffer, so that the dedicated
4257 frame is not changed."
4258 (interactive "P")
4259 (let ((cbuf (current-buffer))
4260 (cwin (selected-window))
4261 (pos (point))
4262 beg end level heading ibuf)
4263 (save-excursion
4264 (org-back-to-heading t)
4265 (when (numberp arg)
4266 (setq level (org-outline-level))
4267 (if (< arg 0) (setq arg (+ level arg)))
4268 (while (> (setq level (org-outline-level)) arg)
4269 (outline-up-heading 1 t)))
4270 (setq beg (point)
4271 heading (org-get-heading))
4272 (org-end-of-subtree t) (setq end (point)))
4273 (if (and (buffer-live-p org-last-indirect-buffer)
4274 (not (eq org-indirect-buffer-display 'new-frame))
4275 (not arg))
4276 (kill-buffer org-last-indirect-buffer))
4277 (setq ibuf (org-get-indirect-buffer cbuf)
4278 org-last-indirect-buffer ibuf)
4279 (cond
4280 ((or (eq org-indirect-buffer-display 'new-frame)
4281 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
4282 (select-frame (make-frame))
4283 (delete-other-windows)
4284 (switch-to-buffer ibuf)
4285 (org-set-frame-title heading))
4286 ((eq org-indirect-buffer-display 'dedicated-frame)
4287 (raise-frame
4288 (select-frame (or (and org-indirect-dedicated-frame
4289 (frame-live-p org-indirect-dedicated-frame)
4290 org-indirect-dedicated-frame)
4291 (setq org-indirect-dedicated-frame (make-frame)))))
4292 (delete-other-windows)
4293 (switch-to-buffer ibuf)
4294 (org-set-frame-title (concat "Indirect: " heading)))
4295 ((eq org-indirect-buffer-display 'current-window)
4296 (switch-to-buffer ibuf))
4297 ((eq org-indirect-buffer-display 'other-window)
4298 (pop-to-buffer ibuf))
4299 (t (error "Invalid value.")))
4300 (if (featurep 'xemacs)
4301 (save-excursion (org-mode) (turn-on-font-lock)))
4302 (narrow-to-region beg end)
4303 (show-all)
4304 (goto-char pos)
4305 (and (window-live-p cwin) (select-window cwin))))
4307 (defun org-get-indirect-buffer (&optional buffer)
4308 (setq buffer (or buffer (current-buffer)))
4309 (let ((n 1) (base (buffer-name buffer)) bname)
4310 (while (buffer-live-p
4311 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
4312 (setq n (1+ n)))
4313 (condition-case nil
4314 (make-indirect-buffer buffer bname 'clone)
4315 (error (make-indirect-buffer buffer bname)))))
4317 (defun org-set-frame-title (title)
4318 "Set the title of the current frame to the string TITLE."
4319 ;; FIXME: how to name a single frame in XEmacs???
4320 (unless (featurep 'xemacs)
4321 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
4323 ;;;; Structure editing
4325 ;;; Inserting headlines
4327 (defun org-insert-heading (&optional force-heading)
4328 "Insert a new heading or item with same depth at point.
4329 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
4330 If point is at the beginning of a headline, insert a sibling before the
4331 current headline. If point is not at the beginning, do not split the line,
4332 but create the new hedline after the current line."
4333 (interactive "P")
4334 (if (= (buffer-size) 0)
4335 (insert "\n* ")
4336 (when (or force-heading (not (org-insert-item)))
4337 (let* ((head (save-excursion
4338 (condition-case nil
4339 (progn
4340 (org-back-to-heading)
4341 (match-string 0))
4342 (error "*"))))
4343 (blank (cdr (assq 'heading org-blank-before-new-entry)))
4344 pos)
4345 (cond
4346 ((and (org-on-heading-p) (bolp)
4347 (or (bobp)
4348 (save-excursion (backward-char 1) (not (org-invisible-p)))))
4349 ;; insert before the current line
4350 (open-line (if blank 2 1)))
4351 ((and (bolp)
4352 (or (bobp)
4353 (save-excursion
4354 (backward-char 1) (not (org-invisible-p)))))
4355 ;; insert right here
4356 nil)
4358 ;; in the middle of the line
4359 (org-show-entry)
4360 (let ((split
4361 (org-get-alist-option org-M-RET-may-split-line 'headline))
4362 tags pos)
4363 (if (org-on-heading-p)
4364 (progn
4365 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
4366 (setq tags (and (match-end 2) (match-string 2)))
4367 (and (match-end 1)
4368 (delete-region (match-beginning 1) (match-end 1)))
4369 (setq pos (point-at-bol))
4370 (or split (end-of-line 1))
4371 (delete-horizontal-space)
4372 (newline (if blank 2 1))
4373 (when tags
4374 (save-excursion
4375 (goto-char pos)
4376 (end-of-line 1)
4377 (insert " " tags)
4378 (org-set-tags nil 'align))))
4379 (or split (end-of-line 1))
4380 (newline (if blank 2 1))))))
4381 (insert head) (just-one-space)
4382 (setq pos (point))
4383 (end-of-line 1)
4384 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
4385 (run-hooks 'org-insert-heading-hook)))))
4387 (defun org-get-heading (&optional no-tags)
4388 "Return the heading of the current entry, without the stars."
4389 (save-excursion
4390 (org-back-to-heading t)
4391 (if (looking-at
4392 (if no-tags
4393 (org-re "\\*+[ \t]+\\([^\n\r]*?\\)\\([ \t]+:[[:alnum:]:_@]+:[ \t]*\\)?$")
4394 "\\*+[ \t]+\\([^\r\n]*\\)"))
4395 (match-string 1) "")))
4397 (defun org-insert-heading-after-current ()
4398 "Insert a new heading with same level as current, after current subtree."
4399 (interactive)
4400 (org-back-to-heading)
4401 (org-insert-heading)
4402 (org-move-subtree-down)
4403 (end-of-line 1))
4405 (defun org-insert-todo-heading (arg)
4406 "Insert a new heading with the same level and TODO state as current heading.
4407 If the heading has no TODO state, or if the state is DONE, use the first
4408 state (TODO by default). Also with prefix arg, force first state."
4409 (interactive "P")
4410 (when (not (org-insert-item 'checkbox))
4411 (org-insert-heading)
4412 (save-excursion
4413 (org-back-to-heading)
4414 (outline-previous-heading)
4415 (looking-at org-todo-line-regexp))
4416 (if (or arg
4417 (not (match-beginning 2))
4418 (member (match-string 2) org-done-keywords))
4419 (insert (car org-todo-keywords-1) " ")
4420 (insert (match-string 2) " "))))
4422 (defun org-insert-subheading (arg)
4423 "Insert a new subheading and demote it.
4424 Works for outline headings and for plain lists alike."
4425 (interactive "P")
4426 (org-insert-heading arg)
4427 (cond
4428 ((org-on-heading-p) (org-do-demote))
4429 ((org-at-item-p) (org-indent-item 1))))
4431 (defun org-insert-todo-subheading (arg)
4432 "Insert a new subheading with TODO keyword or checkbox and demote it.
4433 Works for outline headings and for plain lists alike."
4434 (interactive "P")
4435 (org-insert-todo-heading arg)
4436 (cond
4437 ((org-on-heading-p) (org-do-demote))
4438 ((org-at-item-p) (org-indent-item 1))))
4440 ;;; Promotion and Demotion
4442 (defun org-promote-subtree ()
4443 "Promote the entire subtree.
4444 See also `org-promote'."
4445 (interactive)
4446 (save-excursion
4447 (org-map-tree 'org-promote))
4448 (org-fix-position-after-promote))
4450 (defun org-demote-subtree ()
4451 "Demote the entire subtree. See `org-demote'.
4452 See also `org-promote'."
4453 (interactive)
4454 (save-excursion
4455 (org-map-tree 'org-demote))
4456 (org-fix-position-after-promote))
4459 (defun org-do-promote ()
4460 "Promote the current heading higher up the tree.
4461 If the region is active in `transient-mark-mode', promote all headings
4462 in the region."
4463 (interactive)
4464 (save-excursion
4465 (if (org-region-active-p)
4466 (org-map-region 'org-promote (region-beginning) (region-end))
4467 (org-promote)))
4468 (org-fix-position-after-promote))
4470 (defun org-do-demote ()
4471 "Demote the current heading lower down the tree.
4472 If the region is active in `transient-mark-mode', demote all headings
4473 in the region."
4474 (interactive)
4475 (save-excursion
4476 (if (org-region-active-p)
4477 (org-map-region 'org-demote (region-beginning) (region-end))
4478 (org-demote)))
4479 (org-fix-position-after-promote))
4481 (defun org-fix-position-after-promote ()
4482 "Make sure that after pro/demotion cursor position is right."
4483 (let ((pos (point)))
4484 (when (save-excursion
4485 (beginning-of-line 1)
4486 (looking-at org-todo-line-regexp)
4487 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
4488 (cond ((eobp) (insert " "))
4489 ((eolp) (insert " "))
4490 ((equal (char-after) ?\ ) (forward-char 1))))))
4492 (defun org-reduced-level (l)
4493 (if org-odd-levels-only (1+ (floor (/ l 2))) l))
4495 (defun org-get-valid-level (level &optional change)
4496 "Rectify a level change under the influence of `org-odd-levels-only'
4497 LEVEL is a current level, CHANGE is by how much the level should be
4498 modified. Even if CHANGE is nil, LEVEL may be returned modified because
4499 even level numbers will become the next higher odd number."
4500 (if org-odd-levels-only
4501 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
4502 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
4503 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
4504 (max 1 (+ level change))))
4506 (if (boundp 'define-obsolete-function-alias)
4507 (if (or (featurep 'xemacs) (< emacs-major-version 23))
4508 (define-obsolete-function-alias 'org-get-legal-level
4509 'org-get-valid-level)
4510 (define-obsolete-function-alias 'org-get-legal-level
4511 'org-get-valid-level "23.1")))
4513 (defun org-promote ()
4514 "Promote the current heading higher up the tree.
4515 If the region is active in `transient-mark-mode', promote all headings
4516 in the region."
4517 (org-back-to-heading t)
4518 (let* ((level (save-match-data (funcall outline-level)))
4519 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
4520 (diff (abs (- level (length up-head) -1))))
4521 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
4522 (replace-match up-head nil t)
4523 ;; Fixup tag positioning
4524 (and org-auto-align-tags (org-set-tags nil t))
4525 (if org-adapt-indentation (org-fixup-indentation (- diff)))))
4527 (defun org-demote ()
4528 "Demote the current heading lower down the tree.
4529 If the region is active in `transient-mark-mode', demote all headings
4530 in the region."
4531 (org-back-to-heading t)
4532 (let* ((level (save-match-data (funcall outline-level)))
4533 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
4534 (diff (abs (- level (length down-head) -1))))
4535 (replace-match down-head nil t)
4536 ;; Fixup tag positioning
4537 (and org-auto-align-tags (org-set-tags nil t))
4538 (if org-adapt-indentation (org-fixup-indentation diff))))
4540 (defun org-map-tree (fun)
4541 "Call FUN for every heading underneath the current one."
4542 (org-back-to-heading)
4543 (let ((level (funcall outline-level)))
4544 (save-excursion
4545 (funcall fun)
4546 (while (and (progn
4547 (outline-next-heading)
4548 (> (funcall outline-level) level))
4549 (not (eobp)))
4550 (funcall fun)))))
4552 (defun org-map-region (fun beg end)
4553 "Call FUN for every heading between BEG and END."
4554 (let ((org-ignore-region t))
4555 (save-excursion
4556 (setq end (copy-marker end))
4557 (goto-char beg)
4558 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
4559 (< (point) end))
4560 (funcall fun))
4561 (while (and (progn
4562 (outline-next-heading)
4563 (< (point) end))
4564 (not (eobp)))
4565 (funcall fun)))))
4567 (defun org-fixup-indentation (diff)
4568 "Change the indentation in the current entry by DIFF
4569 However, if any line in the current entry has no indentation, or if it
4570 would end up with no indentation after the change, nothing at all is done."
4571 (save-excursion
4572 (let ((end (save-excursion (outline-next-heading)
4573 (point-marker)))
4574 (prohibit (if (> diff 0)
4575 "^\\S-"
4576 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
4577 col)
4578 (unless (save-excursion (end-of-line 1)
4579 (re-search-forward prohibit end t))
4580 (while (and (< (point) end)
4581 (re-search-forward "^[ \t]+" end t))
4582 (goto-char (match-end 0))
4583 (setq col (current-column))
4584 (if (< diff 0) (replace-match ""))
4585 (indent-to (+ diff col))))
4586 (move-marker end nil))))
4588 (defun org-convert-to-odd-levels ()
4589 "Convert an org-mode file with all levels allowed to one with odd levels.
4590 This will leave level 1 alone, convert level 2 to level 3, level 3 to
4591 level 5 etc."
4592 (interactive)
4593 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
4594 (let ((org-odd-levels-only nil) n)
4595 (save-excursion
4596 (goto-char (point-min))
4597 (while (re-search-forward "^\\*\\*+ " nil t)
4598 (setq n (- (length (match-string 0)) 2))
4599 (while (>= (setq n (1- n)) 0)
4600 (org-demote))
4601 (end-of-line 1))))))
4604 (defun org-convert-to-oddeven-levels ()
4605 "Convert an org-mode file with only odd levels to one with odd and even levels.
4606 This promotes level 3 to level 2, level 5 to level 3 etc. If the file contains a
4607 section with an even level, conversion would destroy the structure of the file. An error
4608 is signaled in this case."
4609 (interactive)
4610 (goto-char (point-min))
4611 ;; First check if there are no even levels
4612 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
4613 (org-show-context t)
4614 (error "Not all levels are odd in this file. Conversion not possible."))
4615 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
4616 (let ((org-odd-levels-only nil) n)
4617 (save-excursion
4618 (goto-char (point-min))
4619 (while (re-search-forward "^\\*\\*+ " nil t)
4620 (setq n (/ (1- (length (match-string 0))) 2))
4621 (while (>= (setq n (1- n)) 0)
4622 (org-promote))
4623 (end-of-line 1))))))
4625 (defun org-tr-level (n)
4626 "Make N odd if required."
4627 (if org-odd-levels-only (1+ (/ n 2)) n))
4629 ;;; Vertical tree motion, cutting and pasting of subtrees
4631 (defun org-move-subtree-up (&optional arg)
4632 "Move the current subtree up past ARG headlines of the same level."
4633 (interactive "p")
4634 (org-move-subtree-down (- (prefix-numeric-value arg))))
4636 (defun org-move-subtree-down (&optional arg)
4637 "Move the current subtree down past ARG headlines of the same level."
4638 (interactive "p")
4639 (setq arg (prefix-numeric-value arg))
4640 (let ((movfunc (if (> arg 0) 'outline-get-next-sibling
4641 'outline-get-last-sibling))
4642 (ins-point (make-marker))
4643 (cnt (abs arg))
4644 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
4645 ;; Select the tree
4646 (org-back-to-heading)
4647 (setq beg0 (point))
4648 (save-excursion
4649 (setq ne-beg (org-back-over-empty-lines))
4650 (setq beg (point)))
4651 (save-match-data
4652 (save-excursion (outline-end-of-heading)
4653 (setq folded (org-invisible-p)))
4654 (outline-end-of-subtree))
4655 (outline-next-heading)
4656 (setq ne-end (org-back-over-empty-lines))
4657 (setq end (point))
4658 (goto-char beg0)
4659 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
4660 ;; include less whitespace
4661 (save-excursion
4662 (goto-char beg)
4663 (forward-line (- ne-beg ne-end))
4664 (setq beg (point))))
4665 ;; Find insertion point, with error handling
4666 (while (> cnt 0)
4667 (or (and (funcall movfunc) (looking-at outline-regexp))
4668 (progn (goto-char beg0)
4669 (error "Cannot move past superior level or buffer limit")))
4670 (setq cnt (1- cnt)))
4671 (if (> arg 0)
4672 ;; Moving forward - still need to move over subtree
4673 (progn (org-end-of-subtree t t)
4674 (save-excursion
4675 (org-back-over-empty-lines)
4676 (or (bolp) (newline)))))
4677 (setq ne-ins (org-back-over-empty-lines))
4678 (move-marker ins-point (point))
4679 (setq txt (buffer-substring beg end))
4680 (org-save-markers-in-region beg end)
4681 (delete-region beg end)
4682 (outline-flag-region (1- beg) beg nil)
4683 (outline-flag-region (1- (point)) (point) nil)
4684 (let ((bbb (point)))
4685 (insert-before-markers txt)
4686 (org-reinstall-markers-in-region bbb)
4687 (move-marker ins-point bbb))
4688 (or (bolp) (insert "\n"))
4689 (setq ins-end (point))
4690 (goto-char ins-point)
4691 (org-skip-whitespace)
4692 (when (and (< arg 0)
4693 (org-first-sibling-p)
4694 (> ne-ins ne-beg))
4695 ;; Move whitespace back to beginning
4696 (save-excursion
4697 (goto-char ins-end)
4698 (let ((kill-whole-line t))
4699 (kill-line (- ne-ins ne-beg)) (point)))
4700 (insert (make-string (- ne-ins ne-beg) ?\n)))
4701 (move-marker ins-point nil)
4702 (org-compact-display-after-subtree-move)
4703 (unless folded
4704 (org-show-entry)
4705 (show-children)
4706 (org-cycle-hide-drawers 'children))))
4708 (defvar org-subtree-clip ""
4709 "Clipboard for cut and paste of subtrees.
4710 This is actually only a copy of the kill, because we use the normal kill
4711 ring. We need it to check if the kill was created by `org-copy-subtree'.")
4713 (defvar org-subtree-clip-folded nil
4714 "Was the last copied subtree folded?
4715 This is used to fold the tree back after pasting.")
4717 (defun org-cut-subtree (&optional n)
4718 "Cut the current subtree into the clipboard.
4719 With prefix arg N, cut this many sequential subtrees.
4720 This is a short-hand for marking the subtree and then cutting it."
4721 (interactive "p")
4722 (org-copy-subtree n 'cut))
4724 (defun org-copy-subtree (&optional n cut force-store-markers)
4725 "Cut the current subtree into the clipboard.
4726 With prefix arg N, cut this many sequential subtrees.
4727 This is a short-hand for marking the subtree and then copying it.
4728 If CUT is non-nil, actually cut the subtree.
4729 If FORCE-STORE-MARKERS is non-nil, store the relative locations
4730 of some markers in the region, even if CUT is non-nil. This is
4731 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
4732 (interactive "p")
4733 (let (beg end folded (beg0 (point)))
4734 (if (interactive-p)
4735 (org-back-to-heading nil) ; take what looks like a subtree
4736 (org-back-to-heading t)) ; take what is really there
4737 (org-back-over-empty-lines)
4738 (setq beg (point))
4739 (skip-chars-forward " \t\r\n")
4740 (save-match-data
4741 (save-excursion (outline-end-of-heading)
4742 (setq folded (org-invisible-p)))
4743 (condition-case nil
4744 (outline-forward-same-level (1- n))
4745 (error nil))
4746 (org-end-of-subtree t t))
4747 (org-back-over-empty-lines)
4748 (setq end (point))
4749 (goto-char beg0)
4750 (when (> end beg)
4751 (setq org-subtree-clip-folded folded)
4752 (when (or cut force-store-markers)
4753 (org-save-markers-in-region beg end))
4754 (if cut (kill-region beg end) (copy-region-as-kill beg end))
4755 (setq org-subtree-clip (current-kill 0))
4756 (message "%s: Subtree(s) with %d characters"
4757 (if cut "Cut" "Copied")
4758 (length org-subtree-clip)))))
4760 (defun org-paste-subtree (&optional level tree)
4761 "Paste the clipboard as a subtree, with modification of headline level.
4762 The entire subtree is promoted or demoted in order to match a new headline
4763 level. By default, the new level is derived from the visible headings
4764 before and after the insertion point, and taken to be the inferior headline
4765 level of the two. So if the previous visible heading is level 3 and the
4766 next is level 4 (or vice versa), level 4 will be used for insertion.
4767 This makes sure that the subtree remains an independent subtree and does
4768 not swallow low level entries.
4770 You can also force a different level, either by using a numeric prefix
4771 argument, or by inserting the heading marker by hand. For example, if the
4772 cursor is after \"*****\", then the tree will be shifted to level 5.
4774 If you want to insert the tree as is, just use \\[yank].
4776 If optional TREE is given, use this text instead of the kill ring."
4777 (interactive "P")
4778 (unless (org-kill-is-subtree-p tree)
4779 (error "%s"
4780 (substitute-command-keys
4781 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
4782 (let* ((txt (or tree (and kill-ring (current-kill 0))))
4783 (^re (concat "^\\(" outline-regexp "\\)"))
4784 (re (concat "\\(" outline-regexp "\\)"))
4785 (^re_ (concat "\\(\\*+\\)[ \t]*"))
4787 (old-level (if (string-match ^re txt)
4788 (- (match-end 0) (match-beginning 0) 1)
4789 -1))
4790 (force-level (cond (level (prefix-numeric-value level))
4791 ((string-match
4792 ^re_ (buffer-substring (point-at-bol) (point)))
4793 (- (match-end 1) (match-beginning 1)))
4794 (t nil)))
4795 (previous-level (save-excursion
4796 (condition-case nil
4797 (progn
4798 (outline-previous-visible-heading 1)
4799 (if (looking-at re)
4800 (- (match-end 0) (match-beginning 0) 1)
4802 (error 1))))
4803 (next-level (save-excursion
4804 (condition-case nil
4805 (progn
4806 (or (looking-at outline-regexp)
4807 (outline-next-visible-heading 1))
4808 (if (looking-at re)
4809 (- (match-end 0) (match-beginning 0) 1)
4811 (error 1))))
4812 (new-level (or force-level (max previous-level next-level)))
4813 (shift (if (or (= old-level -1)
4814 (= new-level -1)
4815 (= old-level new-level))
4817 (- new-level old-level)))
4818 (delta (if (> shift 0) -1 1))
4819 (func (if (> shift 0) 'org-demote 'org-promote))
4820 (org-odd-levels-only nil)
4821 beg end)
4822 ;; Remove the forced level indicator
4823 (if force-level
4824 (delete-region (point-at-bol) (point)))
4825 ;; Paste
4826 (beginning-of-line 1)
4827 (org-back-over-empty-lines)
4828 (setq beg (point))
4829 (insert-before-markers txt)
4830 (unless (string-match "\n\\'" txt) (insert "\n"))
4831 (org-reinstall-markers-in-region beg)
4832 (setq end (point))
4833 (goto-char beg)
4834 (skip-chars-forward " \t\n\r")
4835 (setq beg (point))
4836 ;; Shift if necessary
4837 (unless (= shift 0)
4838 (save-restriction
4839 (narrow-to-region beg end)
4840 (while (not (= shift 0))
4841 (org-map-region func (point-min) (point-max))
4842 (setq shift (+ delta shift)))
4843 (goto-char (point-min))))
4844 (when (interactive-p)
4845 (message "Clipboard pasted as level %d subtree" new-level))
4846 (if (and kill-ring
4847 (eq org-subtree-clip (current-kill 0))
4848 org-subtree-clip-folded)
4849 ;; The tree was folded before it was killed/copied
4850 (hide-subtree))))
4852 (defun org-kill-is-subtree-p (&optional txt)
4853 "Check if the current kill is an outline subtree, or a set of trees.
4854 Returns nil if kill does not start with a headline, or if the first
4855 headline level is not the largest headline level in the tree.
4856 So this will actually accept several entries of equal levels as well,
4857 which is OK for `org-paste-subtree'.
4858 If optional TXT is given, check this string instead of the current kill."
4859 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
4860 (start-level (and kill
4861 (string-match (concat "\\`\\([ \t\n\r]*?\n\\)?\\("
4862 org-outline-regexp "\\)")
4863 kill)
4864 (- (match-end 2) (match-beginning 2) 1)))
4865 (re (concat "^" org-outline-regexp))
4866 (start (1+ (match-beginning 2))))
4867 (if (not start-level)
4868 (progn
4869 nil) ;; does not even start with a heading
4870 (catch 'exit
4871 (while (setq start (string-match re kill (1+ start)))
4872 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
4873 (throw 'exit nil)))
4874 t))))
4876 (defvar org-markers-to-move nil
4877 "Markers that should be moved with a cut-and-paste operation.
4878 Those markers are stored together with their positions relative to
4879 the start of the region.")
4881 (defun org-save-markers-in-region (beg end)
4882 "Check markers in region.
4883 If these markers are between BEG and END, record their position relative
4884 to BEG, so that after moving the block of text, we can put the markers back
4885 into place.
4886 This function gets called just before an entry or tree gets cut from the
4887 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
4888 called immediately, to move the markers with the entries."
4889 (setq org-markers-to-move nil)
4890 (when (featurep 'org-clock)
4891 (org-clock-save-markers-for-cut-and-paste beg end))
4892 (when (featurep 'org-agenda)
4893 (org-agenda-save-markers-for-cut-and-paste beg end)))
4895 (defun org-check-and-save-marker (marker beg end)
4896 "Check if MARKER is between BEG and END.
4897 If yes, remember the marker and the distance to BEG."
4898 (when (and (marker-buffer marker)
4899 (equal (marker-buffer marker) (current-buffer)))
4900 (if (and (>= marker beg) (< marker end))
4901 (push (cons marker (- marker beg)) org-markers-to-move))))
4903 (defun org-reinstall-markers-in-region (beg)
4904 "Move all remembered markers to their position relative to BEG."
4905 (mapc (lambda (x)
4906 (move-marker (car x) (+ beg (cdr x))))
4907 org-markers-to-move)
4908 (setq org-markers-to-move nil))
4910 (defun org-narrow-to-subtree ()
4911 "Narrow buffer to the current subtree."
4912 (interactive)
4913 (save-excursion
4914 (save-match-data
4915 (narrow-to-region
4916 (progn (org-back-to-heading) (point))
4917 (progn (org-end-of-subtree t t) (point))))))
4920 ;;; Outline Sorting
4922 (defun org-sort (with-case)
4923 "Call `org-sort-entries-or-items' or `org-table-sort-lines'.
4924 Optional argument WITH-CASE means sort case-sensitively."
4925 (interactive "P")
4926 (if (org-at-table-p)
4927 (org-call-with-arg 'org-table-sort-lines with-case)
4928 (org-call-with-arg 'org-sort-entries-or-items with-case)))
4930 (defun org-sort-remove-invisible (s)
4931 (remove-text-properties 0 (length s) org-rm-props s)
4932 (while (string-match org-bracket-link-regexp s)
4933 (setq s (replace-match (if (match-end 2)
4934 (match-string 3 s)
4935 (match-string 1 s)) t t s)))
4938 (defvar org-priority-regexp) ; defined later in the file
4940 (defun org-sort-entries-or-items (&optional with-case sorting-type getkey-func property)
4941 "Sort entries on a certain level of an outline tree.
4942 If there is an active region, the entries in the region are sorted.
4943 Else, if the cursor is before the first entry, sort the top-level items.
4944 Else, the children of the entry at point are sorted.
4946 Sorting can be alphabetically, numerically, and by date/time as given by
4947 the first time stamp in the entry. The command prompts for the sorting
4948 type unless it has been given to the function through the SORTING-TYPE
4949 argument, which needs to a character, any of (?n ?N ?a ?A ?t ?T ?p ?P ?f ?F).
4950 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
4951 called with point at the beginning of the record. It must return either
4952 a string or a number that should serve as the sorting key for that record.
4954 Comparing entries ignores case by default. However, with an optional argument
4955 WITH-CASE, the sorting considers case as well."
4956 (interactive "P")
4957 (let ((case-func (if with-case 'identity 'downcase))
4958 start beg end stars re re2
4959 txt what tmp plain-list-p)
4960 ;; Find beginning and end of region to sort
4961 (cond
4962 ((org-region-active-p)
4963 ;; we will sort the region
4964 (setq end (region-end)
4965 what "region")
4966 (goto-char (region-beginning))
4967 (if (not (org-on-heading-p)) (outline-next-heading))
4968 (setq start (point)))
4969 ((org-at-item-p)
4970 ;; we will sort this plain list
4971 (org-beginning-of-item-list) (setq start (point))
4972 (org-end-of-item-list) (setq end (point))
4973 (goto-char start)
4974 (setq plain-list-p t
4975 what "plain list"))
4976 ((or (org-on-heading-p)
4977 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
4978 ;; we will sort the children of the current headline
4979 (org-back-to-heading)
4980 (setq start (point)
4981 end (progn (org-end-of-subtree t t)
4982 (org-back-over-empty-lines)
4983 (point))
4984 what "children")
4985 (goto-char start)
4986 (show-subtree)
4987 (outline-next-heading))
4989 ;; we will sort the top-level entries in this file
4990 (goto-char (point-min))
4991 (or (org-on-heading-p) (outline-next-heading))
4992 (setq start (point) end (point-max) what "top-level")
4993 (goto-char start)
4994 (show-all)))
4996 (setq beg (point))
4997 (if (>= beg end) (error "Nothing to sort"))
4999 (unless plain-list-p
5000 (looking-at "\\(\\*+\\)")
5001 (setq stars (match-string 1)
5002 re (concat "^" (regexp-quote stars) " +")
5003 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[^*]")
5004 txt (buffer-substring beg end))
5005 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
5006 (if (and (not (equal stars "*")) (string-match re2 txt))
5007 (error "Region to sort contains a level above the first entry")))
5009 (unless sorting-type
5010 (message
5011 (if plain-list-p
5012 "Sort %s: [a]lpha [n]umeric [t]ime [f]unc A/N/T/F means reversed:"
5013 "Sort %s: [a]lpha [n]umeric [t]ime [p]riority p[r]operty todo[o]rder [f]unc A/N/T/P/O/F means reversed:")
5014 what)
5015 (setq sorting-type (read-char-exclusive))
5017 (and (= (downcase sorting-type) ?f)
5018 (setq getkey-func
5019 (completing-read "Sort using function: "
5020 obarray 'fboundp t nil nil))
5021 (setq getkey-func (intern getkey-func)))
5023 (and (= (downcase sorting-type) ?r)
5024 (setq property
5025 (completing-read "Property: "
5026 (mapcar 'list (org-buffer-property-keys t))
5027 nil t))))
5029 (message "Sorting entries...")
5031 (save-restriction
5032 (narrow-to-region start end)
5034 (let ((dcst (downcase sorting-type))
5035 (now (current-time)))
5036 (sort-subr
5037 (/= dcst sorting-type)
5038 ;; This function moves to the beginning character of the "record" to
5039 ;; be sorted.
5040 (if plain-list-p
5041 (lambda nil
5042 (if (org-at-item-p) t (goto-char (point-max))))
5043 (lambda nil
5044 (if (re-search-forward re nil t)
5045 (goto-char (match-beginning 0))
5046 (goto-char (point-max)))))
5047 ;; This function moves to the last character of the "record" being
5048 ;; sorted.
5049 (if plain-list-p
5050 'org-end-of-item
5051 (lambda nil
5052 (save-match-data
5053 (condition-case nil
5054 (outline-forward-same-level 1)
5055 (error
5056 (goto-char (point-max)))))))
5058 ;; This function returns the value that gets sorted against.
5059 (if plain-list-p
5060 (lambda nil
5061 (when (looking-at "[ \t]*[-+*0-9.)]+[ \t]+")
5062 (cond
5063 ((= dcst ?n)
5064 (string-to-number (buffer-substring (match-end 0)
5065 (point-at-eol))))
5066 ((= dcst ?a)
5067 (buffer-substring (match-end 0) (point-at-eol)))
5068 ((= dcst ?t)
5069 (if (re-search-forward org-ts-regexp
5070 (point-at-eol) t)
5071 (org-time-string-to-time (match-string 0))
5072 now))
5073 ((= dcst ?f)
5074 (if getkey-func
5075 (progn
5076 (setq tmp (funcall getkey-func))
5077 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
5078 tmp)
5079 (error "Invalid key function `%s'" getkey-func)))
5080 (t (error "Invalid sorting type `%c'" sorting-type)))))
5081 (lambda nil
5082 (cond
5083 ((= dcst ?n)
5084 (if (looking-at outline-regexp)
5085 (string-to-number (buffer-substring (match-end 0)
5086 (point-at-eol)))
5087 nil))
5088 ((= dcst ?a)
5089 (funcall case-func (buffer-substring (point-at-bol)
5090 (point-at-eol))))
5091 ((= dcst ?t)
5092 (if (re-search-forward org-ts-regexp
5093 (save-excursion
5094 (forward-line 2)
5095 (point)) t)
5096 (org-time-string-to-time (match-string 0))
5097 now))
5098 ((= dcst ?p)
5099 (if (re-search-forward org-priority-regexp (point-at-eol) t)
5100 (string-to-char (match-string 2))
5101 org-default-priority))
5102 ((= dcst ?r)
5103 (or (org-entry-get nil property) ""))
5104 ((= dcst ?o)
5105 (if (looking-at org-complex-heading-regexp)
5106 (- 9999 (length (member (match-string 2)
5107 org-todo-keywords-1)))))
5108 ((= dcst ?f)
5109 (if getkey-func
5110 (progn
5111 (setq tmp (funcall getkey-func))
5112 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
5113 tmp)
5114 (error "Invalid key function `%s'" getkey-func)))
5115 (t (error "Invalid sorting type `%c'" sorting-type)))))
5117 (cond
5118 ((= dcst ?a) 'string<)
5119 ((= dcst ?t) 'time-less-p)
5120 (t nil)))))
5121 (message "Sorting entries...done")))
5123 (defun org-do-sort (table what &optional with-case sorting-type)
5124 "Sort TABLE of WHAT according to SORTING-TYPE.
5125 The user will be prompted for the SORTING-TYPE if the call to this
5126 function does not specify it. WHAT is only for the prompt, to indicate
5127 what is being sorted. The sorting key will be extracted from
5128 the car of the elements of the table.
5129 If WITH-CASE is non-nil, the sorting will be case-sensitive."
5130 (unless sorting-type
5131 (message
5132 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
5133 what)
5134 (setq sorting-type (read-char-exclusive)))
5135 (let ((dcst (downcase sorting-type))
5136 extractfun comparefun)
5137 ;; Define the appropriate functions
5138 (cond
5139 ((= dcst ?n)
5140 (setq extractfun 'string-to-number
5141 comparefun (if (= dcst sorting-type) '< '>)))
5142 ((= dcst ?a)
5143 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
5144 (lambda(x) (downcase (org-sort-remove-invisible x))))
5145 comparefun (if (= dcst sorting-type)
5146 'string<
5147 (lambda (a b) (and (not (string< a b))
5148 (not (string= a b)))))))
5149 ((= dcst ?t)
5150 (setq extractfun
5151 (lambda (x)
5152 (if (string-match org-ts-regexp x)
5153 (time-to-seconds
5154 (org-time-string-to-time (match-string 0 x)))
5156 comparefun (if (= dcst sorting-type) '< '>)))
5157 (t (error "Invalid sorting type `%c'" sorting-type)))
5159 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
5160 table)
5161 (lambda (a b) (funcall comparefun (car a) (car b))))))
5163 ;;;; Plain list items, including checkboxes
5165 ;;; Plain list items
5167 (defun org-at-item-p ()
5168 "Is point in a line starting a hand-formatted item?"
5169 (let ((llt org-plain-list-ordered-item-terminator))
5170 (save-excursion
5171 (goto-char (point-at-bol))
5172 (looking-at
5173 (cond
5174 ((eq llt t) "\\([ \t]*\\([-+]\\|\\([0-9]+[.)]\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
5175 ((= llt ?.) "\\([ \t]*\\([-+]\\|\\([0-9]+\\.\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
5176 ((= llt ?\)) "\\([ \t]*\\([-+]\\|\\([0-9]+))\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
5177 (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))))))
5179 (defun org-in-item-p ()
5180 "It the cursor inside a plain list item.
5181 Does not have to be the first line."
5182 (save-excursion
5183 (condition-case nil
5184 (progn
5185 (org-beginning-of-item)
5186 (org-at-item-p)
5188 (error nil))))
5190 (defun org-insert-item (&optional checkbox)
5191 "Insert a new item at the current level.
5192 Return t when things worked, nil when we are not in an item."
5193 (when (save-excursion
5194 (condition-case nil
5195 (progn
5196 (org-beginning-of-item)
5197 (org-at-item-p)
5198 (if (org-invisible-p) (error "Invisible item"))
5200 (error nil)))
5201 (let* ((bul (match-string 0))
5202 (eow (save-excursion (beginning-of-line 1) (looking-at "[ \t]*")
5203 (match-end 0)))
5204 (blank (cdr (assq 'plain-list-item org-blank-before-new-entry)))
5205 pos)
5206 (cond
5207 ((and (org-at-item-p) (<= (point) eow))
5208 ;; before the bullet
5209 (beginning-of-line 1)
5210 (open-line (if blank 2 1)))
5211 ((<= (point) eow)
5212 (beginning-of-line 1))
5214 (unless (org-get-alist-option org-M-RET-may-split-line 'item)
5215 (end-of-line 1)
5216 (delete-horizontal-space))
5217 (newline (if blank 2 1))))
5218 (insert bul (if checkbox "[ ]" ""))
5219 (just-one-space)
5220 (setq pos (point))
5221 (end-of-line 1)
5222 (unless (= (point) pos) (just-one-space) (backward-delete-char 1)))
5223 (org-maybe-renumber-ordered-list)
5224 (and checkbox (org-update-checkbox-count-maybe))
5227 ;;; Checkboxes
5229 (defun org-at-item-checkbox-p ()
5230 "Is point at a line starting a plain-list item with a checklet?"
5231 (and (org-at-item-p)
5232 (save-excursion
5233 (goto-char (match-end 0))
5234 (skip-chars-forward " \t")
5235 (looking-at "\\[[- X]\\]"))))
5237 (defun org-toggle-checkbox (&optional arg)
5238 "Toggle the checkbox in the current line."
5239 (interactive "P")
5240 (catch 'exit
5241 (let (beg end status (firstnew 'unknown))
5242 (cond
5243 ((org-region-active-p)
5244 (setq beg (region-beginning) end (region-end)))
5245 ((org-on-heading-p)
5246 (setq beg (point) end (save-excursion (outline-next-heading) (point))))
5247 ((org-at-item-checkbox-p)
5248 (let ((pos (point)))
5249 (replace-match
5250 (cond (arg "[-]")
5251 ((member (match-string 0) '("[ ]" "[-]")) "[X]")
5252 (t "[ ]"))
5253 t t)
5254 (goto-char pos))
5255 (throw 'exit t))
5256 (t (error "Not at a checkbox or heading, and no active region")))
5257 (save-excursion
5258 (goto-char beg)
5259 (while (< (point) end)
5260 (when (org-at-item-checkbox-p)
5261 (setq status (equal (match-string 0) "[X]"))
5262 (when (eq firstnew 'unknown)
5263 (setq firstnew (not status)))
5264 (replace-match
5265 (if (if arg (not status) firstnew) "[X]" "[ ]") t t))
5266 (beginning-of-line 2)))))
5267 (org-update-checkbox-count-maybe))
5269 (defun org-update-checkbox-count-maybe ()
5270 "Update checkbox statistics unless turned off by user."
5271 (when org-provide-checkbox-statistics
5272 (org-update-checkbox-count)))
5274 (defun org-update-checkbox-count (&optional all)
5275 "Update the checkbox statistics in the current section.
5276 This will find all statistic cookies like [57%] and [6/12] and update them
5277 with the current numbers. With optional prefix argument ALL, do this for
5278 the whole buffer."
5279 (interactive "P")
5280 (save-excursion
5281 (let* ((buffer-invisibility-spec (org-inhibit-invisibility)) ; Emacs 21
5282 (beg (condition-case nil
5283 (progn (outline-back-to-heading) (point))
5284 (error (point-min))))
5285 (end (move-marker (make-marker)
5286 (progn (outline-next-heading) (point))))
5287 (re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
5288 (re-box "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)")
5289 (re-find (concat re "\\|" re-box))
5290 beg-cookie end-cookie is-percent c-on c-off lim
5291 eline curr-ind next-ind continue-from startsearch
5292 (cstat 0)
5294 (when all
5295 (goto-char (point-min))
5296 (outline-next-heading)
5297 (setq beg (point) end (point-max)))
5298 (goto-char end)
5299 ;; find each statistic cookie
5300 (while (re-search-backward re-find beg t)
5301 (setq beg-cookie (match-beginning 1)
5302 end-cookie (match-end 1)
5303 cstat (+ cstat (if end-cookie 1 0))
5304 startsearch (point-at-eol)
5305 continue-from (point-at-bol)
5306 is-percent (match-beginning 2)
5307 lim (cond
5308 ((org-on-heading-p) (outline-next-heading) (point))
5309 ((org-at-item-p) (org-end-of-item) (point))
5310 (t nil))
5311 c-on 0
5312 c-off 0)
5313 (when lim
5314 ;; find first checkbox for this cookie and gather
5315 ;; statistics from all that are at this indentation level
5316 (goto-char startsearch)
5317 (if (re-search-forward re-box lim t)
5318 (progn
5319 (org-beginning-of-item)
5320 (setq curr-ind (org-get-indentation))
5321 (setq next-ind curr-ind)
5322 (while (and (bolp) (org-at-item-p) (= curr-ind next-ind))
5323 (save-excursion (end-of-line) (setq eline (point)))
5324 (if (re-search-forward re-box eline t)
5325 (if (member (match-string 2) '("[ ]" "[-]"))
5326 (setq c-off (1+ c-off))
5327 (setq c-on (1+ c-on))
5330 (org-end-of-item)
5331 (setq next-ind (org-get-indentation))
5333 (goto-char continue-from)
5334 ;; update cookie
5335 (when end-cookie
5336 (delete-region beg-cookie end-cookie)
5337 (goto-char beg-cookie)
5338 (insert
5339 (if is-percent
5340 (format "[%d%%]" (/ (* 100 c-on) (max 1 (+ c-on c-off))))
5341 (format "[%d/%d]" c-on (+ c-on c-off)))))
5342 ;; update items checkbox if it has one
5343 (when (org-at-item-p)
5344 (org-beginning-of-item)
5345 (when (and (> (+ c-on c-off) 0)
5346 (re-search-forward re-box (point-at-eol) t))
5347 (setq beg-cookie (match-beginning 2)
5348 end-cookie (match-end 2))
5349 (delete-region beg-cookie end-cookie)
5350 (goto-char beg-cookie)
5351 (cond ((= c-off 0) (insert "[X]"))
5352 ((= c-on 0) (insert "[ ]"))
5353 (t (insert "[-]")))
5355 (goto-char continue-from))
5356 (when (interactive-p)
5357 (message "Checkbox satistics updated %s (%d places)"
5358 (if all "in entire file" "in current outline entry") cstat)))))
5360 (defun org-get-checkbox-statistics-face ()
5361 "Select the face for checkbox statistics.
5362 The face will be `org-done' when all relevant boxes are checked. Otherwise
5363 it will be `org-todo'."
5364 (if (match-end 1)
5365 (if (equal (match-string 1) "100%") 'org-done 'org-todo)
5366 (if (and (> (match-end 2) (match-beginning 2))
5367 (equal (match-string 2) (match-string 3)))
5368 'org-done
5369 'org-todo)))
5371 (defun org-get-indentation (&optional line)
5372 "Get the indentation of the current line, interpreting tabs.
5373 When LINE is given, assume it represents a line and compute its indentation."
5374 (if line
5375 (if (string-match "^ *" (org-remove-tabs line))
5376 (match-end 0))
5377 (save-excursion
5378 (beginning-of-line 1)
5379 (skip-chars-forward " \t")
5380 (current-column))))
5382 (defun org-remove-tabs (s &optional width)
5383 "Replace tabulators in S with spaces.
5384 Assumes that s is a single line, starting in column 0."
5385 (setq width (or width tab-width))
5386 (while (string-match "\t" s)
5387 (setq s (replace-match
5388 (make-string
5389 (- (* width (/ (+ (match-beginning 0) width) width))
5390 (match-beginning 0)) ?\ )
5391 t t s)))
5394 (defun org-fix-indentation (line ind)
5395 "Fix indentation in LINE.
5396 IND is a cons cell with target and minimum indentation.
5397 If the current indenation in LINE is smaller than the minimum,
5398 leave it alone. If it is larger than ind, set it to the target."
5399 (let* ((l (org-remove-tabs line))
5400 (i (org-get-indentation l))
5401 (i1 (car ind)) (i2 (cdr ind)))
5402 (if (>= i i2) (setq l (substring line i2)))
5403 (if (> i1 0)
5404 (concat (make-string i1 ?\ ) l)
5405 l)))
5407 (defun org-beginning-of-item ()
5408 "Go to the beginning of the current hand-formatted item.
5409 If the cursor is not in an item, throw an error."
5410 (interactive)
5411 (let ((pos (point))
5412 (limit (save-excursion
5413 (condition-case nil
5414 (progn
5415 (org-back-to-heading)
5416 (beginning-of-line 2) (point))
5417 (error (point-min)))))
5418 (ind-empty (if org-empty-line-terminates-plain-lists 0 10000))
5419 ind ind1)
5420 (if (org-at-item-p)
5421 (beginning-of-line 1)
5422 (beginning-of-line 1)
5423 (skip-chars-forward " \t")
5424 (setq ind (current-column))
5425 (if (catch 'exit
5426 (while t
5427 (beginning-of-line 0)
5428 (if (or (bobp) (< (point) limit)) (throw 'exit nil))
5430 (if (looking-at "[ \t]*$")
5431 (setq ind1 ind-empty)
5432 (skip-chars-forward " \t")
5433 (setq ind1 (current-column)))
5434 (if (< ind1 ind)
5435 (progn (beginning-of-line 1) (throw 'exit (org-at-item-p))))))
5437 (goto-char pos)
5438 (error "Not in an item")))))
5440 (defun org-end-of-item ()
5441 "Go to the end of the current hand-formatted item.
5442 If the cursor is not in an item, throw an error."
5443 (interactive)
5444 (let* ((pos (point))
5445 ind1
5446 (ind-empty (if org-empty-line-terminates-plain-lists 0 10000))
5447 (limit (save-excursion (outline-next-heading) (point)))
5448 (ind (save-excursion
5449 (org-beginning-of-item)
5450 (skip-chars-forward " \t")
5451 (current-column)))
5452 (end (catch 'exit
5453 (while t
5454 (beginning-of-line 2)
5455 (if (eobp) (throw 'exit (point)))
5456 (if (>= (point) limit) (throw 'exit (point-at-bol)))
5457 (if (looking-at "[ \t]*$")
5458 (setq ind1 ind-empty)
5459 (skip-chars-forward " \t")
5460 (setq ind1 (current-column)))
5461 (if (<= ind1 ind)
5462 (throw 'exit (point-at-bol)))))))
5463 (if end
5464 (goto-char end)
5465 (goto-char pos)
5466 (error "Not in an item"))))
5468 (defun org-next-item ()
5469 "Move to the beginning of the next item in the current plain list.
5470 Error if not at a plain list, or if this is the last item in the list."
5471 (interactive)
5472 (let (ind ind1 (pos (point)))
5473 (org-beginning-of-item)
5474 (setq ind (org-get-indentation))
5475 (org-end-of-item)
5476 (setq ind1 (org-get-indentation))
5477 (unless (and (org-at-item-p) (= ind ind1))
5478 (goto-char pos)
5479 (error "On last item"))))
5481 (defun org-previous-item ()
5482 "Move to the beginning of the previous item in the current plain list.
5483 Error if not at a plain list, or if this is the first item in the list."
5484 (interactive)
5485 (let (beg ind ind1 (pos (point)))
5486 (org-beginning-of-item)
5487 (setq beg (point))
5488 (setq ind (org-get-indentation))
5489 (goto-char beg)
5490 (catch 'exit
5491 (while t
5492 (beginning-of-line 0)
5493 (if (looking-at "[ \t]*$")
5495 (if (<= (setq ind1 (org-get-indentation)) ind)
5496 (throw 'exit t)))))
5497 (condition-case nil
5498 (if (or (not (org-at-item-p))
5499 (< ind1 (1- ind)))
5500 (error "")
5501 (org-beginning-of-item))
5502 (error (goto-char pos)
5503 (error "On first item")))))
5505 (defun org-first-list-item-p ()
5506 "Is this heading the item in a plain list?"
5507 (unless (org-at-item-p)
5508 (error "Not at a plain list item"))
5509 (org-beginning-of-item)
5510 (= (point) (save-excursion (org-beginning-of-item-list))))
5512 (defun org-move-item-down ()
5513 "Move the plain list item at point down, i.e. swap with following item.
5514 Subitems (items with larger indentation) are considered part of the item,
5515 so this really moves item trees."
5516 (interactive)
5517 (let (beg beg0 end end0 ind ind1 (pos (point)) txt ne-end ne-beg)
5518 (org-beginning-of-item)
5519 (setq beg0 (point))
5520 (save-excursion
5521 (setq ne-beg (org-back-over-empty-lines))
5522 (setq beg (point)))
5523 (goto-char beg0)
5524 (setq ind (org-get-indentation))
5525 (org-end-of-item)
5526 (setq end0 (point))
5527 (setq ind1 (org-get-indentation))
5528 (setq ne-end (org-back-over-empty-lines))
5529 (setq end (point))
5530 (goto-char beg0)
5531 (when (and (org-first-list-item-p) (< ne-end ne-beg))
5532 ;; include less whitespace
5533 (save-excursion
5534 (goto-char beg)
5535 (forward-line (- ne-beg ne-end))
5536 (setq beg (point))))
5537 (goto-char end0)
5538 (if (and (org-at-item-p) (= ind ind1))
5539 (progn
5540 (org-end-of-item)
5541 (org-back-over-empty-lines)
5542 (setq txt (buffer-substring beg end))
5543 (save-excursion
5544 (delete-region beg end))
5545 (setq pos (point))
5546 (insert txt)
5547 (goto-char pos) (org-skip-whitespace)
5548 (org-maybe-renumber-ordered-list))
5549 (goto-char pos)
5550 (error "Cannot move this item further down"))))
5552 (defun org-move-item-up (arg)
5553 "Move the plain list item at point up, i.e. swap with previous item.
5554 Subitems (items with larger indentation) are considered part of the item,
5555 so this really moves item trees."
5556 (interactive "p")
5557 (let (beg beg0 end ind ind1 (pos (point)) txt
5558 ne-beg ne-ins ins-end)
5559 (org-beginning-of-item)
5560 (setq beg0 (point))
5561 (setq ind (org-get-indentation))
5562 (save-excursion
5563 (setq ne-beg (org-back-over-empty-lines))
5564 (setq beg (point)))
5565 (goto-char beg0)
5566 (org-end-of-item)
5567 (setq end (point))
5568 (goto-char beg0)
5569 (catch 'exit
5570 (while t
5571 (beginning-of-line 0)
5572 (if (looking-at "[ \t]*$")
5573 (if org-empty-line-terminates-plain-lists
5574 (progn
5575 (goto-char pos)
5576 (error "Cannot move this item further up"))
5577 nil)
5578 (if (<= (setq ind1 (org-get-indentation)) ind)
5579 (throw 'exit t)))))
5580 (condition-case nil
5581 (org-beginning-of-item)
5582 (error (goto-char beg)
5583 (error "Cannot move this item further up")))
5584 (setq ind1 (org-get-indentation))
5585 (if (and (org-at-item-p) (= ind ind1))
5586 (progn
5587 (setq ne-ins (org-back-over-empty-lines))
5588 (setq txt (buffer-substring beg end))
5589 (save-excursion
5590 (delete-region beg end))
5591 (setq pos (point))
5592 (insert txt)
5593 (setq ins-end (point))
5594 (goto-char pos) (org-skip-whitespace)
5596 (when (and (org-first-list-item-p) (> ne-ins ne-beg))
5597 ;; Move whitespace back to beginning
5598 (save-excursion
5599 (goto-char ins-end)
5600 (let ((kill-whole-line t))
5601 (kill-line (- ne-ins ne-beg)) (point)))
5602 (insert (make-string (- ne-ins ne-beg) ?\n)))
5604 (org-maybe-renumber-ordered-list))
5605 (goto-char pos)
5606 (error "Cannot move this item further up"))))
5608 (defun org-maybe-renumber-ordered-list ()
5609 "Renumber the ordered list at point if setup allows it.
5610 This tests the user option `org-auto-renumber-ordered-lists' before
5611 doing the renumbering."
5612 (interactive)
5613 (when (and org-auto-renumber-ordered-lists
5614 (org-at-item-p))
5615 (if (match-beginning 3)
5616 (org-renumber-ordered-list 1)
5617 (org-fix-bullet-type))))
5619 (defun org-maybe-renumber-ordered-list-safe ()
5620 (condition-case nil
5621 (save-excursion
5622 (org-maybe-renumber-ordered-list))
5623 (error nil)))
5625 (defun org-cycle-list-bullet (&optional which)
5626 "Cycle through the different itemize/enumerate bullets.
5627 This cycle the entire list level through the sequence:
5629 `-' -> `+' -> `*' -> `1.' -> `1)'
5631 If WHICH is a string, use that as the new bullet. If WHICH is an integer,
5632 0 meand `-', 1 means `+' etc."
5633 (interactive "P")
5634 (org-preserve-lc
5635 (org-beginning-of-item-list)
5636 (org-at-item-p)
5637 (beginning-of-line 1)
5638 (let ((current (match-string 0))
5639 (prevp (eq which 'previous))
5640 new)
5641 (setq new (cond
5642 ((and (numberp which)
5643 (nth (1- which) '("-" "+" "*" "1." "1)"))))
5644 ((string-match "-" current) (if prevp "1)" "+"))
5645 ((string-match "\\+" current)
5646 (if prevp "-" (if (looking-at "\\S-") "1." "*")))
5647 ((string-match "\\*" current) (if prevp "+" "1."))
5648 ((string-match "\\." current) (if prevp "*" "1)"))
5649 ((string-match ")" current) (if prevp "1." "-"))
5650 (t (error "This should not happen"))))
5651 (and (looking-at "\\([ \t]*\\)\\S-+") (replace-match (concat "\\1" new)))
5652 (org-fix-bullet-type)
5653 (org-maybe-renumber-ordered-list))))
5655 (defun org-get-string-indentation (s)
5656 "What indentation has S due to SPACE and TAB at the beginning of the string?"
5657 (let ((n -1) (i 0) (w tab-width) c)
5658 (catch 'exit
5659 (while (< (setq n (1+ n)) (length s))
5660 (setq c (aref s n))
5661 (cond ((= c ?\ ) (setq i (1+ i)))
5662 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
5663 (t (throw 'exit t)))))
5666 (defun org-renumber-ordered-list (arg)
5667 "Renumber an ordered plain list.
5668 Cursor needs to be in the first line of an item, the line that starts
5669 with something like \"1.\" or \"2)\"."
5670 (interactive "p")
5671 (unless (and (org-at-item-p)
5672 (match-beginning 3))
5673 (error "This is not an ordered list"))
5674 (let ((line (org-current-line))
5675 (col (current-column))
5676 (ind (org-get-string-indentation
5677 (buffer-substring (point-at-bol) (match-beginning 3))))
5678 ;; (term (substring (match-string 3) -1))
5679 ind1 (n (1- arg))
5680 fmt)
5681 ;; find where this list begins
5682 (org-beginning-of-item-list)
5683 (looking-at "[ \t]*[0-9]+\\([.)]\\)")
5684 (setq fmt (concat "%d" (match-string 1)))
5685 (beginning-of-line 0)
5686 ;; walk forward and replace these numbers
5687 (catch 'exit
5688 (while t
5689 (catch 'next
5690 (beginning-of-line 2)
5691 (if (eobp) (throw 'exit nil))
5692 (if (looking-at "[ \t]*$") (throw 'next nil))
5693 (skip-chars-forward " \t") (setq ind1 (current-column))
5694 (if (> ind1 ind) (throw 'next t))
5695 (if (< ind1 ind) (throw 'exit t))
5696 (if (not (org-at-item-p)) (throw 'exit nil))
5697 (delete-region (match-beginning 2) (match-end 2))
5698 (goto-char (match-beginning 2))
5699 (insert (format fmt (setq n (1+ n)))))))
5700 (goto-line line)
5701 (org-move-to-column col)))
5703 (defun org-fix-bullet-type ()
5704 "Make sure all items in this list have the same bullet as the firsst item."
5705 (interactive)
5706 (unless (org-at-item-p) (error "This is not a list"))
5707 (let ((line (org-current-line))
5708 (col (current-column))
5709 (ind (current-indentation))
5710 ind1 bullet)
5711 ;; find where this list begins
5712 (org-beginning-of-item-list)
5713 (beginning-of-line 1)
5714 ;; find out what the bullet type is
5715 (looking-at "[ \t]*\\(\\S-+\\)")
5716 (setq bullet (match-string 1))
5717 ;; walk forward and replace these numbers
5718 (beginning-of-line 0)
5719 (catch 'exit
5720 (while t
5721 (catch 'next
5722 (beginning-of-line 2)
5723 (if (eobp) (throw 'exit nil))
5724 (if (looking-at "[ \t]*$") (throw 'next nil))
5725 (skip-chars-forward " \t") (setq ind1 (current-column))
5726 (if (> ind1 ind) (throw 'next t))
5727 (if (< ind1 ind) (throw 'exit t))
5728 (if (not (org-at-item-p)) (throw 'exit nil))
5729 (skip-chars-forward " \t")
5730 (looking-at "\\S-+")
5731 (replace-match bullet))))
5732 (goto-line line)
5733 (org-move-to-column col)
5734 (if (string-match "[0-9]" bullet)
5735 (org-renumber-ordered-list 1))))
5737 (defun org-beginning-of-item-list ()
5738 "Go to the beginning of the current item list.
5739 I.e. to the first item in this list."
5740 (interactive)
5741 (org-beginning-of-item)
5742 (let ((pos (point-at-bol))
5743 (ind (org-get-indentation))
5744 ind1)
5745 ;; find where this list begins
5746 (catch 'exit
5747 (while t
5748 (catch 'next
5749 (beginning-of-line 0)
5750 (if (looking-at "[ \t]*$")
5751 (throw (if (bobp) 'exit 'next) t))
5752 (skip-chars-forward " \t") (setq ind1 (current-column))
5753 (if (or (< ind1 ind)
5754 (and (= ind1 ind)
5755 (not (org-at-item-p)))
5756 (bobp))
5757 (throw 'exit t)
5758 (when (org-at-item-p) (setq pos (point-at-bol)))))))
5759 (goto-char pos)))
5762 (defun org-end-of-item-list ()
5763 "Go to the end of the current item list.
5764 I.e. to the text after the last item."
5765 (interactive)
5766 (org-beginning-of-item)
5767 (let ((pos (point-at-bol))
5768 (ind (org-get-indentation))
5769 ind1)
5770 ;; find where this list begins
5771 (catch 'exit
5772 (while t
5773 (catch 'next
5774 (beginning-of-line 2)
5775 (if (looking-at "[ \t]*$")
5776 (throw (if (eobp) 'exit 'next) t))
5777 (skip-chars-forward " \t") (setq ind1 (current-column))
5778 (if (or (< ind1 ind)
5779 (and (= ind1 ind)
5780 (not (org-at-item-p)))
5781 (eobp))
5782 (progn
5783 (setq pos (point-at-bol))
5784 (throw 'exit t))))))
5785 (goto-char pos)))
5788 (defvar org-last-indent-begin-marker (make-marker))
5789 (defvar org-last-indent-end-marker (make-marker))
5791 (defun org-outdent-item (arg)
5792 "Outdent a local list item."
5793 (interactive "p")
5794 (org-indent-item (- arg)))
5796 (defun org-indent-item (arg)
5797 "Indent a local list item."
5798 (interactive "p")
5799 (unless (org-at-item-p)
5800 (error "Not on an item"))
5801 (save-excursion
5802 (let (beg end ind ind1 tmp delta ind-down ind-up)
5803 (if (memq last-command '(org-shiftmetaright org-shiftmetaleft))
5804 (setq beg org-last-indent-begin-marker
5805 end org-last-indent-end-marker)
5806 (org-beginning-of-item)
5807 (setq beg (move-marker org-last-indent-begin-marker (point)))
5808 (org-end-of-item)
5809 (setq end (move-marker org-last-indent-end-marker (point))))
5810 (goto-char beg)
5811 (setq tmp (org-item-indent-positions)
5812 ind (car tmp)
5813 ind-down (nth 2 tmp)
5814 ind-up (nth 1 tmp)
5815 delta (if (> arg 0)
5816 (if ind-down (- ind-down ind) 2)
5817 (if ind-up (- ind-up ind) -2)))
5818 (if (< (+ delta ind) 0) (error "Cannot outdent beyond margin"))
5819 (while (< (point) end)
5820 (beginning-of-line 1)
5821 (skip-chars-forward " \t") (setq ind1 (current-column))
5822 (delete-region (point-at-bol) (point))
5823 (or (eolp) (org-indent-to-column (+ ind1 delta)))
5824 (beginning-of-line 2))))
5825 (org-fix-bullet-type)
5826 (org-maybe-renumber-ordered-list-safe)
5827 (save-excursion
5828 (beginning-of-line 0)
5829 (condition-case nil (org-beginning-of-item) (error nil))
5830 (org-maybe-renumber-ordered-list-safe)))
5832 (defun org-item-indent-positions ()
5833 "Return indentation for plain list items.
5834 This returns a list with three values: The current indentation, the
5835 parent indentation and the indentation a child should habe.
5836 Assumes cursor in item line."
5837 (let* ((bolpos (point-at-bol))
5838 (ind (org-get-indentation))
5839 ind-down ind-up pos)
5840 (save-excursion
5841 (org-beginning-of-item-list)
5842 (skip-chars-backward "\n\r \t")
5843 (when (org-in-item-p)
5844 (org-beginning-of-item)
5845 (setq ind-up (org-get-indentation))))
5846 (setq pos (point))
5847 (save-excursion
5848 (cond
5849 ((and (condition-case nil (progn (org-previous-item) t)
5850 (error nil))
5851 (or (forward-char 1) t)
5852 (re-search-forward "^\\([ \t]*\\([-+]\\|\\([0-9]+[.)]\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)" bolpos t))
5853 (setq ind-down (org-get-indentation)))
5854 ((and (goto-char pos)
5855 (org-at-item-p))
5856 (goto-char (match-end 0))
5857 (skip-chars-forward " \t")
5858 (setq ind-down (current-column)))))
5859 (list ind ind-up ind-down)))
5861 ;;; The orgstruct minor mode
5863 ;; Define a minor mode which can be used in other modes in order to
5864 ;; integrate the org-mode structure editing commands.
5866 ;; This is really a hack, because the org-mode structure commands use
5867 ;; keys which normally belong to the major mode. Here is how it
5868 ;; works: The minor mode defines all the keys necessary to operate the
5869 ;; structure commands, but wraps the commands into a function which
5870 ;; tests if the cursor is currently at a headline or a plain list
5871 ;; item. If that is the case, the structure command is used,
5872 ;; temporarily setting many Org-mode variables like regular
5873 ;; expressions for filling etc. However, when any of those keys is
5874 ;; used at a different location, function uses `key-binding' to look
5875 ;; up if the key has an associated command in another currently active
5876 ;; keymap (minor modes, major mode, global), and executes that
5877 ;; command. There might be problems if any of the keys is otherwise
5878 ;; used as a prefix key.
5880 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
5881 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
5882 ;; addresses this by checking explicitly for both bindings.
5884 (defvar orgstruct-mode-map (make-sparse-keymap)
5885 "Keymap for the minor `orgstruct-mode'.")
5887 (defvar org-local-vars nil
5888 "List of local variables, for use by `orgstruct-mode'")
5890 ;;;###autoload
5891 (define-minor-mode orgstruct-mode
5892 "Toggle the minor more `orgstruct-mode'.
5893 This mode is for using Org-mode structure commands in other modes.
5894 The following key behave as if Org-mode was active, if the cursor
5895 is on a headline, or on a plain list item (both in the definition
5896 of Org-mode).
5898 M-up Move entry/item up
5899 M-down Move entry/item down
5900 M-left Promote
5901 M-right Demote
5902 M-S-up Move entry/item up
5903 M-S-down Move entry/item down
5904 M-S-left Promote subtree
5905 M-S-right Demote subtree
5906 M-q Fill paragraph and items like in Org-mode
5907 C-c ^ Sort entries
5908 C-c - Cycle list bullet
5909 TAB Cycle item visibility
5910 M-RET Insert new heading/item
5911 S-M-RET Insert new TODO heading / Chekbox item
5912 C-c C-c Set tags / toggle checkbox"
5913 nil " OrgStruct" nil
5914 (org-load-modules-maybe)
5915 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
5917 ;;;###autoload
5918 (defun turn-on-orgstruct ()
5919 "Unconditionally turn on `orgstruct-mode'."
5920 (orgstruct-mode 1))
5922 ;;;###autoload
5923 (defun turn-on-orgstruct++ ()
5924 "Unconditionally turn on `orgstruct-mode', and force org-mode indentations.
5925 In addition to setting orgstruct-mode, this also exports all indentation and
5926 autofilling variables from org-mode into the buffer. Note that turning
5927 off orgstruct-mode will *not* remove these additional settings."
5928 (orgstruct-mode 1)
5929 (let (var val)
5930 (mapc
5931 (lambda (x)
5932 (when (string-match
5933 "^\\(paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
5934 (symbol-name (car x)))
5935 (setq var (car x) val (nth 1 x))
5936 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
5937 org-local-vars)))
5939 (defun orgstruct-error ()
5940 "Error when there is no default binding for a structure key."
5941 (interactive)
5942 (error "This key has no function outside structure elements"))
5944 (defun orgstruct-setup ()
5945 "Setup orgstruct keymaps."
5946 (let ((nfunc 0)
5947 (bindings
5948 (list
5949 '([(meta up)] org-metaup)
5950 '([(meta down)] org-metadown)
5951 '([(meta left)] org-metaleft)
5952 '([(meta right)] org-metaright)
5953 '([(meta shift up)] org-shiftmetaup)
5954 '([(meta shift down)] org-shiftmetadown)
5955 '([(meta shift left)] org-shiftmetaleft)
5956 '([(meta shift right)] org-shiftmetaright)
5957 '([(shift up)] org-shiftup)
5958 '([(shift down)] org-shiftdown)
5959 '("\C-c\C-c" org-ctrl-c-ctrl-c)
5960 '("\M-q" fill-paragraph)
5961 '("\C-c^" org-sort)
5962 '("\C-c-" org-cycle-list-bullet)))
5963 elt key fun cmd)
5964 (while (setq elt (pop bindings))
5965 (setq nfunc (1+ nfunc))
5966 (setq key (org-key (car elt))
5967 fun (nth 1 elt)
5968 cmd (orgstruct-make-binding fun nfunc key))
5969 (org-defkey orgstruct-mode-map key cmd))
5971 ;; Special treatment needed for TAB and RET
5972 (org-defkey orgstruct-mode-map [(tab)]
5973 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
5974 (org-defkey orgstruct-mode-map "\C-i"
5975 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
5977 (org-defkey orgstruct-mode-map "\M-\C-m"
5978 (orgstruct-make-binding 'org-insert-heading 105
5979 "\M-\C-m" [(meta return)]))
5980 (org-defkey orgstruct-mode-map [(meta return)]
5981 (orgstruct-make-binding 'org-insert-heading 106
5982 [(meta return)] "\M-\C-m"))
5984 (org-defkey orgstruct-mode-map [(shift meta return)]
5985 (orgstruct-make-binding 'org-insert-todo-heading 107
5986 [(meta return)] "\M-\C-m"))
5988 (unless org-local-vars
5989 (setq org-local-vars (org-get-local-variables)))
5993 (defun orgstruct-make-binding (fun n &rest keys)
5994 "Create a function for binding in the structure minor mode.
5995 FUN is the command to call inside a table. N is used to create a unique
5996 command name. KEYS are keys that should be checked in for a command
5997 to execute outside of tables."
5998 (eval
5999 (list 'defun
6000 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
6001 '(arg)
6002 (concat "In Structure, run `" (symbol-name fun) "'.\n"
6003 "Outside of structure, run the binding of `"
6004 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
6005 "'.")
6006 '(interactive "p")
6007 (list 'if
6008 '(org-context-p 'headline 'item)
6009 (list 'org-run-like-in-org-mode (list 'quote fun))
6010 (list 'let '(orgstruct-mode)
6011 (list 'call-interactively
6012 (append '(or)
6013 (mapcar (lambda (k)
6014 (list 'key-binding k))
6015 keys)
6016 '('orgstruct-error))))))))
6018 (defun org-context-p (&rest contexts)
6019 "Check if local context is and of CONTEXTS.
6020 Possible values in the list of contexts are `table', `headline', and `item'."
6021 (let ((pos (point)))
6022 (goto-char (point-at-bol))
6023 (prog1 (or (and (memq 'table contexts)
6024 (looking-at "[ \t]*|"))
6025 (and (memq 'headline contexts)
6026 (looking-at "\\*+"))
6027 (and (memq 'item contexts)
6028 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)")))
6029 (goto-char pos))))
6031 (defun org-get-local-variables ()
6032 "Return a list of all local variables in an org-mode buffer."
6033 (let (varlist)
6034 (with-current-buffer (get-buffer-create "*Org tmp*")
6035 (erase-buffer)
6036 (org-mode)
6037 (setq varlist (buffer-local-variables)))
6038 (kill-buffer "*Org tmp*")
6039 (delq nil
6040 (mapcar
6041 (lambda (x)
6042 (setq x
6043 (if (symbolp x)
6044 (list x)
6045 (list (car x) (list 'quote (cdr x)))))
6046 (if (string-match
6047 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
6048 (symbol-name (car x)))
6049 x nil))
6050 varlist))))
6052 ;;;###autoload
6053 (defun org-run-like-in-org-mode (cmd)
6054 (org-load-modules-maybe)
6055 (unless org-local-vars
6056 (setq org-local-vars (org-get-local-variables)))
6057 (eval (list 'let org-local-vars
6058 (list 'call-interactively (list 'quote cmd)))))
6060 ;;;; Archiving
6062 (defun org-get-category (&optional pos)
6063 "Get the category applying to position POS."
6064 (get-text-property (or pos (point)) 'org-category))
6066 (defun org-refresh-category-properties ()
6067 "Refresh category text properties in the buffer."
6068 (let ((def-cat (cond
6069 ((null org-category)
6070 (if buffer-file-name
6071 (file-name-sans-extension
6072 (file-name-nondirectory buffer-file-name))
6073 "???"))
6074 ((symbolp org-category) (symbol-name org-category))
6075 (t org-category)))
6076 beg end cat pos optionp)
6077 (org-unmodified
6078 (save-excursion
6079 (save-restriction
6080 (widen)
6081 (goto-char (point-min))
6082 (put-text-property (point) (point-max) 'org-category def-cat)
6083 (while (re-search-forward
6084 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
6085 (setq pos (match-end 0)
6086 optionp (equal (char-after (match-beginning 0)) ?#)
6087 cat (org-trim (match-string 2)))
6088 (if optionp
6089 (setq beg (point-at-bol) end (point-max))
6090 (org-back-to-heading t)
6091 (setq beg (point) end (org-end-of-subtree t t)))
6092 (put-text-property beg end 'org-category cat)
6093 (goto-char pos)))))))
6096 ;;;; Link Stuff
6098 ;;; Link abbreviations
6100 (defun org-link-expand-abbrev (link)
6101 "Apply replacements as defined in `org-link-abbrev-alist."
6102 (if (string-match "^\\([a-zA-Z][-_a-zA-Z0-9]*\\)\\(::?\\(.*\\)\\)?$" link)
6103 (let* ((key (match-string 1 link))
6104 (as (or (assoc key org-link-abbrev-alist-local)
6105 (assoc key org-link-abbrev-alist)))
6106 (tag (and (match-end 2) (match-string 3 link)))
6107 rpl)
6108 (if (not as)
6109 link
6110 (setq rpl (cdr as))
6111 (cond
6112 ((symbolp rpl) (funcall rpl tag))
6113 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
6114 (t (concat rpl tag)))))
6115 link))
6117 ;;; Storing and inserting links
6119 (defvar org-insert-link-history nil
6120 "Minibuffer history for links inserted with `org-insert-link'.")
6122 (defvar org-stored-links nil
6123 "Contains the links stored with `org-store-link'.")
6125 (defvar org-store-link-plist nil
6126 "Plist with info about the most recently link created with `org-store-link'.")
6128 (defvar org-link-protocols nil
6129 "Link protocols added to Org-mode using `org-add-link-type'.")
6131 (defvar org-store-link-functions nil
6132 "List of functions that are called to create and store a link.
6133 Each function will be called in turn until one returns a non-nil
6134 value. Each function should check if it is responsible for creating
6135 this link (for example by looking at the major mode).
6136 If not, it must exit and return nil.
6137 If yes, it should return a non-nil value after a calling
6138 `org-store-link-props' with a list of properties and values.
6139 Special properties are:
6141 :type The link prefix. like \"http\". This must be given.
6142 :link The link, like \"http://www.astro.uva.nl/~dominik\".
6143 This is obligatory as well.
6144 :description Optional default description for the second pair
6145 of brackets in an Org-mode link. The user can still change
6146 this when inserting this link into an Org-mode buffer.
6148 In addition to these, any additional properties can be specified
6149 and then used in remember templates.")
6151 (defun org-add-link-type (type &optional follow export)
6152 "Add TYPE to the list of `org-link-types'.
6153 Re-compute all regular expressions depending on `org-link-types'
6155 FOLLOW and EXPORT are two functions.
6157 FOLLOW should take the link path as the single argument and do whatever
6158 is necessary to follow the link, for example find a file or display
6159 a mail message.
6161 EXPORT should format the link path for export to one of the export formats.
6162 It should be a function accepting three arguments:
6164 path the path of the link, the text after the prefix (like \"http:\")
6165 desc the description of the link, if any, nil if there was no descripton
6166 format the export format, a symbol like `html' or `latex'.
6168 The function may use the FORMAT information to return different values
6169 depending on the format. The return value will be put literally into
6170 the exported file.
6171 Org-mode has a built-in default for exporting links. If you are happy with
6172 this default, there is no need to define an export function for the link
6173 type. For a simple example of an export function, see `org-bbdb.el'."
6174 (add-to-list 'org-link-types type t)
6175 (org-make-link-regexps)
6176 (if (assoc type org-link-protocols)
6177 (setcdr (assoc type org-link-protocols) (list follow export))
6178 (push (list type follow export) org-link-protocols)))
6181 ;;;###autoload
6182 (defun org-store-link (arg)
6183 "\\<org-mode-map>Store an org-link to the current location.
6184 This link is added to `org-stored-links' and can later be inserted
6185 into an org-buffer with \\[org-insert-link].
6187 For some link types, a prefix arg is interpreted:
6188 For links to usenet articles, arg negates `org-usenet-links-prefer-google'.
6189 For file links, arg negates `org-context-in-file-links'."
6190 (interactive "P")
6191 (org-load-modules-maybe)
6192 (setq org-store-link-plist nil) ; reset
6193 (let (link cpltxt desc description search txt)
6194 (cond
6196 ((run-hook-with-args-until-success 'org-store-link-functions)
6197 (setq link (plist-get org-store-link-plist :link)
6198 desc (or (plist-get org-store-link-plist :description) link)))
6200 ((eq major-mode 'calendar-mode)
6201 (let ((cd (calendar-cursor-to-date)))
6202 (setq link
6203 (format-time-string
6204 (car org-time-stamp-formats)
6205 (apply 'encode-time
6206 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
6207 nil nil nil))))
6208 (org-store-link-props :type "calendar" :date cd)))
6210 ((eq major-mode 'w3-mode)
6211 (setq cpltxt (url-view-url t)
6212 link (org-make-link cpltxt))
6213 (org-store-link-props :type "w3" :url (url-view-url t)))
6215 ((eq major-mode 'w3m-mode)
6216 (setq cpltxt (or w3m-current-title w3m-current-url)
6217 link (org-make-link w3m-current-url))
6218 (org-store-link-props :type "w3m" :url (url-view-url t)))
6220 ((setq search (run-hook-with-args-until-success
6221 'org-create-file-search-functions))
6222 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
6223 "::" search))
6224 (setq cpltxt (or description link)))
6226 ((eq major-mode 'image-mode)
6227 (setq cpltxt (concat "file:"
6228 (abbreviate-file-name buffer-file-name))
6229 link (org-make-link cpltxt))
6230 (org-store-link-props :type "image" :file buffer-file-name))
6232 ((eq major-mode 'dired-mode)
6233 ;; link to the file in the current line
6234 (setq cpltxt (concat "file:"
6235 (abbreviate-file-name
6236 (expand-file-name
6237 (dired-get-filename nil t))))
6238 link (org-make-link cpltxt)))
6240 ((and buffer-file-name (org-mode-p))
6241 ;; Just link to current headline
6242 (setq cpltxt (concat "file:"
6243 (abbreviate-file-name buffer-file-name)))
6244 ;; Add a context search string
6245 (when (org-xor org-context-in-file-links arg)
6246 ;; Check if we are on a target
6247 (if (org-in-regexp "<<\\(.*?\\)>>")
6248 (setq cpltxt (concat cpltxt "::" (match-string 1)))
6249 (setq txt (cond
6250 ((org-on-heading-p) nil)
6251 ((org-region-active-p)
6252 (buffer-substring (region-beginning) (region-end)))
6253 (t nil)))
6254 (when (or (null txt) (string-match "\\S-" txt))
6255 (setq cpltxt
6256 (concat cpltxt "::"
6257 (condition-case nil
6258 (org-make-org-heading-search-string txt)
6259 (error "")))
6260 desc "NONE"))))
6261 (if (string-match "::\\'" cpltxt)
6262 (setq cpltxt (substring cpltxt 0 -2)))
6263 (setq link (org-make-link cpltxt)))
6265 ((buffer-file-name (buffer-base-buffer))
6266 ;; Just link to this file here.
6267 (setq cpltxt (concat "file:"
6268 (abbreviate-file-name
6269 (buffer-file-name (buffer-base-buffer)))))
6270 ;; Add a context string
6271 (when (org-xor org-context-in-file-links arg)
6272 (setq txt (if (org-region-active-p)
6273 (buffer-substring (region-beginning) (region-end))
6274 (buffer-substring (point-at-bol) (point-at-eol))))
6275 ;; Only use search option if there is some text.
6276 (when (string-match "\\S-" txt)
6277 (setq cpltxt
6278 (concat cpltxt "::" (org-make-org-heading-search-string txt))
6279 desc "NONE")))
6280 (setq link (org-make-link cpltxt)))
6282 ((interactive-p)
6283 (error "Cannot link to a buffer which is not visiting a file"))
6285 (t (setq link nil)))
6287 (if (consp link) (setq cpltxt (car link) link (cdr link)))
6288 (setq link (or link cpltxt)
6289 desc (or desc cpltxt))
6290 (if (equal desc "NONE") (setq desc nil))
6292 (if (and (interactive-p) link)
6293 (progn
6294 (setq org-stored-links
6295 (cons (list link desc) org-stored-links))
6296 (message "Stored: %s" (or desc link)))
6297 (and link (org-make-link-string link desc)))))
6299 (defun org-store-link-props (&rest plist)
6300 "Store link properties, extract names and addresses."
6301 (let (x adr)
6302 (when (setq x (plist-get plist :from))
6303 (setq adr (mail-extract-address-components x))
6304 (plist-put plist :fromname (car adr))
6305 (plist-put plist :fromaddress (nth 1 adr)))
6306 (when (setq x (plist-get plist :to))
6307 (setq adr (mail-extract-address-components x))
6308 (plist-put plist :toname (car adr))
6309 (plist-put plist :toaddress (nth 1 adr))))
6310 (let ((from (plist-get plist :from))
6311 (to (plist-get plist :to)))
6312 (when (and from to org-from-is-user-regexp)
6313 (plist-put plist :fromto
6314 (if (string-match org-from-is-user-regexp from)
6315 (concat "to %t")
6316 (concat "from %f")))))
6317 (setq org-store-link-plist plist))
6319 (defun org-add-link-props (&rest plist)
6320 "Add these properties to the link property list."
6321 (let (key value)
6322 (while plist
6323 (setq key (pop plist) value (pop plist))
6324 (setq org-store-link-plist
6325 (plist-put org-store-link-plist key value)))))
6327 (defun org-email-link-description (&optional fmt)
6328 "Return the description part of an email link.
6329 This takes information from `org-store-link-plist' and formats it
6330 according to FMT (default from `org-email-link-description-format')."
6331 (setq fmt (or fmt org-email-link-description-format))
6332 (let* ((p org-store-link-plist)
6333 (to (plist-get p :toaddress))
6334 (from (plist-get p :fromaddress))
6335 (table
6336 (list
6337 (cons "%c" (plist-get p :fromto))
6338 (cons "%F" (plist-get p :from))
6339 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
6340 (cons "%T" (plist-get p :to))
6341 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
6342 (cons "%s" (plist-get p :subject))
6343 (cons "%m" (plist-get p :message-id)))))
6344 (when (string-match "%c" fmt)
6345 ;; Check if the user wrote this message
6346 (if (and org-from-is-user-regexp from to
6347 (save-match-data (string-match org-from-is-user-regexp from)))
6348 (setq fmt (replace-match "to %t" t t fmt))
6349 (setq fmt (replace-match "from %f" t t fmt))))
6350 (org-replace-escapes fmt table)))
6352 (defun org-make-org-heading-search-string (&optional string heading)
6353 "Make search string for STRING or current headline."
6354 (interactive)
6355 (let ((s (or string (org-get-heading))))
6356 (unless (and string (not heading))
6357 ;; We are using a headline, clean up garbage in there.
6358 (if (string-match org-todo-regexp s)
6359 (setq s (replace-match "" t t s)))
6360 (if (string-match (org-re ":[[:alnum:]_@:]+:[ \t]*$") s)
6361 (setq s (replace-match "" t t s)))
6362 (setq s (org-trim s))
6363 (if (string-match (concat "^\\(" org-quote-string "\\|"
6364 org-comment-string "\\)") s)
6365 (setq s (replace-match "" t t s)))
6366 (while (string-match org-ts-regexp s)
6367 (setq s (replace-match "" t t s))))
6368 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
6369 (setq s (replace-match " " t t s)))
6370 (or string (setq s (concat "*" s))) ; Add * for headlines
6371 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
6373 (defun org-make-link (&rest strings)
6374 "Concatenate STRINGS."
6375 (apply 'concat strings))
6377 (defun org-make-link-string (link &optional description)
6378 "Make a link with brackets, consisting of LINK and DESCRIPTION."
6379 (unless (string-match "\\S-" link)
6380 (error "Empty link"))
6381 (when (stringp description)
6382 ;; Remove brackets from the description, they are fatal.
6383 (while (string-match "\\[" description)
6384 (setq description (replace-match "{" t t description)))
6385 (while (string-match "\\]" description)
6386 (setq description (replace-match "}" t t description))))
6387 (when (equal (org-link-escape link) description)
6388 ;; No description needed, it is identical
6389 (setq description nil))
6390 (when (and (not description)
6391 (not (equal link (org-link-escape link))))
6392 (setq description link))
6393 (concat "[[" (org-link-escape link) "]"
6394 (if description (concat "[" description "]") "")
6395 "]"))
6397 (defconst org-link-escape-chars
6398 '((?\ . "%20")
6399 (?\[ . "%5B")
6400 (?\] . "%5D")
6401 (?\340 . "%E0") ; `a
6402 (?\342 . "%E2") ; ^a
6403 (?\347 . "%E7") ; ,c
6404 (?\350 . "%E8") ; `e
6405 (?\351 . "%E9") ; 'e
6406 (?\352 . "%EA") ; ^e
6407 (?\356 . "%EE") ; ^i
6408 (?\364 . "%F4") ; ^o
6409 (?\371 . "%F9") ; `u
6410 (?\373 . "%FB") ; ^u
6411 (?\; . "%3B")
6412 (?? . "%3F")
6413 (?= . "%3D")
6414 (?+ . "%2B")
6416 "Association list of escapes for some characters problematic in links.
6417 This is the list that is used for internal purposes.")
6419 (defconst org-link-escape-chars-browser
6420 '((?\ . "%20")) ; 32 for the SPC char
6421 "Association list of escapes for some characters problematic in links.
6422 This is the list that is used before handing over to the browser.")
6424 (defun org-link-escape (text &optional table)
6425 "Escape charaters in TEXT that are problematic for links."
6426 (setq table (or table org-link-escape-chars))
6427 (when text
6428 (let ((re (mapconcat (lambda (x) (regexp-quote
6429 (char-to-string (car x))))
6430 table "\\|")))
6431 (while (string-match re text)
6432 (setq text
6433 (replace-match
6434 (cdr (assoc (string-to-char (match-string 0 text))
6435 table))
6436 t t text)))
6437 text)))
6439 (defun org-link-unescape (text &optional table)
6440 "Reverse the action of `org-link-escape'."
6441 (setq table (or table org-link-escape-chars))
6442 (when text
6443 (let ((re (mapconcat (lambda (x) (regexp-quote (cdr x)))
6444 table "\\|")))
6445 (while (string-match re text)
6446 (setq text
6447 (replace-match
6448 (char-to-string (car (rassoc (match-string 0 text) table)))
6449 t t text)))
6450 text)))
6452 (defun org-xor (a b)
6453 "Exclusive or."
6454 (if a (not b) b))
6456 (defun org-get-header (header)
6457 "Find a header field in the current buffer."
6458 (save-excursion
6459 (goto-char (point-min))
6460 (let ((case-fold-search t) s)
6461 (cond
6462 ((eq header 'from)
6463 (if (re-search-forward "^From:\\s-+\\(.*\\)" nil t)
6464 (setq s (match-string 1)))
6465 (while (string-match "\"" s)
6466 (setq s (replace-match "" t t s)))
6467 (if (string-match "[<(].*" s)
6468 (setq s (replace-match "" t t s))))
6469 ((eq header 'message-id)
6470 (if (re-search-forward "^message-id:\\s-+\\(.*\\)" nil t)
6471 (setq s (match-string 1))))
6472 ((eq header 'subject)
6473 (if (re-search-forward "^subject:\\s-+\\(.*\\)" nil t)
6474 (setq s (match-string 1)))))
6475 (if (string-match "\\`[ \t\]+" s) (setq s (replace-match "" t t s)))
6476 (if (string-match "[ \t\]+\\'" s) (setq s (replace-match "" t t s)))
6477 s)))
6480 (defun org-fixup-message-id-for-http (s)
6481 "Replace special characters in a message id, so it can be used in an http query."
6482 (while (string-match "<" s)
6483 (setq s (replace-match "%3C" t t s)))
6484 (while (string-match ">" s)
6485 (setq s (replace-match "%3E" t t s)))
6486 (while (string-match "@" s)
6487 (setq s (replace-match "%40" t t s)))
6490 ;;;###autoload
6491 (defun org-insert-link-global ()
6492 "Insert a link like Org-mode does.
6493 This command can be called in any mode to insert a link in Org-mode syntax."
6494 (interactive)
6495 (org-load-modules-maybe)
6496 (org-run-like-in-org-mode 'org-insert-link))
6498 (defun org-insert-link (&optional complete-file link-location)
6499 "Insert a link. At the prompt, enter the link.
6501 Completion can be used to select a link previously stored with
6502 `org-store-link'. When the empty string is entered (i.e. if you just
6503 press RET at the prompt), the link defaults to the most recently
6504 stored link. As SPC triggers completion in the minibuffer, you need to
6505 use M-SPC or C-q SPC to force the insertion of a space character.
6507 You will also be prompted for a description, and if one is given, it will
6508 be displayed in the buffer instead of the link.
6510 If there is already a link at point, this command will allow you to edit link
6511 and description parts.
6513 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
6514 be selected using completion. The path to the file will be relative to the
6515 current directory if the file is in the current directory or a subdirectory.
6516 Otherwise, the link will be the absolute path as completed in the minibuffer
6517 \(i.e. normally ~/path/to/file).
6519 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
6520 the current directory or below. With three \\[universal-argument] prefixes, negate the meaning
6521 of `org-keep-stored-link-after-insertion'.
6523 If `org-make-link-description-function' is non-nil, this function will be
6524 called with the link target, and the result will be the default
6525 link description.
6527 If the LINK-LOCATION parameter is non-nil, this value will be
6528 used as the link location instead of reading one interactively."
6529 (interactive "P")
6530 (let* ((wcf (current-window-configuration))
6531 (region (if (org-region-active-p)
6532 (buffer-substring (region-beginning) (region-end))))
6533 (remove (and region (list (region-beginning) (region-end))))
6534 (desc region)
6535 tmphist ; byte-compile incorrectly complains about this
6536 (link link-location)
6537 entry file)
6538 (cond
6539 (link-location) ; specified by arg, just use it.
6540 ((org-in-regexp org-bracket-link-regexp 1)
6541 ;; We do have a link at point, and we are going to edit it.
6542 (setq remove (list (match-beginning 0) (match-end 0)))
6543 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
6544 (setq link (read-string "Link: "
6545 (org-link-unescape
6546 (org-match-string-no-properties 1)))))
6547 ((or (org-in-regexp org-angle-link-re)
6548 (org-in-regexp org-plain-link-re))
6549 ;; Convert to bracket link
6550 (setq remove (list (match-beginning 0) (match-end 0))
6551 link (read-string "Link: "
6552 (org-remove-angle-brackets (match-string 0)))))
6553 ((equal complete-file '(4))
6554 ;; Completing read for file names.
6555 (setq file (read-file-name "File: "))
6556 (let ((pwd (file-name-as-directory (expand-file-name ".")))
6557 (pwd1 (file-name-as-directory (abbreviate-file-name
6558 (expand-file-name ".")))))
6559 (cond
6560 ((equal complete-file '(16))
6561 (setq link (org-make-link
6562 "file:"
6563 (abbreviate-file-name (expand-file-name file)))))
6564 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
6565 (setq link (org-make-link "file:" (match-string 1 file))))
6566 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
6567 (expand-file-name file))
6568 (setq link (org-make-link
6569 "file:" (match-string 1 (expand-file-name file)))))
6570 (t (setq link (org-make-link "file:" file))))))
6572 ;; Read link, with completion for stored links.
6573 (with-output-to-temp-buffer "*Org Links*"
6574 (princ "Insert a link. Use TAB to complete valid link prefixes.\n")
6575 (when org-stored-links
6576 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
6577 (princ (mapconcat
6578 (lambda (x)
6579 (if (nth 1 x) (concat (car x) " (" (nth 1 x) ")") (car x)))
6580 (reverse org-stored-links) "\n"))))
6581 (let ((cw (selected-window)))
6582 (select-window (get-buffer-window "*Org Links*"))
6583 (shrink-window-if-larger-than-buffer)
6584 (setq truncate-lines t)
6585 (select-window cw))
6586 ;; Fake a link history, containing the stored links.
6587 (setq tmphist (append (mapcar 'car org-stored-links)
6588 org-insert-link-history))
6589 (unwind-protect
6590 (setq link (org-completing-read
6591 "Link: "
6592 (append
6593 (mapcar (lambda (x) (list (concat (car x) ":")))
6594 (append org-link-abbrev-alist-local org-link-abbrev-alist))
6595 (mapcar (lambda (x) (list (concat x ":")))
6596 org-link-types))
6597 nil nil nil
6598 'tmphist
6599 (or (car (car org-stored-links)))))
6600 (set-window-configuration wcf)
6601 (kill-buffer "*Org Links*"))
6602 (setq entry (assoc link org-stored-links))
6603 (or entry (push link org-insert-link-history))
6604 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
6605 (not org-keep-stored-link-after-insertion))
6606 (setq org-stored-links (delq (assoc link org-stored-links)
6607 org-stored-links)))
6608 (setq desc (or desc (nth 1 entry)))))
6610 (if (string-match org-plain-link-re link)
6611 ;; URL-like link, normalize the use of angular brackets.
6612 (setq link (org-make-link (org-remove-angle-brackets link))))
6614 ;; Check if we are linking to the current file with a search option
6615 ;; If yes, simplify the link by using only the search option.
6616 (when (and buffer-file-name
6617 (string-match "\\<file:\\(.+?\\)::\\([^>]+\\)" link))
6618 (let* ((path (match-string 1 link))
6619 (case-fold-search nil)
6620 (search (match-string 2 link)))
6621 (save-match-data
6622 (if (equal (file-truename buffer-file-name) (file-truename path))
6623 ;; We are linking to this same file, with a search option
6624 (setq link search)))))
6626 ;; Check if we can/should use a relative path. If yes, simplify the link
6627 (when (string-match "\\<file:\\(.*\\)" link)
6628 (let* ((path (match-string 1 link))
6629 (origpath path)
6630 (case-fold-search nil))
6631 (cond
6632 ((eq org-link-file-path-type 'absolute)
6633 (setq path (abbreviate-file-name (expand-file-name path))))
6634 ((eq org-link-file-path-type 'noabbrev)
6635 (setq path (expand-file-name path)))
6636 ((eq org-link-file-path-type 'relative)
6637 (setq path (file-relative-name path)))
6639 (save-match-data
6640 (if (string-match (concat "^" (regexp-quote
6641 (file-name-as-directory
6642 (expand-file-name "."))))
6643 (expand-file-name path))
6644 ;; We are linking a file with relative path name.
6645 (setq path (substring (expand-file-name path)
6646 (match-end 0)))))))
6647 (setq link (concat "file:" path))
6648 (if (equal desc origpath)
6649 (setq desc path))))
6651 (if org-make-link-description-function
6652 (setq desc (funcall org-make-link-description-function link desc)))
6654 (setq desc (read-string "Description: " desc))
6655 (unless (string-match "\\S-" desc) (setq desc nil))
6656 (if remove (apply 'delete-region remove))
6657 (insert (org-make-link-string link desc))))
6659 (defun org-completing-read (&rest args)
6660 (let ((minibuffer-local-completion-map
6661 (copy-keymap minibuffer-local-completion-map)))
6662 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
6663 (apply 'completing-read args)))
6665 ;;; Opening/following a link
6667 (defvar org-link-search-failed nil)
6669 (defun org-next-link ()
6670 "Move forward to the next link.
6671 If the link is in hidden text, expose it."
6672 (interactive)
6673 (when (and org-link-search-failed (eq this-command last-command))
6674 (goto-char (point-min))
6675 (message "Link search wrapped back to beginning of buffer"))
6676 (setq org-link-search-failed nil)
6677 (let* ((pos (point))
6678 (ct (org-context))
6679 (a (assoc :link ct)))
6680 (if a (goto-char (nth 2 a)))
6681 (if (re-search-forward org-any-link-re nil t)
6682 (progn
6683 (goto-char (match-beginning 0))
6684 (if (org-invisible-p) (org-show-context)))
6685 (goto-char pos)
6686 (setq org-link-search-failed t)
6687 (error "No further link found"))))
6689 (defun org-previous-link ()
6690 "Move backward to the previous link.
6691 If the link is in hidden text, expose it."
6692 (interactive)
6693 (when (and org-link-search-failed (eq this-command last-command))
6694 (goto-char (point-max))
6695 (message "Link search wrapped back to end of buffer"))
6696 (setq org-link-search-failed nil)
6697 (let* ((pos (point))
6698 (ct (org-context))
6699 (a (assoc :link ct)))
6700 (if a (goto-char (nth 1 a)))
6701 (if (re-search-backward org-any-link-re nil t)
6702 (progn
6703 (goto-char (match-beginning 0))
6704 (if (org-invisible-p) (org-show-context)))
6705 (goto-char pos)
6706 (setq org-link-search-failed t)
6707 (error "No further link found"))))
6709 (defun org-find-file-at-mouse (ev)
6710 "Open file link or URL at mouse."
6711 (interactive "e")
6712 (mouse-set-point ev)
6713 (org-open-at-point 'in-emacs))
6715 (defun org-open-at-mouse (ev)
6716 "Open file link or URL at mouse."
6717 (interactive "e")
6718 (mouse-set-point ev)
6719 (org-open-at-point))
6721 (defvar org-window-config-before-follow-link nil
6722 "The window configuration before following a link.
6723 This is saved in case the need arises to restore it.")
6725 (defvar org-open-link-marker (make-marker)
6726 "Marker pointing to the location where `org-open-at-point; was called.")
6728 ;;;###autoload
6729 (defun org-open-at-point-global ()
6730 "Follow a link like Org-mode does.
6731 This command can be called in any mode to follow a link that has
6732 Org-mode syntax."
6733 (interactive)
6734 (org-run-like-in-org-mode 'org-open-at-point))
6736 ;;;###autoload
6737 (defun org-open-link-from-string (s &optional arg)
6738 "Open a link in the string S, as if it was in Org-mode."
6739 (interactive "sLink: \nP")
6740 (with-temp-buffer
6741 (let ((org-inhibit-startup t))
6742 (org-mode)
6743 (insert s)
6744 (goto-char (point-min))
6745 (org-open-at-point arg))))
6747 (defun org-open-at-point (&optional in-emacs)
6748 "Open link at or after point.
6749 If there is no link at point, this function will search forward up to
6750 the end of the current subtree.
6751 Normally, files will be opened by an appropriate application. If the
6752 optional argument IN-EMACS is non-nil, Emacs will visit the file."
6753 (interactive "P")
6754 (org-load-modules-maybe)
6755 (move-marker org-open-link-marker (point))
6756 (setq org-window-config-before-follow-link (current-window-configuration))
6757 (org-remove-occur-highlights nil nil t)
6758 (if (org-at-timestamp-p t)
6759 (org-follow-timestamp-link)
6760 (let (type path link line search (pos (point)))
6761 (catch 'match
6762 (save-excursion
6763 (skip-chars-forward "^]\n\r")
6764 (when (org-in-regexp org-bracket-link-regexp)
6765 (setq link (org-link-unescape (org-match-string-no-properties 1)))
6766 (while (string-match " *\n *" link)
6767 (setq link (replace-match " " t t link)))
6768 (setq link (org-link-expand-abbrev link))
6769 (if (string-match org-link-re-with-space2 link)
6770 (setq type (match-string 1 link) path (match-string 2 link))
6771 (setq type "thisfile" path link))
6772 (throw 'match t)))
6774 (when (get-text-property (point) 'org-linked-text)
6775 (setq type "thisfile"
6776 pos (if (get-text-property (1+ (point)) 'org-linked-text)
6777 (1+ (point)) (point))
6778 path (buffer-substring
6779 (previous-single-property-change pos 'org-linked-text)
6780 (next-single-property-change pos 'org-linked-text)))
6781 (throw 'match t))
6783 (save-excursion
6784 (when (or (org-in-regexp org-angle-link-re)
6785 (org-in-regexp org-plain-link-re))
6786 (setq type (match-string 1) path (match-string 2))
6787 (throw 'match t)))
6788 (when (org-in-regexp "\\<\\([^><\n]+\\)\\>")
6789 (setq type "tree-match"
6790 path (match-string 1))
6791 (throw 'match t))
6792 (save-excursion
6793 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@:]+\\):[ \t]*$"))
6794 (setq type "tags"
6795 path (match-string 1))
6796 (while (string-match ":" path)
6797 (setq path (replace-match "+" t t path)))
6798 (throw 'match t))))
6799 (unless path
6800 (error "No link found"))
6801 ;; Remove any trailing spaces in path
6802 (if (string-match " +\\'" path)
6803 (setq path (replace-match "" t t path)))
6805 (cond
6807 ((assoc type org-link-protocols)
6808 (funcall (nth 1 (assoc type org-link-protocols)) path))
6810 ((equal type "mailto")
6811 (let ((cmd (car org-link-mailto-program))
6812 (args (cdr org-link-mailto-program)) args1
6813 (address path) (subject "") a)
6814 (if (string-match "\\(.*\\)::\\(.*\\)" path)
6815 (setq address (match-string 1 path)
6816 subject (org-link-escape (match-string 2 path))))
6817 (while args
6818 (cond
6819 ((not (stringp (car args))) (push (pop args) args1))
6820 (t (setq a (pop args))
6821 (if (string-match "%a" a)
6822 (setq a (replace-match address t t a)))
6823 (if (string-match "%s" a)
6824 (setq a (replace-match subject t t a)))
6825 (push a args1))))
6826 (apply cmd (nreverse args1))))
6828 ((member type '("http" "https" "ftp" "news"))
6829 (browse-url (concat type ":" (org-link-escape
6830 path org-link-escape-chars-browser))))
6832 ((member type '("message"))
6833 (browse-url (concat type ":" path)))
6835 ((string= type "tags")
6836 (org-tags-view in-emacs path))
6837 ((string= type "thisfile")
6838 (if in-emacs
6839 (switch-to-buffer-other-window
6840 (org-get-buffer-for-internal-link (current-buffer)))
6841 (org-mark-ring-push))
6842 (let ((cmd `(org-link-search
6843 ,path
6844 ,(cond ((equal in-emacs '(4)) 'occur)
6845 ((equal in-emacs '(16)) 'org-occur)
6846 (t nil))
6847 ,pos)))
6848 (condition-case nil (eval cmd)
6849 (error (progn (widen) (eval cmd))))))
6851 ((string= type "tree-match")
6852 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
6854 ((string= type "file")
6855 (if (string-match "::\\([0-9]+\\)\\'" path)
6856 (setq line (string-to-number (match-string 1 path))
6857 path (substring path 0 (match-beginning 0)))
6858 (if (string-match "::\\(.+\\)\\'" path)
6859 (setq search (match-string 1 path)
6860 path (substring path 0 (match-beginning 0)))))
6861 (if (string-match "[*?{]" (file-name-nondirectory path))
6862 (dired path)
6863 (org-open-file path in-emacs line search)))
6865 ((string= type "news")
6866 (require 'org-gnus)
6867 (org-gnus-follow-link path))
6869 ((string= type "shell")
6870 (let ((cmd path))
6871 (if (or (not org-confirm-shell-link-function)
6872 (funcall org-confirm-shell-link-function
6873 (format "Execute \"%s\" in shell? "
6874 (org-add-props cmd nil
6875 'face 'org-warning))))
6876 (progn
6877 (message "Executing %s" cmd)
6878 (shell-command cmd))
6879 (error "Abort"))))
6881 ((string= type "elisp")
6882 (let ((cmd path))
6883 (if (or (not org-confirm-elisp-link-function)
6884 (funcall org-confirm-elisp-link-function
6885 (format "Execute \"%s\" as elisp? "
6886 (org-add-props cmd nil
6887 'face 'org-warning))))
6888 (message "%s => %s" cmd (eval (read cmd)))
6889 (error "Abort"))))
6892 (browse-url-at-point)))))
6893 (move-marker org-open-link-marker nil)
6894 (run-hook-with-args 'org-follow-link-hook))
6896 ;;;; Time estimates
6898 (defun org-get-effort (&optional pom)
6899 "Get the effort estimate for the current entry."
6900 (org-entry-get pom org-effort-property))
6902 ;;; File search
6904 (defvar org-create-file-search-functions nil
6905 "List of functions to construct the right search string for a file link.
6906 These functions are called in turn with point at the location to
6907 which the link should point.
6909 A function in the hook should first test if it would like to
6910 handle this file type, for example by checking the major-mode or
6911 the file extension. If it decides not to handle this file, it
6912 should just return nil to give other functions a chance. If it
6913 does handle the file, it must return the search string to be used
6914 when following the link. The search string will be part of the
6915 file link, given after a double colon, and `org-open-at-point'
6916 will automatically search for it. If special measures must be
6917 taken to make the search successful, another function should be
6918 added to the companion hook `org-execute-file-search-functions',
6919 which see.
6921 A function in this hook may also use `setq' to set the variable
6922 `description' to provide a suggestion for the descriptive text to
6923 be used for this link when it gets inserted into an Org-mode
6924 buffer with \\[org-insert-link].")
6926 (defvar org-execute-file-search-functions nil
6927 "List of functions to execute a file search triggered by a link.
6929 Functions added to this hook must accept a single argument, the
6930 search string that was part of the file link, the part after the
6931 double colon. The function must first check if it would like to
6932 handle this search, for example by checking the major-mode or the
6933 file extension. If it decides not to handle this search, it
6934 should just return nil to give other functions a chance. If it
6935 does handle the search, it must return a non-nil value to keep
6936 other functions from trying.
6938 Each function can access the current prefix argument through the
6939 variable `current-prefix-argument'. Note that a single prefix is
6940 used to force opening a link in Emacs, so it may be good to only
6941 use a numeric or double prefix to guide the search function.
6943 In case this is needed, a function in this hook can also restore
6944 the window configuration before `org-open-at-point' was called using:
6946 (set-window-configuration org-window-config-before-follow-link)")
6948 (defun org-link-search (s &optional type avoid-pos)
6949 "Search for a link search option.
6950 If S is surrounded by forward slashes, it is interpreted as a
6951 regular expression. In org-mode files, this will create an `org-occur'
6952 sparse tree. In ordinary files, `occur' will be used to list matches.
6953 If the current buffer is in `dired-mode', grep will be used to search
6954 in all files. If AVOID-POS is given, ignore matches near that position."
6955 (let ((case-fold-search t)
6956 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
6957 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
6958 (append '(("") (" ") ("\t") ("\n"))
6959 org-emphasis-alist)
6960 "\\|") "\\)"))
6961 (pos (point))
6962 (pre nil) (post nil)
6963 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
6964 (cond
6965 ;; First check if there are any special
6966 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
6967 ;; Now try the builtin stuff
6968 ((save-excursion
6969 (goto-char (point-min))
6970 (and
6971 (re-search-forward
6972 (concat "<<" (regexp-quote s0) ">>") nil t)
6973 (setq type 'dedicated
6974 pos (match-beginning 0))))
6975 ;; There is an exact target for this
6976 (goto-char pos))
6977 ((string-match "^/\\(.*\\)/$" s)
6978 ;; A regular expression
6979 (cond
6980 ((org-mode-p)
6981 (org-occur (match-string 1 s)))
6982 ;;((eq major-mode 'dired-mode)
6983 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
6984 (t (org-do-occur (match-string 1 s)))))
6986 ;; A normal search strings
6987 (when (equal (string-to-char s) ?*)
6988 ;; Anchor on headlines, post may include tags.
6989 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
6990 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@:+]:[ \t]*\\)?$")
6991 s (substring s 1)))
6992 (remove-text-properties
6993 0 (length s)
6994 '(face nil mouse-face nil keymap nil fontified nil) s)
6995 ;; Make a series of regular expressions to find a match
6996 (setq words (org-split-string s "[ \n\r\t]+")
6998 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
6999 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
7000 "\\)" markers)
7001 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
7002 re2a (concat "[ \t\r\n]" re2a_)
7003 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
7004 re4 (concat "[^a-zA-Z_]" re4_)
7006 re1 (concat pre re2 post)
7007 re3 (concat pre (if pre re4_ re4) post)
7008 re5 (concat pre ".*" re4)
7009 re2 (concat pre re2)
7010 re2a (concat pre (if pre re2a_ re2a))
7011 re4 (concat pre (if pre re4_ re4))
7012 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
7013 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
7014 re5 "\\)"
7016 (cond
7017 ((eq type 'org-occur) (org-occur reall))
7018 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
7019 (t (goto-char (point-min))
7020 (setq type 'fuzzy)
7021 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
7022 (org-search-not-self 1 re1 nil t)
7023 (org-search-not-self 1 re2 nil t)
7024 (org-search-not-self 1 re2a nil t)
7025 (org-search-not-self 1 re3 nil t)
7026 (org-search-not-self 1 re4 nil t)
7027 (org-search-not-self 1 re5 nil t)
7029 (goto-char (match-beginning 1))
7030 (goto-char pos)
7031 (error "No match")))))
7033 ;; Normal string-search
7034 (goto-char (point-min))
7035 (if (search-forward s nil t)
7036 (goto-char (match-beginning 0))
7037 (error "No match"))))
7038 (and (org-mode-p) (org-show-context 'link-search))
7039 type))
7041 (defun org-search-not-self (group &rest args)
7042 "Execute `re-search-forward', but only accept matches that do not
7043 enclose the position of `org-open-link-marker'."
7044 (let ((m org-open-link-marker))
7045 (catch 'exit
7046 (while (apply 're-search-forward args)
7047 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
7048 (goto-char (match-end group))
7049 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
7050 (> (match-beginning 0) (marker-position m))
7051 (< (match-end 0) (marker-position m)))
7052 (save-match-data
7053 (or (not (org-in-regexp
7054 org-bracket-link-analytic-regexp 1))
7055 (not (match-end 4)) ; no description
7056 (and (<= (match-beginning 4) (point))
7057 (>= (match-end 4) (point))))))
7058 (throw 'exit (point))))))))
7060 (defun org-get-buffer-for-internal-link (buffer)
7061 "Return a buffer to be used for displaying the link target of internal links."
7062 (cond
7063 ((not org-display-internal-link-with-indirect-buffer)
7064 buffer)
7065 ((string-match "(Clone)$" (buffer-name buffer))
7066 (message "Buffer is already a clone, not making another one")
7067 ;; we also do not modify visibility in this case
7068 buffer)
7069 (t ; make a new indirect buffer for displaying the link
7070 (let* ((bn (buffer-name buffer))
7071 (ibn (concat bn "(Clone)"))
7072 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
7073 (with-current-buffer ib (org-overview))
7074 ib))))
7076 (defun org-do-occur (regexp &optional cleanup)
7077 "Call the Emacs command `occur'.
7078 If CLEANUP is non-nil, remove the printout of the regular expression
7079 in the *Occur* buffer. This is useful if the regex is long and not useful
7080 to read."
7081 (occur regexp)
7082 (when cleanup
7083 (let ((cwin (selected-window)) win beg end)
7084 (when (setq win (get-buffer-window "*Occur*"))
7085 (select-window win))
7086 (goto-char (point-min))
7087 (when (re-search-forward "match[a-z]+" nil t)
7088 (setq beg (match-end 0))
7089 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
7090 (setq end (1- (match-beginning 0)))))
7091 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
7092 (goto-char (point-min))
7093 (select-window cwin))))
7095 ;;; The mark ring for links jumps
7097 (defvar org-mark-ring nil
7098 "Mark ring for positions before jumps in Org-mode.")
7099 (defvar org-mark-ring-last-goto nil
7100 "Last position in the mark ring used to go back.")
7101 ;; Fill and close the ring
7102 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
7103 (loop for i from 1 to org-mark-ring-length do
7104 (push (make-marker) org-mark-ring))
7105 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
7106 org-mark-ring)
7108 (defun org-mark-ring-push (&optional pos buffer)
7109 "Put the current position or POS into the mark ring and rotate it."
7110 (interactive)
7111 (setq pos (or pos (point)))
7112 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
7113 (move-marker (car org-mark-ring)
7114 (or pos (point))
7115 (or buffer (current-buffer)))
7116 (message "%s"
7117 (substitute-command-keys
7118 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
7120 (defun org-mark-ring-goto (&optional n)
7121 "Jump to the previous position in the mark ring.
7122 With prefix arg N, jump back that many stored positions. When
7123 called several times in succession, walk through the entire ring.
7124 Org-mode commands jumping to a different position in the current file,
7125 or to another Org-mode file, automatically push the old position
7126 onto the ring."
7127 (interactive "p")
7128 (let (p m)
7129 (if (eq last-command this-command)
7130 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
7131 (setq p org-mark-ring))
7132 (setq org-mark-ring-last-goto p)
7133 (setq m (car p))
7134 (switch-to-buffer (marker-buffer m))
7135 (goto-char m)
7136 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
7138 (defun org-remove-angle-brackets (s)
7139 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
7140 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
7142 (defun org-add-angle-brackets (s)
7143 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
7144 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
7147 ;;; Following specific links
7149 (defun org-follow-timestamp-link ()
7150 (cond
7151 ((org-at-date-range-p t)
7152 (let ((org-agenda-start-on-weekday)
7153 (t1 (match-string 1))
7154 (t2 (match-string 2)))
7155 (setq t1 (time-to-days (org-time-string-to-time t1))
7156 t2 (time-to-days (org-time-string-to-time t2)))
7157 (org-agenda-list nil t1 (1+ (- t2 t1)))))
7158 ((org-at-timestamp-p t)
7159 (org-agenda-list nil (time-to-days (org-time-string-to-time
7160 (substring (match-string 1) 0 10)))
7162 (t (error "This should not happen"))))
7165 ;;; Following file links
7166 (defvar org-wait nil)
7167 (defun org-open-file (path &optional in-emacs line search)
7168 "Open the file at PATH.
7169 First, this expands any special file name abbreviations. Then the
7170 configuration variable `org-file-apps' is checked if it contains an
7171 entry for this file type, and if yes, the corresponding command is launched.
7172 If no application is found, Emacs simply visits the file.
7173 With optional argument IN-EMACS, Emacs will visit the file.
7174 Optional LINE specifies a line to go to, optional SEARCH a string to
7175 search for. If LINE or SEARCH is given, the file will always be
7176 opened in Emacs.
7177 If the file does not exist, an error is thrown."
7178 (setq in-emacs (or in-emacs line search))
7179 (let* ((file (if (equal path "")
7180 buffer-file-name
7181 (substitute-in-file-name (expand-file-name path))))
7182 (apps (append org-file-apps (org-default-apps)))
7183 (remp (and (assq 'remote apps) (org-file-remote-p file)))
7184 (dirp (if remp nil (file-directory-p file)))
7185 (dfile (downcase file))
7186 (old-buffer (current-buffer))
7187 (old-pos (point))
7188 (old-mode major-mode)
7189 ext cmd)
7190 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
7191 (setq ext (match-string 1 dfile))
7192 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
7193 (setq ext (match-string 1 dfile))))
7194 (if in-emacs
7195 (setq cmd 'emacs)
7196 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
7197 (and dirp (cdr (assoc 'directory apps)))
7198 (cdr (assoc ext apps))
7199 (cdr (assoc t apps)))))
7200 (when (eq cmd 'mailcap)
7201 (require 'mailcap)
7202 (mailcap-parse-mailcaps)
7203 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
7204 (command (mailcap-mime-info mime-type)))
7205 (if (stringp command)
7206 (setq cmd command)
7207 (setq cmd 'emacs))))
7208 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
7209 (not (file-exists-p file))
7210 (not org-open-non-existing-files))
7211 (error "No such file: %s" file))
7212 (cond
7213 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
7214 ;; Remove quotes around the file name - we'll use shell-quote-argument.
7215 (while (string-match "['\"]%s['\"]" cmd)
7216 (setq cmd (replace-match "%s" t t cmd)))
7217 (while (string-match "%s" cmd)
7218 (setq cmd (replace-match
7219 (save-match-data (shell-quote-argument file))
7220 t t cmd)))
7221 (save-window-excursion
7222 (start-process-shell-command cmd nil cmd)
7223 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))
7225 ((or (stringp cmd)
7226 (eq cmd 'emacs))
7227 (funcall (cdr (assq 'file org-link-frame-setup)) file)
7228 (widen)
7229 (if line (goto-line line)
7230 (if search (org-link-search search))))
7231 ((consp cmd)
7232 (eval cmd))
7233 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
7234 (and (org-mode-p) (eq old-mode 'org-mode)
7235 (or (not (equal old-buffer (current-buffer)))
7236 (not (equal old-pos (point))))
7237 (org-mark-ring-push old-pos old-buffer))))
7239 (defun org-default-apps ()
7240 "Return the default applications for this operating system."
7241 (cond
7242 ((eq system-type 'darwin)
7243 org-file-apps-defaults-macosx)
7244 ((eq system-type 'windows-nt)
7245 org-file-apps-defaults-windowsnt)
7246 (t org-file-apps-defaults-gnu)))
7248 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
7249 (defun org-file-remote-p (file)
7250 "Test whether FILE specifies a location on a remote system.
7251 Return non-nil if the location is indeed remote.
7253 For example, the filename \"/user@host:/foo\" specifies a location
7254 on the system \"/user@host:\"."
7255 (cond ((fboundp 'file-remote-p)
7256 (file-remote-p file))
7257 ((fboundp 'tramp-handle-file-remote-p)
7258 (tramp-handle-file-remote-p file))
7259 ((and (boundp 'ange-ftp-name-format)
7260 (string-match (car ange-ftp-name-format) file))
7262 (t nil)))
7265 ;;;; Refiling
7267 (defun org-get-org-file ()
7268 "Read a filename, with default directory `org-directory'."
7269 (let ((default (or org-default-notes-file remember-data-file)))
7270 (read-file-name (format "File name [%s]: " default)
7271 (file-name-as-directory org-directory)
7272 default)))
7274 (defun org-notes-order-reversed-p ()
7275 "Check if the current file should receive notes in reversed order."
7276 (cond
7277 ((not org-reverse-note-order) nil)
7278 ((eq t org-reverse-note-order) t)
7279 ((not (listp org-reverse-note-order)) nil)
7280 (t (catch 'exit
7281 (let ((all org-reverse-note-order)
7282 entry)
7283 (while (setq entry (pop all))
7284 (if (string-match (car entry) buffer-file-name)
7285 (throw 'exit (cdr entry))))
7286 nil)))))
7288 (defvar org-refile-target-table nil
7289 "The list of refile targets, created by `org-refile'.")
7291 (defvar org-agenda-new-buffers nil
7292 "Buffers created to visit agenda files.")
7294 (defun org-get-refile-targets (&optional default-buffer)
7295 "Produce a table with refile targets."
7296 (let ((entries (or org-refile-targets '((nil . (:level . 1)))))
7297 targets txt re files f desc descre)
7298 (with-current-buffer (or default-buffer (current-buffer))
7299 (while (setq entry (pop entries))
7300 (setq files (car entry) desc (cdr entry))
7301 (cond
7302 ((null files) (setq files (list (current-buffer))))
7303 ((eq files 'org-agenda-files)
7304 (setq files (org-agenda-files 'unrestricted)))
7305 ((and (symbolp files) (fboundp files))
7306 (setq files (funcall files)))
7307 ((and (symbolp files) (boundp files))
7308 (setq files (symbol-value files))))
7309 (if (stringp files) (setq files (list files)))
7310 (cond
7311 ((eq (car desc) :tag)
7312 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
7313 ((eq (car desc) :todo)
7314 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
7315 ((eq (car desc) :regexp)
7316 (setq descre (cdr desc)))
7317 ((eq (car desc) :level)
7318 (setq descre (concat "^\\*\\{" (number-to-string
7319 (if org-odd-levels-only
7320 (1- (* 2 (cdr desc)))
7321 (cdr desc)))
7322 "\\}[ \t]")))
7323 ((eq (car desc) :maxlevel)
7324 (setq descre (concat "^\\*\\{1," (number-to-string
7325 (if org-odd-levels-only
7326 (1- (* 2 (cdr desc)))
7327 (cdr desc)))
7328 "\\}[ \t]")))
7329 (t (error "Bad refiling target description %s" desc)))
7330 (while (setq f (pop files))
7331 (save-excursion
7332 (set-buffer (if (bufferp f) f (org-get-agenda-file-buffer f)))
7333 (if (bufferp f) (setq f (buffer-file-name (buffer-base-buffer f))))
7334 (save-excursion
7335 (save-restriction
7336 (widen)
7337 (goto-char (point-min))
7338 (while (re-search-forward descre nil t)
7339 (goto-char (point-at-bol))
7340 (when (looking-at org-complex-heading-regexp)
7341 (setq txt (match-string 4)
7342 re (concat "^" (regexp-quote
7343 (buffer-substring (match-beginning 1)
7344 (match-end 4)))))
7345 (if (match-end 5) (setq re (concat re "[ \t]+"
7346 (regexp-quote
7347 (match-string 5)))))
7348 (setq re (concat re "[ \t]*$"))
7349 (when org-refile-use-outline-path
7350 (setq txt (mapconcat 'identity
7351 (append
7352 (if (eq org-refile-use-outline-path 'file)
7353 (list (file-name-nondirectory
7354 (buffer-file-name (buffer-base-buffer))))
7355 (if (eq org-refile-use-outline-path 'full-file-path)
7356 (list (buffer-file-name (buffer-base-buffer)))))
7357 (org-get-outline-path)
7358 (list txt))
7359 "/")))
7360 (push (list txt f re (point)) targets))
7361 (goto-char (point-at-eol))))))))
7362 (nreverse targets))))
7364 (defun org-get-outline-path ()
7365 "Return the outline path to the current entry, as a list."
7366 (let (rtn)
7367 (save-excursion
7368 (while (org-up-heading-safe)
7369 (when (looking-at org-complex-heading-regexp)
7370 (push (org-match-string-no-properties 4) rtn)))
7371 rtn)))
7373 (defvar org-refile-history nil
7374 "History for refiling operations.")
7376 (defun org-refile (&optional goto default-buffer)
7377 "Move the entry at point to another heading.
7378 The list of target headings is compiled using the information in
7379 `org-refile-targets', which see. This list is created before each use
7380 and will therefore always be up-to-date.
7382 At the target location, the entry is filed as a subitem of the target heading.
7383 Depending on `org-reverse-note-order', the new subitem will either be the
7384 first of the last subitem.
7386 With prefix arg GOTO, the command will only visit the target location,
7387 not actually move anything.
7388 With a double prefix `C-c C-c', go to the location where the last refiling
7389 operation has put the subtree."
7390 (interactive "P")
7391 (let* ((cbuf (current-buffer))
7392 (filename (buffer-file-name (buffer-base-buffer cbuf)))
7393 pos it nbuf file re level reversed)
7394 (if (equal goto '(16))
7395 (org-refile-goto-last-stored)
7396 (when (setq it (org-refile-get-location
7397 (if goto "Goto: " "Refile to: ") default-buffer))
7398 (setq file (nth 1 it)
7399 re (nth 2 it)
7400 pos (nth 3 it))
7401 (setq nbuf (or (find-buffer-visiting file)
7402 (find-file-noselect file)))
7403 (if goto
7404 (progn
7405 (switch-to-buffer nbuf)
7406 (goto-char pos)
7407 (org-show-context 'org-goto))
7408 (org-copy-subtree 1 nil t)
7409 (save-excursion
7410 (set-buffer (setq nbuf (or (find-buffer-visiting file)
7411 (find-file-noselect file))))
7412 (setq reversed (org-notes-order-reversed-p))
7413 (save-excursion
7414 (save-restriction
7415 (widen)
7416 (goto-char pos)
7417 (looking-at outline-regexp)
7418 (setq level (org-get-valid-level (funcall outline-level) 1))
7419 (goto-char
7420 (if reversed
7421 (outline-next-heading)
7422 (or (save-excursion (outline-get-next-sibling))
7423 (org-end-of-subtree t t)
7424 (point-max))))
7425 (bookmark-set "org-refile-last-stored")
7426 (org-paste-subtree level))))
7427 (org-cut-subtree)
7428 (setq org-markers-to-move nil)
7429 (message "Entry refiled to \"%s\"" (car it)))))))
7431 (defun org-refile-goto-last-stored ()
7432 "Go to the location where the last refile was stored."
7433 (interactive)
7434 (bookmark-jump "org-refile-last-stored")
7435 (message "This is the location of the last refile"))
7437 (defun org-refile-get-location (&optional prompt default-buffer)
7438 "Prompt the user for a refile location, using PROMPT."
7439 (let ((org-refile-targets org-refile-targets)
7440 (org-refile-use-outline-path org-refile-use-outline-path))
7441 (setq org-refile-target-table (org-get-refile-targets default-buffer)))
7442 (unless org-refile-target-table
7443 (error "No refile targets"))
7444 (let* ((cbuf (current-buffer))
7445 (filename (buffer-file-name (buffer-base-buffer cbuf)))
7446 (fname (and filename (file-truename filename)))
7447 (tbl (mapcar
7448 (lambda (x)
7449 (if (not (equal fname (file-truename (nth 1 x))))
7450 (cons (concat (car x) " (" (file-name-nondirectory
7451 (nth 1 x)) ")")
7452 (cdr x))
7454 org-refile-target-table))
7455 (completion-ignore-case t))
7456 (assoc (completing-read prompt tbl nil t nil 'org-refile-history)
7457 tbl)))
7459 ;;;; Dynamic blocks
7461 (defun org-find-dblock (name)
7462 "Find the first dynamic block with name NAME in the buffer.
7463 If not found, stay at current position and return nil."
7464 (let (pos)
7465 (save-excursion
7466 (goto-char (point-min))
7467 (setq pos (and (re-search-forward (concat "^#\\+BEGIN:[ \t]+" name "\\>")
7468 nil t)
7469 (match-beginning 0))))
7470 (if pos (goto-char pos))
7471 pos))
7473 (defconst org-dblock-start-re
7474 "^#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
7475 "Matches the startline of a dynamic block, with parameters.")
7477 (defconst org-dblock-end-re "^#\\+END\\([: \t\r\n]\\|$\\)"
7478 "Matches the end of a dyhamic block.")
7480 (defun org-create-dblock (plist)
7481 "Create a dynamic block section, with parameters taken from PLIST.
7482 PLIST must containe a :name entry which is used as name of the block."
7483 (unless (bolp) (newline))
7484 (let ((name (plist-get plist :name)))
7485 (insert "#+BEGIN: " name)
7486 (while plist
7487 (if (eq (car plist) :name)
7488 (setq plist (cddr plist))
7489 (insert " " (prin1-to-string (pop plist)))))
7490 (insert "\n\n#+END:\n")
7491 (beginning-of-line -2)))
7493 (defun org-prepare-dblock ()
7494 "Prepare dynamic block for refresh.
7495 This empties the block, puts the cursor at the insert position and returns
7496 the property list including an extra property :name with the block name."
7497 (unless (looking-at org-dblock-start-re)
7498 (error "Not at a dynamic block"))
7499 (let* ((begdel (1+ (match-end 0)))
7500 (name (org-no-properties (match-string 1)))
7501 (params (append (list :name name)
7502 (read (concat "(" (match-string 3) ")")))))
7503 (unless (re-search-forward org-dblock-end-re nil t)
7504 (error "Dynamic block not terminated"))
7505 (setq params
7506 (append params
7507 (list :content (buffer-substring
7508 begdel (match-beginning 0)))))
7509 (delete-region begdel (match-beginning 0))
7510 (goto-char begdel)
7511 (open-line 1)
7512 params))
7514 (defun org-map-dblocks (&optional command)
7515 "Apply COMMAND to all dynamic blocks in the current buffer.
7516 If COMMAND is not given, use `org-update-dblock'."
7517 (let ((cmd (or command 'org-update-dblock))
7518 pos)
7519 (save-excursion
7520 (goto-char (point-min))
7521 (while (re-search-forward org-dblock-start-re nil t)
7522 (goto-char (setq pos (match-beginning 0)))
7523 (condition-case nil
7524 (funcall cmd)
7525 (error (message "Error during update of dynamic block")))
7526 (goto-char pos)
7527 (unless (re-search-forward org-dblock-end-re nil t)
7528 (error "Dynamic block not terminated"))))))
7530 (defun org-dblock-update (&optional arg)
7531 "User command for updating dynamic blocks.
7532 Update the dynamic block at point. With prefix ARG, update all dynamic
7533 blocks in the buffer."
7534 (interactive "P")
7535 (if arg
7536 (org-update-all-dblocks)
7537 (or (looking-at org-dblock-start-re)
7538 (org-beginning-of-dblock))
7539 (org-update-dblock)))
7541 (defun org-update-dblock ()
7542 "Update the dynamic block at point
7543 This means to empty the block, parse for parameters and then call
7544 the correct writing function."
7545 (save-window-excursion
7546 (let* ((pos (point))
7547 (line (org-current-line))
7548 (params (org-prepare-dblock))
7549 (name (plist-get params :name))
7550 (cmd (intern (concat "org-dblock-write:" name))))
7551 (message "Updating dynamic block `%s' at line %d..." name line)
7552 (funcall cmd params)
7553 (message "Updating dynamic block `%s' at line %d...done" name line)
7554 (goto-char pos))))
7556 (defun org-beginning-of-dblock ()
7557 "Find the beginning of the dynamic block at point.
7558 Error if there is no scuh block at point."
7559 (let ((pos (point))
7560 beg)
7561 (end-of-line 1)
7562 (if (and (re-search-backward org-dblock-start-re nil t)
7563 (setq beg (match-beginning 0))
7564 (re-search-forward org-dblock-end-re nil t)
7565 (> (match-end 0) pos))
7566 (goto-char beg)
7567 (goto-char pos)
7568 (error "Not in a dynamic block"))))
7570 (defun org-update-all-dblocks ()
7571 "Update all dynamic blocks in the buffer.
7572 This function can be used in a hook."
7573 (when (org-mode-p)
7574 (org-map-dblocks 'org-update-dblock)))
7577 ;;;; Completion
7579 (defconst org-additional-option-like-keywords
7580 '("BEGIN_HTML" "BEGIN_LaTeX" "END_HTML" "END_LaTeX"
7581 "ORGTBL" "HTML:" "LaTeX:" "BEGIN:" "END:" "TBLFM"
7582 "BEGIN_EXAMPLE" "END_EXAMPLE"))
7584 (defun org-complete (&optional arg)
7585 "Perform completion on word at point.
7586 At the beginning of a headline, this completes TODO keywords as given in
7587 `org-todo-keywords'.
7588 If the current word is preceded by a backslash, completes the TeX symbols
7589 that are supported for HTML support.
7590 If the current word is preceded by \"#+\", completes special words for
7591 setting file options.
7592 In the line after \"#+STARTUP:, complete valid keywords.\"
7593 At all other locations, this simply calls the value of
7594 `org-completion-fallback-command'."
7595 (interactive "P")
7596 (org-without-partial-completion
7597 (catch 'exit
7598 (let* ((end (point))
7599 (beg1 (save-excursion
7600 (skip-chars-backward (org-re "[:alnum:]_@"))
7601 (point)))
7602 (beg (save-excursion
7603 (skip-chars-backward "a-zA-Z0-9_:$")
7604 (point)))
7605 (confirm (lambda (x) (stringp (car x))))
7606 (searchhead (equal (char-before beg) ?*))
7607 (tag (and (equal (char-before beg1) ?:)
7608 (equal (char-after (point-at-bol)) ?*)))
7609 (prop (and (equal (char-before beg1) ?:)
7610 (not (equal (char-after (point-at-bol)) ?*))))
7611 (texp (equal (char-before beg) ?\\))
7612 (link (equal (char-before beg) ?\[))
7613 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
7614 beg)
7615 "#+"))
7616 (startup (string-match "^#\\+STARTUP:.*"
7617 (buffer-substring (point-at-bol) (point))))
7618 (completion-ignore-case opt)
7619 (type nil)
7620 (tbl nil)
7621 (table (cond
7622 (opt
7623 (setq type :opt)
7624 (require 'org-exp)
7625 (append
7626 (mapcar
7627 (lambda (x)
7628 (string-match "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
7629 (cons (match-string 2 x) (match-string 1 x)))
7630 (org-split-string (org-get-current-options) "\n"))
7631 (mapcar 'list org-additional-option-like-keywords)))
7632 (startup
7633 (setq type :startup)
7634 org-startup-options)
7635 (link (append org-link-abbrev-alist-local
7636 org-link-abbrev-alist))
7637 (texp
7638 (setq type :tex)
7639 org-html-entities)
7640 ((string-match "\\`\\*+[ \t]+\\'"
7641 (buffer-substring (point-at-bol) beg))
7642 (setq type :todo)
7643 (mapcar 'list org-todo-keywords-1))
7644 (searchhead
7645 (setq type :searchhead)
7646 (save-excursion
7647 (goto-char (point-min))
7648 (while (re-search-forward org-todo-line-regexp nil t)
7649 (push (list
7650 (org-make-org-heading-search-string
7651 (match-string 3) t))
7652 tbl)))
7653 tbl)
7654 (tag (setq type :tag beg beg1)
7655 (or org-tag-alist (org-get-buffer-tags)))
7656 (prop (setq type :prop beg beg1)
7657 (mapcar 'list (org-buffer-property-keys nil t t)))
7658 (t (progn
7659 (call-interactively org-completion-fallback-command)
7660 (throw 'exit nil)))))
7661 (pattern (buffer-substring-no-properties beg end))
7662 (completion (try-completion pattern table confirm)))
7663 (cond ((eq completion t)
7664 (if (not (assoc (upcase pattern) table))
7665 (message "Already complete")
7666 (if (and (equal type :opt)
7667 (not (member (car (assoc (upcase pattern) table))
7668 org-additional-option-like-keywords)))
7669 (insert (substring (cdr (assoc (upcase pattern) table))
7670 (length pattern)))
7671 (if (memq type '(:tag :prop)) (insert ":")))))
7672 ((null completion)
7673 (message "Can't find completion for \"%s\"" pattern)
7674 (ding))
7675 ((not (string= pattern completion))
7676 (delete-region beg end)
7677 (if (string-match " +$" completion)
7678 (setq completion (replace-match "" t t completion)))
7679 (insert completion)
7680 (if (get-buffer-window "*Completions*")
7681 (delete-window (get-buffer-window "*Completions*")))
7682 (if (assoc completion table)
7683 (if (eq type :todo) (insert " ")
7684 (if (memq type '(:tag :prop)) (insert ":"))))
7685 (if (and (equal type :opt) (assoc completion table))
7686 (message "%s" (substitute-command-keys
7687 "Press \\[org-complete] again to insert example settings"))))
7689 (message "Making completion list...")
7690 (let ((list (sort (all-completions pattern table confirm)
7691 'string<)))
7692 (with-output-to-temp-buffer "*Completions*"
7693 (condition-case nil
7694 ;; Protection needed for XEmacs and emacs 21
7695 (display-completion-list list pattern)
7696 (error (display-completion-list list)))))
7697 (message "Making completion list...%s" "done")))))))
7699 ;;;; TODO, DEADLINE, Comments
7701 (defun org-toggle-comment ()
7702 "Change the COMMENT state of an entry."
7703 (interactive)
7704 (save-excursion
7705 (org-back-to-heading)
7706 (let (case-fold-search)
7707 (if (looking-at (concat outline-regexp
7708 "\\( *\\<" org-comment-string "\\>[ \t]*\\)"))
7709 (replace-match "" t t nil 1)
7710 (if (looking-at outline-regexp)
7711 (progn
7712 (goto-char (match-end 0))
7713 (insert org-comment-string " ")))))))
7715 (defvar org-last-todo-state-is-todo nil
7716 "This is non-nil when the last TODO state change led to a TODO state.
7717 If the last change removed the TODO tag or switched to DONE, then
7718 this is nil.")
7720 (defvar org-setting-tags nil) ; dynamically skiped
7722 (defun org-parse-local-options (string var)
7723 "Parse STRING for startup setting relevant for variable VAR."
7724 (let ((rtn (symbol-value var))
7725 e opts)
7726 (save-match-data
7727 (if (or (not string) (not (string-match "\\S-" string)))
7729 (setq opts (delq nil (mapcar (lambda (x)
7730 (setq e (assoc x org-startup-options))
7731 (if (eq (nth 1 e) var) e nil))
7732 (org-split-string string "[ \t]+"))))
7733 (if (not opts)
7735 (setq rtn nil)
7736 (while (setq e (pop opts))
7737 (if (not (nth 3 e))
7738 (setq rtn (nth 2 e))
7739 (if (not (listp rtn)) (setq rtn nil))
7740 (push (nth 2 e) rtn)))
7741 rtn)))))
7743 (defvar org-blocker-hook nil
7744 "Hook for functions that are allowed to block a state change.
7746 Each function gets as its single argument a property list, see
7747 `org-trigger-hook' for more information about this list.
7749 If any of the functions in this hook returns nil, the state change
7750 is blocked.")
7752 (defvar org-trigger-hook nil
7753 "Hook for functions that are triggered by a state change.
7755 Each function gets as its single argument a property list with at least
7756 the following elements:
7758 (:type type-of-change :position pos-at-entry-start
7759 :from old-state :to new-state)
7761 Depending on the type, more properties may be present.
7763 This mechanism is currently implemented for:
7765 TODO state changes
7766 ------------------
7767 :type todo-state-change
7768 :from previous state (keyword as a string), or nil
7769 :to new state (keyword as a string), or nil")
7772 (defun org-todo (&optional arg)
7773 "Change the TODO state of an item.
7774 The state of an item is given by a keyword at the start of the heading,
7775 like
7776 *** TODO Write paper
7777 *** DONE Call mom
7779 The different keywords are specified in the variable `org-todo-keywords'.
7780 By default the available states are \"TODO\" and \"DONE\".
7781 So for this example: when the item starts with TODO, it is changed to DONE.
7782 When it starts with DONE, the DONE is removed. And when neither TODO nor
7783 DONE are present, add TODO at the beginning of the heading.
7785 With C-u prefix arg, use completion to determine the new state.
7786 With numeric prefix arg, switch to that state.
7788 For calling through lisp, arg is also interpreted in the following way:
7789 'none -> empty state
7790 \"\"(empty string) -> switch to empty state
7791 'done -> switch to DONE
7792 'nextset -> switch to the next set of keywords
7793 'previousset -> switch to the previous set of keywords
7794 \"WAITING\" -> switch to the specified keyword, but only if it
7795 really is a member of `org-todo-keywords'."
7796 (interactive "P")
7797 (save-excursion
7798 (catch 'exit
7799 (org-back-to-heading)
7800 (if (looking-at outline-regexp) (goto-char (1- (match-end 0))))
7801 (or (looking-at (concat " +" org-todo-regexp " *"))
7802 (looking-at " *"))
7803 (let* ((match-data (match-data))
7804 (startpos (point-at-bol))
7805 (logging (save-match-data (org-entry-get nil "LOGGING" t)))
7806 (org-log-done org-log-done)
7807 (org-log-repeat org-log-repeat)
7808 (org-todo-log-states org-todo-log-states)
7809 (this (match-string 1))
7810 (hl-pos (match-beginning 0))
7811 (head (org-get-todo-sequence-head this))
7812 (ass (assoc head org-todo-kwd-alist))
7813 (interpret (nth 1 ass))
7814 (done-word (nth 3 ass))
7815 (final-done-word (nth 4 ass))
7816 (last-state (or this ""))
7817 (completion-ignore-case t)
7818 (member (member this org-todo-keywords-1))
7819 (tail (cdr member))
7820 (state (cond
7821 ((and org-todo-key-trigger
7822 (or (and (equal arg '(4)) (eq org-use-fast-todo-selection 'prefix))
7823 (and (not arg) org-use-fast-todo-selection
7824 (not (eq org-use-fast-todo-selection 'prefix)))))
7825 ;; Use fast selection
7826 (org-fast-todo-selection))
7827 ((and (equal arg '(4))
7828 (or (not org-use-fast-todo-selection)
7829 (not org-todo-key-trigger)))
7830 ;; Read a state with completion
7831 (completing-read "State: " (mapcar (lambda(x) (list x))
7832 org-todo-keywords-1)
7833 nil t))
7834 ((eq arg 'right)
7835 (if this
7836 (if tail (car tail) nil)
7837 (car org-todo-keywords-1)))
7838 ((eq arg 'left)
7839 (if (equal member org-todo-keywords-1)
7841 (if this
7842 (nth (- (length org-todo-keywords-1) (length tail) 2)
7843 org-todo-keywords-1)
7844 (org-last org-todo-keywords-1))))
7845 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
7846 (setq arg nil))) ; hack to fall back to cycling
7847 (arg
7848 ;; user or caller requests a specific state
7849 (cond
7850 ((equal arg "") nil)
7851 ((eq arg 'none) nil)
7852 ((eq arg 'done) (or done-word (car org-done-keywords)))
7853 ((eq arg 'nextset)
7854 (or (car (cdr (member head org-todo-heads)))
7855 (car org-todo-heads)))
7856 ((eq arg 'previousset)
7857 (let ((org-todo-heads (reverse org-todo-heads)))
7858 (or (car (cdr (member head org-todo-heads)))
7859 (car org-todo-heads))))
7860 ((car (member arg org-todo-keywords-1)))
7861 ((nth (1- (prefix-numeric-value arg))
7862 org-todo-keywords-1))))
7863 ((null member) (or head (car org-todo-keywords-1)))
7864 ((equal this final-done-word) nil) ;; -> make empty
7865 ((null tail) nil) ;; -> first entry
7866 ((eq interpret 'sequence)
7867 (car tail))
7868 ((memq interpret '(type priority))
7869 (if (eq this-command last-command)
7870 (car tail)
7871 (if (> (length tail) 0)
7872 (or done-word (car org-done-keywords))
7873 nil)))
7874 (t nil)))
7875 (next (if state (concat " " state " ") " "))
7876 (change-plist (list :type 'todo-state-change :from this :to state
7877 :position startpos))
7878 dolog now-done-p)
7879 (when org-blocker-hook
7880 (unless (save-excursion
7881 (save-match-data
7882 (run-hook-with-args-until-failure
7883 'org-blocker-hook change-plist)))
7884 (if (interactive-p)
7885 (error "TODO state change from %s to %s blocked" this state)
7886 ;; fail silently
7887 (message "TODO state change from %s to %s blocked" this state)
7888 (throw 'exit nil))))
7889 (store-match-data match-data)
7890 (replace-match next t t)
7891 (unless (pos-visible-in-window-p hl-pos)
7892 (message "TODO state changed to %s" (org-trim next)))
7893 (unless head
7894 (setq head (org-get-todo-sequence-head state)
7895 ass (assoc head org-todo-kwd-alist)
7896 interpret (nth 1 ass)
7897 done-word (nth 3 ass)
7898 final-done-word (nth 4 ass)))
7899 (when (memq arg '(nextset previousset))
7900 (message "Keyword-Set %d/%d: %s"
7901 (- (length org-todo-sets) -1
7902 (length (memq (assoc state org-todo-sets) org-todo-sets)))
7903 (length org-todo-sets)
7904 (mapconcat 'identity (assoc state org-todo-sets) " ")))
7905 (setq org-last-todo-state-is-todo
7906 (not (member state org-done-keywords)))
7907 (setq now-done-p (and (member state org-done-keywords)
7908 (not (member this org-done-keywords))))
7909 (and logging (org-local-logging logging))
7910 (when (and (or org-todo-log-states org-log-done)
7911 (not (memq arg '(nextset previousset))))
7912 ;; we need to look at recording a time and note
7913 (setq dolog (or (nth 1 (assoc state org-todo-log-states))
7914 (nth 2 (assoc this org-todo-log-states))))
7915 (when (and state
7916 (member state org-not-done-keywords)
7917 (not (member this org-not-done-keywords)))
7918 ;; This is now a todo state and was not one before
7919 ;; If there was a CLOSED time stamp, get rid of it.
7920 (org-add-planning-info nil nil 'closed))
7921 (when (and now-done-p org-log-done)
7922 ;; It is now done, and it was not done before
7923 (org-add-planning-info 'closed (org-current-time))
7924 (if (and (not dolog) (eq 'note org-log-done))
7925 (org-add-log-setup 'done state 'findpos 'note)))
7926 (when (and state dolog)
7927 ;; This is a non-nil state, and we need to log it
7928 (org-add-log-setup 'state state 'findpos dolog)))
7929 ;; Fixup tag positioning
7930 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
7931 (run-hooks 'org-after-todo-state-change-hook)
7932 (if (and arg (not (member state org-done-keywords)))
7933 (setq head (org-get-todo-sequence-head state)))
7934 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
7935 ;; Do we need to trigger a repeat?
7936 (when now-done-p (org-auto-repeat-maybe state))
7937 ;; Fixup cursor location if close to the keyword
7938 (if (and (outline-on-heading-p)
7939 (not (bolp))
7940 (save-excursion (beginning-of-line 1)
7941 (looking-at org-todo-line-regexp))
7942 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
7943 (progn
7944 (goto-char (or (match-end 2) (match-end 1)))
7945 (just-one-space)))
7946 (when org-trigger-hook
7947 (save-excursion
7948 (run-hook-with-args 'org-trigger-hook change-plist)))))))
7950 (defun org-local-logging (value)
7951 "Get logging settings from a property VALUE."
7952 (let* (words w a)
7953 ;; directly set the variables, they are already local.
7954 (setq org-log-done nil
7955 org-log-repeat nil
7956 org-todo-log-states nil)
7957 (setq words (org-split-string value))
7958 (while (setq w (pop words))
7959 (cond
7960 ((setq a (assoc w org-startup-options))
7961 (and (member (nth 1 a) '(org-log-done org-log-repeat))
7962 (set (nth 1 a) (nth 2 a))))
7963 ((setq a (org-extract-log-state-settings w))
7964 (and (member (car a) org-todo-keywords-1)
7965 (push a org-todo-log-states)))))))
7967 (defun org-get-todo-sequence-head (kwd)
7968 "Return the head of the TODO sequence to which KWD belongs.
7969 If KWD is not set, check if there is a text property remembering the
7970 right sequence."
7971 (let (p)
7972 (cond
7973 ((not kwd)
7974 (or (get-text-property (point-at-bol) 'org-todo-head)
7975 (progn
7976 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
7977 nil (point-at-eol)))
7978 (get-text-property p 'org-todo-head))))
7979 ((not (member kwd org-todo-keywords-1))
7980 (car org-todo-keywords-1))
7981 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
7983 (defun org-fast-todo-selection ()
7984 "Fast TODO keyword selection with single keys.
7985 Returns the new TODO keyword, or nil if no state change should occur."
7986 (let* ((fulltable org-todo-key-alist)
7987 (done-keywords org-done-keywords) ;; needed for the faces.
7988 (maxlen (apply 'max (mapcar
7989 (lambda (x)
7990 (if (stringp (car x)) (string-width (car x)) 0))
7991 fulltable)))
7992 (expert nil)
7993 (fwidth (+ maxlen 3 1 3))
7994 (ncol (/ (- (window-width) 4) fwidth))
7995 tg cnt e c tbl
7996 groups ingroup)
7997 (save-window-excursion
7998 (if expert
7999 (set-buffer (get-buffer-create " *Org todo*"))
8000 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
8001 (erase-buffer)
8002 (org-set-local 'org-done-keywords done-keywords)
8003 (setq tbl fulltable cnt 0)
8004 (while (setq e (pop tbl))
8005 (cond
8006 ((equal e '(:startgroup))
8007 (push '() groups) (setq ingroup t)
8008 (when (not (= cnt 0))
8009 (setq cnt 0)
8010 (insert "\n"))
8011 (insert "{ "))
8012 ((equal e '(:endgroup))
8013 (setq ingroup nil cnt 0)
8014 (insert "}\n"))
8016 (setq tg (car e) c (cdr e))
8017 (if ingroup (push tg (car groups)))
8018 (setq tg (org-add-props tg nil 'face
8019 (org-get-todo-face tg)))
8020 (if (and (= cnt 0) (not ingroup)) (insert " "))
8021 (insert "[" c "] " tg (make-string
8022 (- fwidth 4 (length tg)) ?\ ))
8023 (when (= (setq cnt (1+ cnt)) ncol)
8024 (insert "\n")
8025 (if ingroup (insert " "))
8026 (setq cnt 0)))))
8027 (insert "\n")
8028 (goto-char (point-min))
8029 (if (and (not expert) (fboundp 'fit-window-to-buffer))
8030 (fit-window-to-buffer))
8031 (message "[a-z..]:Set [SPC]:clear")
8032 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
8033 (cond
8034 ((or (= c ?\C-g)
8035 (and (= c ?q) (not (rassoc c fulltable))))
8036 (setq quit-flag t))
8037 ((= c ?\ ) nil)
8038 ((setq e (rassoc c fulltable) tg (car e))
8040 (t (setq quit-flag t))))))
8042 (defun org-entry-is-todo-p ()
8043 (member (org-get-todo-state) org-not-done-keywords))
8045 (defun org-entry-is-done-p ()
8046 (member (org-get-todo-state) org-done-keywords))
8048 (defun org-get-todo-state ()
8049 (save-excursion
8050 (org-back-to-heading t)
8051 (and (looking-at org-todo-line-regexp)
8052 (match-end 2)
8053 (match-string 2))))
8055 (defun org-at-date-range-p (&optional inactive-ok)
8056 "Is the cursor inside a date range?"
8057 (interactive)
8058 (save-excursion
8059 (catch 'exit
8060 (let ((pos (point)))
8061 (skip-chars-backward "^[<\r\n")
8062 (skip-chars-backward "<[")
8063 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
8064 (>= (match-end 0) pos)
8065 (throw 'exit t))
8066 (skip-chars-backward "^<[\r\n")
8067 (skip-chars-backward "<[")
8068 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
8069 (>= (match-end 0) pos)
8070 (throw 'exit t)))
8071 nil)))
8073 (defun org-get-repeat ()
8074 "Check if tere is a deadline/schedule with repeater in this entry."
8075 (save-match-data
8076 (save-excursion
8077 (org-back-to-heading t)
8078 (if (re-search-forward
8079 org-repeat-re (save-excursion (outline-next-heading) (point)) t)
8080 (match-string 1)))))
8082 (defvar org-last-changed-timestamp)
8083 (defvar org-log-post-message)
8084 (defvar org-log-note-purpose)
8085 (defvar org-log-note-how)
8086 (defun org-auto-repeat-maybe (done-word)
8087 "Check if the current headline contains a repeated deadline/schedule.
8088 If yes, set TODO state back to what it was and change the base date
8089 of repeating deadline/scheduled time stamps to new date.
8090 This function is run automatically after each state change to a DONE state."
8091 ;; last-state is dynamically scoped into this function
8092 (let* ((repeat (org-get-repeat))
8093 (aa (assoc last-state org-todo-kwd-alist))
8094 (interpret (nth 1 aa))
8095 (head (nth 2 aa))
8096 (whata '(("d" . day) ("m" . month) ("y" . year)))
8097 (msg "Entry repeats: ")
8098 (org-log-done nil)
8099 (org-todo-log-states nil)
8100 (nshiftmax 10) (nshift 0)
8101 re type n what ts mb0 time)
8102 (when repeat
8103 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
8104 (org-todo (if (eq interpret 'type) last-state head))
8105 (when org-log-repeat
8106 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
8107 (memq 'org-add-log-note post-command-hook))
8108 ;; OK, we are already setup for some record
8109 (if (eq org-log-repeat 'note)
8110 ;; make sure we take a note, not only a time stamp
8111 (setq org-log-note-how 'note))
8112 ;; Set up for taking a record
8113 (org-add-log-setup 'state (or done-word (car org-done-keywords))
8114 'findpos org-log-repeat)))
8115 (org-back-to-heading t)
8116 (org-add-planning-info nil nil 'closed)
8117 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
8118 org-deadline-time-regexp "\\)\\|\\("
8119 org-ts-regexp "\\)"))
8120 (while (re-search-forward
8121 re (save-excursion (outline-next-heading) (point)) t)
8122 (setq type (if (match-end 1) org-scheduled-string
8123 (if (match-end 3) org-deadline-string "Plain:"))
8124 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0)))
8125 mb0 (match-beginning 0))
8126 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts)
8127 (setq n (string-to-number (match-string 2 ts))
8128 what (match-string 3 ts))
8129 (if (equal what "w") (setq n (* n 7) what "d"))
8130 ;; Preparation, see if we need to modify the start date for the change
8131 (when (match-end 1)
8132 (setq time (save-match-data (org-time-string-to-time ts)))
8133 (cond
8134 ((equal (match-string 1 ts) ".")
8135 ;; Shift starting date to today
8136 (org-timestamp-change
8137 (- (time-to-days (current-time)) (time-to-days time))
8138 'day))
8139 ((equal (match-string 1 ts) "+")
8140 (while (or (= nshift 0)
8141 (<= (time-to-days time) (time-to-days (current-time))))
8142 (when (= (incf nshift) nshiftmax)
8143 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
8144 (error "Abort")))
8145 (org-timestamp-change n (cdr (assoc what whata)))
8146 (org-at-timestamp-p t)
8147 (setq ts (match-string 1))
8148 (setq time (save-match-data (org-time-string-to-time ts))))
8149 (org-timestamp-change (- n) (cdr (assoc what whata)))
8150 ;; rematch, so that we have everything in place for the real shift
8151 (org-at-timestamp-p t)
8152 (setq ts (match-string 1))
8153 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts))))
8154 (org-timestamp-change n (cdr (assoc what whata)))
8155 (setq msg (concat msg type org-last-changed-timestamp " "))))
8156 (setq org-log-post-message msg)
8157 (message "%s" msg))))
8159 (defun org-show-todo-tree (arg)
8160 "Make a compact tree which shows all headlines marked with TODO.
8161 The tree will show the lines where the regexp matches, and all higher
8162 headlines above the match.
8163 With a \\[universal-argument] prefix, also show the DONE entries.
8164 With a numeric prefix N, construct a sparse tree for the Nth element
8165 of `org-todo-keywords-1'."
8166 (interactive "P")
8167 (let ((case-fold-search nil)
8168 (kwd-re
8169 (cond ((null arg) org-not-done-regexp)
8170 ((equal arg '(4))
8171 (let ((kwd (completing-read "Keyword (or KWD1|KWD2|...): "
8172 (mapcar 'list org-todo-keywords-1))))
8173 (concat "\\("
8174 (mapconcat 'identity (org-split-string kwd "|") "\\|")
8175 "\\)\\>")))
8176 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
8177 (regexp-quote (nth (1- (prefix-numeric-value arg))
8178 org-todo-keywords-1)))
8179 (t (error "Invalid prefix argument: %s" arg)))))
8180 (message "%d TODO entries found"
8181 (org-occur (concat "^" outline-regexp " *" kwd-re )))))
8183 (defun org-deadline (&optional remove)
8184 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
8185 With argument REMOVE, remove any deadline from the item."
8186 (interactive "P")
8187 (if remove
8188 (progn
8189 (org-remove-timestamp-with-keyword org-deadline-string)
8190 (message "Item no longer has a deadline."))
8191 (org-add-planning-info 'deadline nil 'closed)))
8193 (defun org-schedule (&optional remove)
8194 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
8195 With argument REMOVE, remove any scheduling date from the item."
8196 (interactive "P")
8197 (if remove
8198 (progn
8199 (org-remove-timestamp-with-keyword org-scheduled-string)
8200 (message "Item is no longer scheduled."))
8201 (org-add-planning-info 'scheduled nil 'closed)))
8203 (defun org-remove-timestamp-with-keyword (keyword)
8204 "Remove all time stamps with KEYWORD in the current entry."
8205 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
8206 beg)
8207 (save-excursion
8208 (org-back-to-heading t)
8209 (setq beg (point))
8210 (org-end-of-subtree t t)
8211 (while (re-search-backward re beg t)
8212 (replace-match "")
8213 (unless (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
8214 (delete-region (point-at-bol) (min (1+ (point)) (point-max))))))))
8216 (defun org-add-planning-info (what &optional time &rest remove)
8217 "Insert new timestamp with keyword in the line directly after the headline.
8218 WHAT indicates what kind of time stamp to add. TIME indicated the time to use.
8219 If non is given, the user is prompted for a date.
8220 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
8221 be removed."
8222 (interactive)
8223 (let (org-time-was-given org-end-time-was-given ts
8224 end default-time default-input)
8226 (when (and (not time) (memq what '(scheduled deadline)))
8227 ;; Try to get a default date/time from existing timestamp
8228 (save-excursion
8229 (org-back-to-heading t)
8230 (setq end (save-excursion (outline-next-heading) (point)))
8231 (when (re-search-forward (if (eq what 'scheduled)
8232 org-scheduled-time-regexp
8233 org-deadline-time-regexp)
8234 end t)
8235 (setq ts (match-string 1)
8236 default-time
8237 (apply 'encode-time (org-parse-time-string ts))
8238 default-input (and ts (org-get-compact-tod ts))))))
8239 (when what
8240 ;; If necessary, get the time from the user
8241 (setq time (or time (org-read-date nil 'to-time nil nil
8242 default-time default-input))))
8244 (when (and org-insert-labeled-timestamps-at-point
8245 (member what '(scheduled deadline)))
8246 (insert
8247 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
8248 (org-insert-time-stamp time org-time-was-given
8249 nil nil nil (list org-end-time-was-given))
8250 (setq what nil))
8251 (save-excursion
8252 (save-restriction
8253 (let (col list elt ts buffer-invisibility-spec)
8254 (org-back-to-heading t)
8255 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
8256 (goto-char (match-end 1))
8257 (setq col (current-column))
8258 (goto-char (match-end 0))
8259 (if (eobp) (insert "\n") (forward-char 1))
8260 (if (and (not (looking-at outline-regexp))
8261 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
8262 "[^\r\n]*"))
8263 (not (equal (match-string 1) org-clock-string)))
8264 (narrow-to-region (match-beginning 0) (match-end 0))
8265 (insert-before-markers "\n")
8266 (backward-char 1)
8267 (narrow-to-region (point) (point))
8268 (org-indent-to-column col))
8269 ;; Check if we have to remove something.
8270 (setq list (cons what remove))
8271 (while list
8272 (setq elt (pop list))
8273 (goto-char (point-min))
8274 (when (or (and (eq elt 'scheduled)
8275 (re-search-forward org-scheduled-time-regexp nil t))
8276 (and (eq elt 'deadline)
8277 (re-search-forward org-deadline-time-regexp nil t))
8278 (and (eq elt 'closed)
8279 (re-search-forward org-closed-time-regexp nil t)))
8280 (replace-match "")
8281 (if (looking-at "--+<[^>]+>") (replace-match ""))
8282 (if (looking-at " +") (replace-match ""))))
8283 (goto-char (point-max))
8284 (when what
8285 (insert
8286 (if (not (equal (char-before) ?\ )) " " "")
8287 (cond ((eq what 'scheduled) org-scheduled-string)
8288 ((eq what 'deadline) org-deadline-string)
8289 ((eq what 'closed) org-closed-string))
8290 " ")
8291 (setq ts (org-insert-time-stamp
8292 time
8293 (or org-time-was-given
8294 (and (eq what 'closed) org-log-done-with-time))
8295 (eq what 'closed)
8296 nil nil (list org-end-time-was-given)))
8297 (end-of-line 1))
8298 (goto-char (point-min))
8299 (widen)
8300 (if (and (looking-at "[ \t]+\n")
8301 (equal (char-before) ?\n))
8302 (backward-delete-char 1))
8303 ts)))))
8305 (defvar org-log-note-marker (make-marker))
8306 (defvar org-log-note-purpose nil)
8307 (defvar org-log-note-state nil)
8308 (defvar org-log-note-how nil)
8309 (defvar org-log-note-window-configuration nil)
8310 (defvar org-log-note-return-to (make-marker))
8311 (defvar org-log-post-message nil
8312 "Message to be displayed after a log note has been stored.
8313 The auto-repeater uses this.")
8315 (defun org-add-note ()
8316 "Add a note to the current entry.
8317 This is done in the same way as adding a state change note."
8318 (interactive)
8319 (org-add-log-setup 'note nil t nil))
8321 (defun org-add-log-setup (&optional purpose state findpos how)
8322 "Set up the post command hook to take a note.
8323 If this is about to TODO state change, the new state is expected in STATE.
8324 When FINDPOS is non-nil, find the correct position for the note in
8325 the current entry. If not, assume that it can be inserted at point."
8326 (save-excursion
8327 (when findpos
8328 (org-back-to-heading t)
8329 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"
8330 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
8331 "[^\r\n]*\\)?"))
8332 (goto-char (match-end 0))
8333 (unless org-log-states-order-reversed
8334 (and (= (char-after) ?\n) (forward-char 1))
8335 (org-skip-over-state-notes)
8336 (skip-chars-backward " \t\n\r")))
8337 (move-marker org-log-note-marker (point))
8338 (setq org-log-note-purpose purpose
8339 org-log-note-state state
8340 org-log-note-how how)
8341 (add-hook 'post-command-hook 'org-add-log-note 'append)))
8343 (defun org-skip-over-state-notes ()
8344 "Skip past the list of State notes in an entry."
8345 (if (looking-at "\n[ \t]*- State") (forward-char 1))
8346 (while (looking-at "[ \t]*- State")
8347 (condition-case nil
8348 (org-next-item)
8349 (error (org-end-of-item)))))
8351 (defun org-add-log-note (&optional purpose)
8352 "Pop up a window for taking a note, and add this note later at point."
8353 (remove-hook 'post-command-hook 'org-add-log-note)
8354 (setq org-log-note-window-configuration (current-window-configuration))
8355 (delete-other-windows)
8356 (move-marker org-log-note-return-to (point))
8357 (switch-to-buffer (marker-buffer org-log-note-marker))
8358 (goto-char org-log-note-marker)
8359 (org-switch-to-buffer-other-window "*Org Note*")
8360 (erase-buffer)
8361 (if (memq org-log-note-how '(time state))
8362 (org-store-log-note)
8363 (let ((org-inhibit-startup t)) (org-mode))
8364 (insert (format "# Insert note for %s.
8365 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
8366 (cond
8367 ((eq org-log-note-purpose 'clock-out) "stopped clock")
8368 ((eq org-log-note-purpose 'done) "closed todo item")
8369 ((eq org-log-note-purpose 'state)
8370 (format "state change to \"%s\"" org-log-note-state))
8371 ((eq org-log-note-purpose 'note)
8372 "this entry")
8373 (t (error "This should not happen")))))
8374 (org-set-local 'org-finish-function 'org-store-log-note)))
8376 (defvar org-note-abort nil) ; dynamically scoped
8377 (defun org-store-log-note ()
8378 "Finish taking a log note, and insert it to where it belongs."
8379 (let ((txt (buffer-string))
8380 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
8381 lines ind)
8382 (kill-buffer (current-buffer))
8383 (while (string-match "\\`#.*\n[ \t\n]*" txt)
8384 (setq txt (replace-match "" t t txt)))
8385 (if (string-match "\\s-+\\'" txt)
8386 (setq txt (replace-match "" t t txt)))
8387 (setq lines (org-split-string txt "\n"))
8388 (when (and note (string-match "\\S-" note))
8389 (setq note
8390 (org-replace-escapes
8391 note
8392 (list (cons "%u" (user-login-name))
8393 (cons "%U" user-full-name)
8394 (cons "%t" (format-time-string
8395 (org-time-stamp-format 'long 'inactive)
8396 (current-time)))
8397 (cons "%s" (if org-log-note-state
8398 (concat "\"" org-log-note-state "\"")
8399 "")))))
8400 (if lines (setq note (concat note " \\\\")))
8401 (push note lines))
8402 (when (or current-prefix-arg org-note-abort) (setq lines nil))
8403 (when lines
8404 (save-excursion
8405 (set-buffer (marker-buffer org-log-note-marker))
8406 (save-excursion
8407 (goto-char org-log-note-marker)
8408 (move-marker org-log-note-marker nil)
8409 (end-of-line 1)
8410 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
8411 (indent-relative nil)
8412 (insert "- " (pop lines))
8413 (org-indent-line-function)
8414 (beginning-of-line 1)
8415 (looking-at "[ \t]*")
8416 (setq ind (concat (match-string 0) " "))
8417 (end-of-line 1)
8418 (while lines (insert "\n" ind (pop lines)))))))
8419 (set-window-configuration org-log-note-window-configuration)
8420 (with-current-buffer (marker-buffer org-log-note-return-to)
8421 (goto-char org-log-note-return-to))
8422 (move-marker org-log-note-return-to nil)
8423 (and org-log-post-message (message "%s" org-log-post-message)))
8425 (defun org-sparse-tree (&optional arg)
8426 "Create a sparse tree, prompt for the details.
8427 This command can create sparse trees. You first need to select the type
8428 of match used to create the tree:
8430 t Show entries with a specific TODO keyword.
8431 T Show entries selected by a tags match.
8432 p Enter a property name and its value (both with completion on existing
8433 names/values) and show entries with that property.
8434 r Show entries matching a regular expression
8435 d Show deadlines due within `org-deadline-warning-days'."
8436 (interactive "P")
8437 (let (ans kwd value)
8438 (message "Sparse tree: [/]regexp [t]odo-kwd [T]ag [p]roperty [d]eadlines [b]efore-date")
8439 (setq ans (read-char-exclusive))
8440 (cond
8441 ((equal ans ?d)
8442 (call-interactively 'org-check-deadlines))
8443 ((equal ans ?b)
8444 (call-interactively 'org-check-before-date))
8445 ((equal ans ?t)
8446 (org-show-todo-tree '(4)))
8447 ((equal ans ?T)
8448 (call-interactively 'org-tags-sparse-tree))
8449 ((member ans '(?p ?P))
8450 (setq kwd (completing-read "Property: "
8451 (mapcar 'list (org-buffer-property-keys))))
8452 (setq value (completing-read "Value: "
8453 (mapcar 'list (org-property-values kwd))))
8454 (unless (string-match "\\`{.*}\\'" value)
8455 (setq value (concat "\"" value "\"")))
8456 (org-tags-sparse-tree arg (concat kwd "=" value)))
8457 ((member ans '(?r ?R ?/))
8458 (call-interactively 'org-occur))
8459 (t (error "No such sparse tree command \"%c\"" ans)))))
8461 (defvar org-occur-highlights nil
8462 "List of overlays used for occur matches.")
8463 (make-variable-buffer-local 'org-occur-highlights)
8464 (defvar org-occur-parameters nil
8465 "Parameters of the active org-occur calls.
8466 This is a list, each call to org-occur pushes as cons cell,
8467 containing the regular expression and the callback, onto the list.
8468 The list can contain several entries if `org-occur' has been called
8469 several time with the KEEP-PREVIOUS argument. Otherwise, this list
8470 will only contain one set of parameters. When the highlights are
8471 removed (for example with `C-c C-c', or with the next edit (depending
8472 on `org-remove-highlights-with-change'), this variable is emptied
8473 as well.")
8474 (make-variable-buffer-local 'org-occur-parameters)
8476 (defun org-occur (regexp &optional keep-previous callback)
8477 "Make a compact tree which shows all matches of REGEXP.
8478 The tree will show the lines where the regexp matches, and all higher
8479 headlines above the match. It will also show the heading after the match,
8480 to make sure editing the matching entry is easy.
8481 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
8482 call to `org-occur' will be kept, to allow stacking of calls to this
8483 command.
8484 If CALLBACK is non-nil, it is a function which is called to confirm
8485 that the match should indeed be shown."
8486 (interactive "sRegexp: \nP")
8487 (unless keep-previous
8488 (org-remove-occur-highlights nil nil t))
8489 (push (cons regexp callback) org-occur-parameters)
8490 (let ((cnt 0))
8491 (save-excursion
8492 (goto-char (point-min))
8493 (if (or (not keep-previous) ; do not want to keep
8494 (not org-occur-highlights)) ; no previous matches
8495 ;; hide everything
8496 (org-overview))
8497 (while (re-search-forward regexp nil t)
8498 (when (or (not callback)
8499 (save-match-data (funcall callback)))
8500 (setq cnt (1+ cnt))
8501 (when org-highlight-sparse-tree-matches
8502 (org-highlight-new-match (match-beginning 0) (match-end 0)))
8503 (org-show-context 'occur-tree))))
8504 (when org-remove-highlights-with-change
8505 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
8506 nil 'local))
8507 (unless org-sparse-tree-open-archived-trees
8508 (org-hide-archived-subtrees (point-min) (point-max)))
8509 (run-hooks 'org-occur-hook)
8510 (if (interactive-p)
8511 (message "%d match(es) for regexp %s" cnt regexp))
8512 cnt))
8514 (defun org-show-context (&optional key)
8515 "Make sure point and context and visible.
8516 How much context is shown depends upon the variables
8517 `org-show-hierarchy-above', `org-show-following-heading'. and
8518 `org-show-siblings'."
8519 (let ((heading-p (org-on-heading-p t))
8520 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
8521 (following-p (org-get-alist-option org-show-following-heading key))
8522 (entry-p (org-get-alist-option org-show-entry-below key))
8523 (siblings-p (org-get-alist-option org-show-siblings key)))
8524 (catch 'exit
8525 ;; Show heading or entry text
8526 (if (and heading-p (not entry-p))
8527 (org-flag-heading nil) ; only show the heading
8528 (and (or entry-p (org-invisible-p) (org-invisible-p2))
8529 (org-show-hidden-entry))) ; show entire entry
8530 (when following-p
8531 ;; Show next sibling, or heading below text
8532 (save-excursion
8533 (and (if heading-p (org-goto-sibling) (outline-next-heading))
8534 (org-flag-heading nil))))
8535 (when siblings-p (org-show-siblings))
8536 (when hierarchy-p
8537 ;; show all higher headings, possibly with siblings
8538 (save-excursion
8539 (while (and (condition-case nil
8540 (progn (org-up-heading-all 1) t)
8541 (error nil))
8542 (not (bobp)))
8543 (org-flag-heading nil)
8544 (when siblings-p (org-show-siblings))))))))
8546 (defun org-reveal (&optional siblings)
8547 "Show current entry, hierarchy above it, and the following headline.
8548 This can be used to show a consistent set of context around locations
8549 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
8550 not t for the search context.
8552 With optional argument SIBLINGS, on each level of the hierarchy all
8553 siblings are shown. This repairs the tree structure to what it would
8554 look like when opened with hierarchical calls to `org-cycle'."
8555 (interactive "P")
8556 (let ((org-show-hierarchy-above t)
8557 (org-show-following-heading t)
8558 (org-show-siblings (if siblings t org-show-siblings)))
8559 (org-show-context nil)))
8561 (defun org-highlight-new-match (beg end)
8562 "Highlight from BEG to END and mark the highlight is an occur headline."
8563 (let ((ov (org-make-overlay beg end)))
8564 (org-overlay-put ov 'face 'secondary-selection)
8565 (push ov org-occur-highlights)))
8567 (defun org-remove-occur-highlights (&optional beg end noremove)
8568 "Remove the occur highlights from the buffer.
8569 BEG and END are ignored. If NOREMOVE is nil, remove this function
8570 from the `before-change-functions' in the current buffer."
8571 (interactive)
8572 (unless org-inhibit-highlight-removal
8573 (mapc 'org-delete-overlay org-occur-highlights)
8574 (setq org-occur-highlights nil)
8575 (setq org-occur-parameters nil)
8576 (unless noremove
8577 (remove-hook 'before-change-functions
8578 'org-remove-occur-highlights 'local))))
8580 ;;;; Priorities
8582 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
8583 "Regular expression matching the priority indicator.")
8585 (defvar org-remove-priority-next-time nil)
8587 (defun org-priority-up ()
8588 "Increase the priority of the current item."
8589 (interactive)
8590 (org-priority 'up))
8592 (defun org-priority-down ()
8593 "Decrease the priority of the current item."
8594 (interactive)
8595 (org-priority 'down))
8597 (defun org-priority (&optional action)
8598 "Change the priority of an item by ARG.
8599 ACTION can be `set', `up', `down', or a character."
8600 (interactive)
8601 (setq action (or action 'set))
8602 (let (current new news have remove)
8603 (save-excursion
8604 (org-back-to-heading)
8605 (if (looking-at org-priority-regexp)
8606 (setq current (string-to-char (match-string 2))
8607 have t)
8608 (setq current org-default-priority))
8609 (cond
8610 ((or (eq action 'set)
8611 (if (featurep 'xemacs) (characterp action) (integerp action)))
8612 (if (not (eq action 'set))
8613 (setq new action)
8614 (message "Priority %c-%c, SPC to remove: "
8615 org-highest-priority org-lowest-priority)
8616 (setq new (read-char-exclusive)))
8617 (if (and (= (upcase org-highest-priority) org-highest-priority)
8618 (= (upcase org-lowest-priority) org-lowest-priority))
8619 (setq new (upcase new)))
8620 (cond ((equal new ?\ ) (setq remove t))
8621 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
8622 (error "Priority must be between `%c' and `%c'"
8623 org-highest-priority org-lowest-priority))))
8624 ((eq action 'up)
8625 (if (and (not have) (eq last-command this-command))
8626 (setq new org-lowest-priority)
8627 (setq new (if (and org-priority-start-cycle-with-default (not have))
8628 org-default-priority (1- current)))))
8629 ((eq action 'down)
8630 (if (and (not have) (eq last-command this-command))
8631 (setq new org-highest-priority)
8632 (setq new (if (and org-priority-start-cycle-with-default (not have))
8633 org-default-priority (1+ current)))))
8634 (t (error "Invalid action")))
8635 (if (or (< (upcase new) org-highest-priority)
8636 (> (upcase new) org-lowest-priority))
8637 (setq remove t))
8638 (setq news (format "%c" new))
8639 (if have
8640 (if remove
8641 (replace-match "" t t nil 1)
8642 (replace-match news t t nil 2))
8643 (if remove
8644 (error "No priority cookie found in line")
8645 (looking-at org-todo-line-regexp)
8646 (if (match-end 2)
8647 (progn
8648 (goto-char (match-end 2))
8649 (insert " [#" news "]"))
8650 (goto-char (match-beginning 3))
8651 (insert "[#" news "] ")))))
8652 (org-preserve-lc (org-set-tags nil 'align))
8653 (if remove
8654 (message "Priority removed")
8655 (message "Priority of current item set to %s" news))))
8658 (defun org-get-priority (s)
8659 "Find priority cookie and return priority."
8660 (save-match-data
8661 (if (not (string-match org-priority-regexp s))
8662 (* 1000 (- org-lowest-priority org-default-priority))
8663 (* 1000 (- org-lowest-priority
8664 (string-to-char (match-string 2 s)))))))
8666 ;;;; Tags
8668 (defun org-scan-tags (action matcher &optional todo-only)
8669 "Scan headline tags with inheritance and produce output ACTION.
8670 ACTION can be `sparse-tree' or `agenda'. MATCHER is a Lisp form to be
8671 evaluated, testing if a given set of tags qualifies a headline for
8672 inclusion. When TODO-ONLY is non-nil, only lines with a TODO keyword
8673 are included in the output."
8674 (let* ((re (concat "[\n\r]" outline-regexp " *\\(\\<\\("
8675 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
8676 (org-re
8677 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*$")))
8678 (props (list 'face nil
8679 'done-face 'org-done
8680 'undone-face nil
8681 'mouse-face 'highlight
8682 'org-not-done-regexp org-not-done-regexp
8683 'org-todo-regexp org-todo-regexp
8684 'keymap org-agenda-keymap
8685 'help-echo
8686 (format "mouse-2 or RET jump to org file %s"
8687 (abbreviate-file-name
8688 (or (buffer-file-name (buffer-base-buffer))
8689 (buffer-name (buffer-base-buffer)))))))
8690 (case-fold-search nil)
8691 lspos
8692 tags tags-list tags-alist (llast 0) rtn level category i txt
8693 todo marker entry priority)
8694 (save-excursion
8695 (goto-char (point-min))
8696 (when (eq action 'sparse-tree)
8697 (org-overview)
8698 (org-remove-occur-highlights))
8699 (while (re-search-forward re nil t)
8700 (catch :skip
8701 (setq todo (if (match-end 1) (match-string 2))
8702 tags (if (match-end 4) (match-string 4)))
8703 (goto-char (setq lspos (1+ (match-beginning 0))))
8704 (setq level (org-reduced-level (funcall outline-level))
8705 category (org-get-category))
8706 (setq i llast llast level)
8707 ;; remove tag lists from same and sublevels
8708 (while (>= i level)
8709 (when (setq entry (assoc i tags-alist))
8710 (setq tags-alist (delete entry tags-alist)))
8711 (setq i (1- i)))
8712 ;; add the next tags
8713 (when tags
8714 (setq tags (mapcar 'downcase (org-split-string tags ":"))
8715 tags-alist
8716 (cons (cons level tags) tags-alist)))
8717 ;; compile tags for current headline
8718 (setq tags-list
8719 (if org-use-tag-inheritance
8720 (apply 'append (mapcar 'cdr tags-alist))
8721 tags))
8722 (when (and tags org-use-tag-inheritance
8723 (not (eq t org-use-tag-inheritance)))
8724 ;; selective inheritance, remove uninherited ones
8725 (setcdr (car tags-alist)
8726 (org-remove-uniherited-tags (cdar tags-alist))))
8727 (when (and (or (not todo-only) (member todo org-not-done-keywords))
8728 (eval matcher)
8729 (or (not org-agenda-skip-archived-trees)
8730 (not (member org-archive-tag tags-list))))
8731 (and (eq action 'agenda) (org-agenda-skip))
8732 ;; list this headline
8734 (if (eq action 'sparse-tree)
8735 (progn
8736 (and org-highlight-sparse-tree-matches
8737 (org-get-heading) (match-end 0)
8738 (org-highlight-new-match
8739 (match-beginning 0) (match-beginning 1)))
8740 (org-show-context 'tags-tree))
8741 (setq txt (org-format-agenda-item
8743 (concat
8744 (if org-tags-match-list-sublevels
8745 (make-string (1- level) ?.) "")
8746 (org-get-heading))
8747 category tags-list)
8748 priority (org-get-priority txt))
8749 (goto-char lspos)
8750 (setq marker (org-agenda-new-marker))
8751 (org-add-props txt props
8752 'org-marker marker 'org-hd-marker marker 'org-category category
8753 'priority priority 'type "tagsmatch")
8754 (push txt rtn))
8755 ;; if we are to skip sublevels, jump to end of subtree
8756 (or org-tags-match-list-sublevels (org-end-of-subtree t))))))
8757 (when (and (eq action 'sparse-tree)
8758 (not org-sparse-tree-open-archived-trees))
8759 (org-hide-archived-subtrees (point-min) (point-max)))
8760 (nreverse rtn)))
8762 (defun org-remove-uniherited-tags (tags)
8763 "Remove all tags that are not inherited from the list TAGS."
8764 (cond
8765 ((eq org-use-tag-inheritance t) tags)
8766 ((not org-use-tag-inheritance) nil)
8767 ((stringp org-use-tag-inheritance)
8768 (delq nil (mapcar
8769 (lambda (x) (if (string-match org-use-tag-inheritance x) x nil))
8770 tags)))
8771 ((listp org-use-tag-inheritance)
8772 (org-delete-all org-use-tag-inheritance tags))))
8774 (defvar todo-only) ;; dynamically scoped
8776 (defun org-tags-sparse-tree (&optional todo-only match)
8777 "Create a sparse tree according to tags string MATCH.
8778 MATCH can contain positive and negative selection of tags, like
8779 \"+WORK+URGENT-WITHBOSS\".
8780 If optional argument TODO_ONLY is non-nil, only select lines that are
8781 also TODO lines."
8782 (interactive "P")
8783 (org-prepare-agenda-buffers (list (current-buffer)))
8784 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
8786 (defvar org-cached-props nil)
8787 (defun org-cached-entry-get (pom property)
8788 (if (or (eq t org-use-property-inheritance)
8789 (and (stringp org-use-property-inheritance)
8790 (string-match org-use-property-inheritance property))
8791 (and (listp org-use-property-inheritance)
8792 (member property org-use-property-inheritance)))
8793 ;; Caching is not possible, check it directly
8794 (org-entry-get pom property 'inherit)
8795 ;; Get all properties, so that we can do complicated checks easily
8796 (cdr (assoc property (or org-cached-props
8797 (setq org-cached-props
8798 (org-entry-properties pom)))))))
8800 (defun org-global-tags-completion-table (&optional files)
8801 "Return the list of all tags in all agenda buffer/files."
8802 (save-excursion
8803 (org-uniquify
8804 (delq nil
8805 (apply 'append
8806 (mapcar
8807 (lambda (file)
8808 (set-buffer (find-file-noselect file))
8809 (append (org-get-buffer-tags)
8810 (mapcar (lambda (x) (if (stringp (car-safe x))
8811 (list (car-safe x)) nil))
8812 org-tag-alist)))
8813 (if (and files (car files))
8814 files
8815 (org-agenda-files))))))))
8817 (defun org-make-tags-matcher (match)
8818 "Create the TAGS//TODO matcher form for the selection string MATCH."
8819 ;; todo-only is scoped dynamically into this function, and the function
8820 ;; may change it it the matcher asksk for it.
8821 (unless match
8822 ;; Get a new match request, with completion
8823 (let ((org-last-tags-completion-table
8824 (org-global-tags-completion-table)))
8825 (setq match (completing-read
8826 "Match: " 'org-tags-completion-function nil nil nil
8827 'org-tags-history))))
8829 ;; Parse the string and create a lisp form
8830 (let ((match0 match)
8831 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\([[:alnum:]_]+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@]+\\)"))
8832 minus tag mm
8833 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
8834 orterms term orlist re-p str-p level-p level-op
8835 prop-p pn pv po cat-p gv)
8836 (if (string-match "/+" match)
8837 ;; match contains also a todo-matching request
8838 (progn
8839 (setq tagsmatch (substring match 0 (match-beginning 0))
8840 todomatch (substring match (match-end 0)))
8841 (if (string-match "^!" todomatch)
8842 (setq todo-only t todomatch (substring todomatch 1)))
8843 (if (string-match "^\\s-*$" todomatch)
8844 (setq todomatch nil)))
8845 ;; only matching tags
8846 (setq tagsmatch match todomatch nil))
8848 ;; Make the tags matcher
8849 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
8850 (setq tagsmatcher t)
8851 (setq orterms (org-split-string tagsmatch "|") orlist nil)
8852 (while (setq term (pop orterms))
8853 (while (and (equal (substring term -1) "\\") orterms)
8854 (setq term (concat term "|" (pop orterms)))) ; repair bad split
8855 (while (string-match re term)
8856 (setq minus (and (match-end 1)
8857 (equal (match-string 1 term) "-"))
8858 tag (match-string 2 term)
8859 re-p (equal (string-to-char tag) ?{)
8860 level-p (match-end 4)
8861 prop-p (match-end 5)
8862 mm (cond
8863 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
8864 (level-p
8865 (setq level-op (org-op-to-function (match-string 3 term)))
8866 `(,level-op level ,(string-to-number
8867 (match-string 4 term))))
8868 (prop-p
8869 (setq pn (match-string 5 term)
8870 po (match-string 6 term)
8871 pv (match-string 7 term)
8872 cat-p (equal pn "CATEGORY")
8873 re-p (equal (string-to-char pv) ?{)
8874 str-p (equal (string-to-char pv) ?\")
8875 pv (if (or re-p str-p) (substring pv 1 -1) pv))
8876 (setq po (org-op-to-function po str-p))
8877 (if (equal pn "CATEGORY")
8878 (setq gv '(get-text-property (point) 'org-category))
8879 (setq gv `(org-cached-entry-get nil ,pn)))
8880 (if re-p
8881 (if (eq po 'org<>)
8882 `(not (string-match ,pv (or ,gv "")))
8883 `(string-match ,pv (or ,gv "")))
8884 (if str-p
8885 `(,po (or ,gv "") ,pv)
8886 `(,po (string-to-number (or ,gv ""))
8887 ,(string-to-number pv) ))))
8888 (t `(member ,(downcase tag) tags-list)))
8889 mm (if minus (list 'not mm) mm)
8890 term (substring term (match-end 0)))
8891 (push mm tagsmatcher))
8892 (push (if (> (length tagsmatcher) 1)
8893 (cons 'and tagsmatcher)
8894 (car tagsmatcher))
8895 orlist)
8896 (setq tagsmatcher nil))
8897 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
8898 (setq tagsmatcher
8899 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
8900 ;; Make the todo matcher
8901 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
8902 (setq todomatcher t)
8903 (setq orterms (org-split-string todomatch "|") orlist nil)
8904 (while (setq term (pop orterms))
8905 (while (string-match re term)
8906 (setq minus (and (match-end 1)
8907 (equal (match-string 1 term) "-"))
8908 kwd (match-string 2 term)
8909 re-p (equal (string-to-char kwd) ?{)
8910 term (substring term (match-end 0))
8911 mm (if re-p
8912 `(string-match ,(substring kwd 1 -1) todo)
8913 (list 'equal 'todo kwd))
8914 mm (if minus (list 'not mm) mm))
8915 (push mm todomatcher))
8916 (push (if (> (length todomatcher) 1)
8917 (cons 'and todomatcher)
8918 (car todomatcher))
8919 orlist)
8920 (setq todomatcher nil))
8921 (setq todomatcher (if (> (length orlist) 1)
8922 (cons 'or orlist) (car orlist))))
8924 ;; Return the string and lisp forms of the matcher
8925 (setq matcher (if todomatcher
8926 (list 'and tagsmatcher todomatcher)
8927 tagsmatcher))
8928 (cons match0 matcher)))
8930 (defun org-op-to-function (op &optional stringp)
8931 (setq op
8932 (cond
8933 ((equal op "<" ) '(< string< ))
8934 ((equal op ">" ) '(> org-string> ))
8935 ((member op '("<=" "=<")) '(<= org-string<= ))
8936 ((member op '(">=" "=>")) '(>= org-string>= ))
8937 ((member op '("=" "==")) '(= string= ))
8938 ((member op '("<>" "!=")) '(org<> org-string<> ))))
8939 (nth (if stringp 1 0) op))
8941 (defun org<> (a b) (not (= a b)))
8942 (defun org-string<= (a b) (or (string= a b) (string< a b)))
8943 (defun org-string>= (a b) (not (string< a b)))
8944 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
8945 (defun org-string<> (a b) (not (string= a b)))
8947 (defun org-match-any-p (re list)
8948 "Does re match any element of list?"
8949 (setq list (mapcar (lambda (x) (string-match re x)) list))
8950 (delq nil list))
8952 (defvar org-add-colon-after-tag-completion nil) ;; dynamically skoped param
8953 (defvar org-tags-overlay (org-make-overlay 1 1))
8954 (org-detach-overlay org-tags-overlay)
8956 (defun org-get-tags-at (&optional pos)
8957 "Get a list of all headline tags applicable at POS.
8958 POS defaults to point. If tags are inherited, the list contains
8959 the targets in the same sequence as the headlines appear, i.e.
8960 sthe tags of the current headline come last."
8961 (interactive)
8962 (let (tags ltags lastpos parent)
8963 (save-excursion
8964 (save-restriction
8965 (widen)
8966 (goto-char (or pos (point)))
8967 (save-match-data
8968 (condition-case nil
8969 (progn
8970 (org-back-to-heading t)
8971 (while (not (equal lastpos (point)))
8972 (setq lastpos (point))
8973 (when (looking-at (org-re "[^\r\n]+?:\\([[:alnum:]_@:]+\\):[ \t]*$"))
8974 (setq ltags (org-split-string
8975 (org-match-string-no-properties 1) ":"))
8976 (setq tags (append (org-remove-uniherited-tags ltags)
8977 tags)))
8978 (or org-use-tag-inheritance (error ""))
8979 (org-up-heading-all 1)
8980 (setq parent t)))
8981 (error nil))))
8982 tags)))
8984 (defun org-toggle-tag (tag &optional onoff)
8985 "Toggle the tag TAG for the current line.
8986 If ONOFF is `on' or `off', don't toggle but set to this state."
8987 (unless (org-on-heading-p t) (error "Not on headling"))
8988 (let (res current)
8989 (save-excursion
8990 (beginning-of-line)
8991 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t]*$")
8992 (point-at-eol) t)
8993 (progn
8994 (setq current (match-string 1))
8995 (replace-match ""))
8996 (setq current ""))
8997 (setq current (nreverse (org-split-string current ":")))
8998 (cond
8999 ((eq onoff 'on)
9000 (setq res t)
9001 (or (member tag current) (push tag current)))
9002 ((eq onoff 'off)
9003 (or (not (member tag current)) (setq current (delete tag current))))
9004 (t (if (member tag current)
9005 (setq current (delete tag current))
9006 (setq res t)
9007 (push tag current))))
9008 (end-of-line 1)
9009 (if current
9010 (progn
9011 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
9012 (org-set-tags nil t))
9013 (delete-horizontal-space))
9014 (run-hooks 'org-after-tags-change-hook))
9015 res))
9017 (defun org-align-tags-here (to-col)
9018 ;; Assumes that this is a headline
9019 (let ((pos (point)) (col (current-column)) ncol tags-l p)
9020 (beginning-of-line 1)
9021 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
9022 (< pos (match-beginning 2)))
9023 (progn
9024 (setq tags-l (- (match-end 2) (match-beginning 2)))
9025 (goto-char (match-beginning 1))
9026 (insert " ")
9027 (delete-region (point) (1+ (match-beginning 2)))
9028 (setq ncol (max (1+ (current-column))
9029 (1+ col)
9030 (if (> to-col 0)
9031 to-col
9032 (- (abs to-col) tags-l))))
9033 (setq p (point))
9034 (insert (make-string (- ncol (current-column)) ?\ ))
9035 (setq ncol (current-column))
9036 (tabify p (point-at-eol))
9037 (org-move-to-column (min ncol col) t))
9038 (goto-char pos))))
9040 (defun org-set-tags (&optional arg just-align)
9041 "Set the tags for the current headline.
9042 With prefix ARG, realign all tags in headings in the current buffer."
9043 (interactive "P")
9044 (let* ((re (concat "^" outline-regexp))
9045 (current (org-get-tags-string))
9046 (col (current-column))
9047 (org-setting-tags t)
9048 table current-tags inherited-tags ; computed below when needed
9049 tags p0 c0 c1 rpl)
9050 (if arg
9051 (save-excursion
9052 (goto-char (point-min))
9053 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
9054 (while (re-search-forward re nil t)
9055 (org-set-tags nil t)
9056 (end-of-line 1)))
9057 (message "All tags realigned to column %d" org-tags-column))
9058 (if just-align
9059 (setq tags current)
9060 ;; Get a new set of tags from the user
9061 (save-excursion
9062 (setq table (or org-tag-alist (org-get-buffer-tags))
9063 org-last-tags-completion-table table
9064 current-tags (org-split-string current ":")
9065 inherited-tags (nreverse
9066 (nthcdr (length current-tags)
9067 (nreverse (org-get-tags-at))))
9068 tags
9069 (if (or (eq t org-use-fast-tag-selection)
9070 (and org-use-fast-tag-selection
9071 (delq nil (mapcar 'cdr table))))
9072 (org-fast-tag-selection
9073 current-tags inherited-tags table
9074 (if org-fast-tag-selection-include-todo org-todo-key-alist))
9075 (let ((org-add-colon-after-tag-completion t))
9076 (org-trim
9077 (org-without-partial-completion
9078 (completing-read "Tags: " 'org-tags-completion-function
9079 nil nil current 'org-tags-history)))))))
9080 (while (string-match "[-+&]+" tags)
9081 ;; No boolean logic, just a list
9082 (setq tags (replace-match ":" t t tags))))
9084 (if (string-match "\\`[\t ]*\\'" tags)
9085 (setq tags "")
9086 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
9087 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
9089 ;; Insert new tags at the correct column
9090 (beginning-of-line 1)
9091 (cond
9092 ((and (equal current "") (equal tags "")))
9093 ((re-search-forward
9094 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
9095 (point-at-eol) t)
9096 (if (equal tags "")
9097 (setq rpl "")
9098 (goto-char (match-beginning 0))
9099 (setq c0 (current-column) p0 (point)
9100 c1 (max (1+ c0) (if (> org-tags-column 0)
9101 org-tags-column
9102 (- (- org-tags-column) (length tags))))
9103 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
9104 (replace-match rpl t t)
9105 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
9106 tags)
9107 (t (error "Tags alignment failed")))
9108 (org-move-to-column col)
9109 (unless just-align
9110 (run-hooks 'org-after-tags-change-hook)))))
9112 (defun org-change-tag-in-region (beg end tag off)
9113 "Add or remove TAG for each entry in the region.
9114 This works in the agenda, and also in an org-mode buffer."
9115 (interactive
9116 (list (region-beginning) (region-end)
9117 (let ((org-last-tags-completion-table
9118 (if (org-mode-p)
9119 (org-get-buffer-tags)
9120 (org-global-tags-completion-table))))
9121 (completing-read
9122 "Tag: " 'org-tags-completion-function nil nil nil
9123 'org-tags-history))
9124 (progn
9125 (message "[s]et or [r]emove? ")
9126 (equal (read-char-exclusive) ?r))))
9127 (if (fboundp 'deactivate-mark) (deactivate-mark))
9128 (let ((agendap (equal major-mode 'org-agenda-mode))
9129 l1 l2 m buf pos newhead (cnt 0))
9130 (goto-char end)
9131 (setq l2 (1- (org-current-line)))
9132 (goto-char beg)
9133 (setq l1 (org-current-line))
9134 (loop for l from l1 to l2 do
9135 (goto-line l)
9136 (setq m (get-text-property (point) 'org-hd-marker))
9137 (when (or (and (org-mode-p) (org-on-heading-p))
9138 (and agendap m))
9139 (setq buf (if agendap (marker-buffer m) (current-buffer))
9140 pos (if agendap m (point)))
9141 (with-current-buffer buf
9142 (save-excursion
9143 (save-restriction
9144 (goto-char pos)
9145 (setq cnt (1+ cnt))
9146 (org-toggle-tag tag (if off 'off 'on))
9147 (setq newhead (org-get-heading)))))
9148 (and agendap (org-agenda-change-all-lines newhead m))))
9149 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
9151 (defun org-tags-completion-function (string predicate &optional flag)
9152 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
9153 (confirm (lambda (x) (stringp (car x)))))
9154 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
9155 (setq s1 (match-string 1 string)
9156 s2 (match-string 2 string))
9157 (setq s1 "" s2 string))
9158 (cond
9159 ((eq flag nil)
9160 ;; try completion
9161 (setq rtn (try-completion s2 ctable confirm))
9162 (if (stringp rtn)
9163 (setq rtn
9164 (concat s1 s2 (substring rtn (length s2))
9165 (if (and org-add-colon-after-tag-completion
9166 (assoc rtn ctable))
9167 ":" ""))))
9168 rtn)
9169 ((eq flag t)
9170 ;; all-completions
9171 (all-completions s2 ctable confirm)
9173 ((eq flag 'lambda)
9174 ;; exact match?
9175 (assoc s2 ctable)))
9178 (defun org-fast-tag-insert (kwd tags face &optional end)
9179 "Insert KDW, and the TAGS, the latter with face FACE. Also inser END."
9180 (insert (format "%-12s" (concat kwd ":"))
9181 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
9182 (or end "")))
9184 (defun org-fast-tag-show-exit (flag)
9185 (save-excursion
9186 (goto-line 3)
9187 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
9188 (replace-match ""))
9189 (when flag
9190 (end-of-line 1)
9191 (org-move-to-column (- (window-width) 19) t)
9192 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
9194 (defun org-set-current-tags-overlay (current prefix)
9195 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
9196 (if (featurep 'xemacs)
9197 (org-overlay-display org-tags-overlay (concat prefix s)
9198 'secondary-selection)
9199 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
9200 (org-overlay-display org-tags-overlay (concat prefix s)))))
9202 (defun org-fast-tag-selection (current inherited table &optional todo-table)
9203 "Fast tag selection with single keys.
9204 CURRENT is the current list of tags in the headline, INHERITED is the
9205 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
9206 possibly with grouping information. TODO-TABLE is a similar table with
9207 TODO keywords, should these have keys assigned to them.
9208 If the keys are nil, a-z are automatically assigned.
9209 Returns the new tags string, or nil to not change the current settings."
9210 (let* ((fulltable (append table todo-table))
9211 (maxlen (apply 'max (mapcar
9212 (lambda (x)
9213 (if (stringp (car x)) (string-width (car x)) 0))
9214 fulltable)))
9215 (buf (current-buffer))
9216 (expert (eq org-fast-tag-selection-single-key 'expert))
9217 (buffer-tags nil)
9218 (fwidth (+ maxlen 3 1 3))
9219 (ncol (/ (- (window-width) 4) fwidth))
9220 (i-face 'org-done)
9221 (c-face 'org-todo)
9222 tg cnt e c char c1 c2 ntable tbl rtn
9223 ov-start ov-end ov-prefix
9224 (exit-after-next org-fast-tag-selection-single-key)
9225 (done-keywords org-done-keywords)
9226 groups ingroup)
9227 (save-excursion
9228 (beginning-of-line 1)
9229 (if (looking-at
9230 (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
9231 (setq ov-start (match-beginning 1)
9232 ov-end (match-end 1)
9233 ov-prefix "")
9234 (setq ov-start (1- (point-at-eol))
9235 ov-end (1+ ov-start))
9236 (skip-chars-forward "^\n\r")
9237 (setq ov-prefix
9238 (concat
9239 (buffer-substring (1- (point)) (point))
9240 (if (> (current-column) org-tags-column)
9242 (make-string (- org-tags-column (current-column)) ?\ ))))))
9243 (org-move-overlay org-tags-overlay ov-start ov-end)
9244 (save-window-excursion
9245 (if expert
9246 (set-buffer (get-buffer-create " *Org tags*"))
9247 (delete-other-windows)
9248 (split-window-vertically)
9249 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
9250 (erase-buffer)
9251 (org-set-local 'org-done-keywords done-keywords)
9252 (org-fast-tag-insert "Inherited" inherited i-face "\n")
9253 (org-fast-tag-insert "Current" current c-face "\n\n")
9254 (org-fast-tag-show-exit exit-after-next)
9255 (org-set-current-tags-overlay current ov-prefix)
9256 (setq tbl fulltable char ?a cnt 0)
9257 (while (setq e (pop tbl))
9258 (cond
9259 ((equal e '(:startgroup))
9260 (push '() groups) (setq ingroup t)
9261 (when (not (= cnt 0))
9262 (setq cnt 0)
9263 (insert "\n"))
9264 (insert "{ "))
9265 ((equal e '(:endgroup))
9266 (setq ingroup nil cnt 0)
9267 (insert "}\n"))
9269 (setq tg (car e) c2 nil)
9270 (if (cdr e)
9271 (setq c (cdr e))
9272 ;; automatically assign a character.
9273 (setq c1 (string-to-char
9274 (downcase (substring
9275 tg (if (= (string-to-char tg) ?@) 1 0)))))
9276 (if (or (rassoc c1 ntable) (rassoc c1 table))
9277 (while (or (rassoc char ntable) (rassoc char table))
9278 (setq char (1+ char)))
9279 (setq c2 c1))
9280 (setq c (or c2 char)))
9281 (if ingroup (push tg (car groups)))
9282 (setq tg (org-add-props tg nil 'face
9283 (cond
9284 ((not (assoc tg table))
9285 (org-get-todo-face tg))
9286 ((member tg current) c-face)
9287 ((member tg inherited) i-face)
9288 (t nil))))
9289 (if (and (= cnt 0) (not ingroup)) (insert " "))
9290 (insert "[" c "] " tg (make-string
9291 (- fwidth 4 (length tg)) ?\ ))
9292 (push (cons tg c) ntable)
9293 (when (= (setq cnt (1+ cnt)) ncol)
9294 (insert "\n")
9295 (if ingroup (insert " "))
9296 (setq cnt 0)))))
9297 (setq ntable (nreverse ntable))
9298 (insert "\n")
9299 (goto-char (point-min))
9300 (if (and (not expert) (fboundp 'fit-window-to-buffer))
9301 (fit-window-to-buffer))
9302 (setq rtn
9303 (catch 'exit
9304 (while t
9305 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free%s%s"
9306 (if groups " [!] no groups" " [!]groups")
9307 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
9308 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
9309 (cond
9310 ((= c ?\r) (throw 'exit t))
9311 ((= c ?!)
9312 (setq groups (not groups))
9313 (goto-char (point-min))
9314 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
9315 ((= c ?\C-c)
9316 (if (not expert)
9317 (org-fast-tag-show-exit
9318 (setq exit-after-next (not exit-after-next)))
9319 (setq expert nil)
9320 (delete-other-windows)
9321 (split-window-vertically)
9322 (org-switch-to-buffer-other-window " *Org tags*")
9323 (and (fboundp 'fit-window-to-buffer)
9324 (fit-window-to-buffer))))
9325 ((or (= c ?\C-g)
9326 (and (= c ?q) (not (rassoc c ntable))))
9327 (org-detach-overlay org-tags-overlay)
9328 (setq quit-flag t))
9329 ((= c ?\ )
9330 (setq current nil)
9331 (if exit-after-next (setq exit-after-next 'now)))
9332 ((= c ?\t)
9333 (condition-case nil
9334 (setq tg (completing-read
9335 "Tag: "
9336 (or buffer-tags
9337 (with-current-buffer buf
9338 (org-get-buffer-tags)))))
9339 (quit (setq tg "")))
9340 (when (string-match "\\S-" tg)
9341 (add-to-list 'buffer-tags (list tg))
9342 (if (member tg current)
9343 (setq current (delete tg current))
9344 (push tg current)))
9345 (if exit-after-next (setq exit-after-next 'now)))
9346 ((setq e (rassoc c todo-table) tg (car e))
9347 (with-current-buffer buf
9348 (save-excursion (org-todo tg)))
9349 (if exit-after-next (setq exit-after-next 'now)))
9350 ((setq e (rassoc c ntable) tg (car e))
9351 (if (member tg current)
9352 (setq current (delete tg current))
9353 (loop for g in groups do
9354 (if (member tg g)
9355 (mapc (lambda (x)
9356 (setq current (delete x current)))
9357 g)))
9358 (push tg current))
9359 (if exit-after-next (setq exit-after-next 'now))))
9361 ;; Create a sorted list
9362 (setq current
9363 (sort current
9364 (lambda (a b)
9365 (assoc b (cdr (memq (assoc a ntable) ntable))))))
9366 (if (eq exit-after-next 'now) (throw 'exit t))
9367 (goto-char (point-min))
9368 (beginning-of-line 2)
9369 (delete-region (point) (point-at-eol))
9370 (org-fast-tag-insert "Current" current c-face)
9371 (org-set-current-tags-overlay current ov-prefix)
9372 (while (re-search-forward
9373 (org-re "\\[.\\] \\([[:alnum:]_@]+\\)") nil t)
9374 (setq tg (match-string 1))
9375 (add-text-properties
9376 (match-beginning 1) (match-end 1)
9377 (list 'face
9378 (cond
9379 ((member tg current) c-face)
9380 ((member tg inherited) i-face)
9381 (t (get-text-property (match-beginning 1) 'face))))))
9382 (goto-char (point-min)))))
9383 (org-detach-overlay org-tags-overlay)
9384 (if rtn
9385 (mapconcat 'identity current ":")
9386 nil))))
9388 (defun org-get-tags-string ()
9389 "Get the TAGS string in the current headline."
9390 (unless (org-on-heading-p t)
9391 (error "Not on a heading"))
9392 (save-excursion
9393 (beginning-of-line 1)
9394 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
9395 (org-match-string-no-properties 1)
9396 "")))
9398 (defun org-get-tags ()
9399 "Get the list of tags specified in the current headline."
9400 (org-split-string (org-get-tags-string) ":"))
9402 (defun org-get-buffer-tags ()
9403 "Get a table of all tags used in the buffer, for completion."
9404 (let (tags)
9405 (save-excursion
9406 (goto-char (point-min))
9407 (while (re-search-forward
9408 (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t\r\n]") nil t)
9409 (when (equal (char-after (point-at-bol 0)) ?*)
9410 (mapc (lambda (x) (add-to-list 'tags x))
9411 (org-split-string (org-match-string-no-properties 1) ":")))))
9412 (mapcar 'list tags)))
9415 ;;;; Properties
9417 ;;; Setting and retrieving properties
9419 (defconst org-special-properties
9420 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "PRIORITY"
9421 "TIMESTAMP" "TIMESTAMP_IA")
9422 "The special properties valid in Org-mode.
9424 These are properties that are not defined in the property drawer,
9425 but in some other way.")
9427 (defconst org-default-properties
9428 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION"
9429 "LOCATION" "LOGGING" "COLUMNS")
9430 "Some properties that are used by Org-mode for various purposes.
9431 Being in this list makes sure that they are offered for completion.")
9433 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
9434 "Regular expression matching the first line of a property drawer.")
9436 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
9437 "Regular expression matching the first line of a property drawer.")
9439 (defun org-property-action ()
9440 "Do an action on properties."
9441 (interactive)
9442 (let (c)
9443 (org-at-property-p)
9444 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
9445 (setq c (read-char-exclusive))
9446 (cond
9447 ((equal c ?s)
9448 (call-interactively 'org-set-property))
9449 ((equal c ?d)
9450 (call-interactively 'org-delete-property))
9451 ((equal c ?D)
9452 (call-interactively 'org-delete-property-globally))
9453 ((equal c ?c)
9454 (call-interactively 'org-compute-property-at-point))
9455 (t (error "No such property action %c" c)))))
9457 (defun org-at-property-p ()
9458 "Is the cursor in a property line?"
9459 ;; FIXME: Does not check if we are actually in the drawer.
9460 ;; FIXME: also returns true on any drawers.....
9461 ;; This is used by C-c C-c for property action.
9462 (save-excursion
9463 (beginning-of-line 1)
9464 (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))))
9466 (defun org-get-property-block (&optional beg end force)
9467 "Return the (beg . end) range of the body of the property drawer.
9468 BEG and END can be beginning and end of subtree, if not given
9469 they will be found.
9470 If the drawer does not exist and FORCE is non-nil, create the drawer."
9471 (catch 'exit
9472 (save-excursion
9473 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
9474 (end (or end (progn (outline-next-heading) (point)))))
9475 (goto-char beg)
9476 (if (re-search-forward org-property-start-re end t)
9477 (setq beg (1+ (match-end 0)))
9478 (if force
9479 (save-excursion
9480 (org-insert-property-drawer)
9481 (setq end (progn (outline-next-heading) (point))))
9482 (throw 'exit nil))
9483 (goto-char beg)
9484 (if (re-search-forward org-property-start-re end t)
9485 (setq beg (1+ (match-end 0)))))
9486 (if (re-search-forward org-property-end-re end t)
9487 (setq end (match-beginning 0))
9488 (or force (throw 'exit nil))
9489 (goto-char beg)
9490 (setq end beg)
9491 (org-indent-line-function)
9492 (insert ":END:\n"))
9493 (cons beg end)))))
9495 (defun org-entry-properties (&optional pom which)
9496 "Get all properties of the entry at point-or-marker POM.
9497 This includes the TODO keyword, the tags, time strings for deadline,
9498 scheduled, and clocking, and any additional properties defined in the
9499 entry. The return value is an alist, keys may occur multiple times
9500 if the property key was used several times.
9501 POM may also be nil, in which case the current entry is used.
9502 If WHICH is nil or `all', get all properties. If WHICH is
9503 `special' or `standard', only get that subclass."
9504 (setq which (or which 'all))
9505 (org-with-point-at pom
9506 (let ((clockstr (substring org-clock-string 0 -1))
9507 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY"))
9508 beg end range props sum-props key value string clocksum)
9509 (save-excursion
9510 (when (condition-case nil (org-back-to-heading t) (error nil))
9511 (setq beg (point))
9512 (setq sum-props (get-text-property (point) 'org-summaries))
9513 (setq clocksum (get-text-property (point) :org-clock-minutes))
9514 (outline-next-heading)
9515 (setq end (point))
9516 (when (memq which '(all special))
9517 ;; Get the special properties, like TODO and tags
9518 (goto-char beg)
9519 (when (and (looking-at org-todo-line-regexp) (match-end 2))
9520 (push (cons "TODO" (org-match-string-no-properties 2)) props))
9521 (when (looking-at org-priority-regexp)
9522 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
9523 (when (and (setq value (org-get-tags-string))
9524 (string-match "\\S-" value))
9525 (push (cons "TAGS" value) props))
9526 (when (setq value (org-get-tags-at))
9527 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":") ":"))
9528 props))
9529 (while (re-search-forward org-maybe-keyword-time-regexp end t)
9530 (setq key (if (match-end 1) (substring (org-match-string-no-properties 1) 0 -1))
9531 string (if (equal key clockstr)
9532 (org-no-properties
9533 (org-trim
9534 (buffer-substring
9535 (match-beginning 3) (goto-char (point-at-eol)))))
9536 (substring (org-match-string-no-properties 3) 1 -1)))
9537 (unless key
9538 (if (= (char-after (match-beginning 3)) ?\[)
9539 (setq key "TIMESTAMP_IA")
9540 (setq key "TIMESTAMP")))
9541 (when (or (equal key clockstr) (not (assoc key props)))
9542 (push (cons key string) props)))
9546 (when (memq which '(all standard))
9547 ;; Get the standard properties, like :PORP: ...
9548 (setq range (org-get-property-block beg end))
9549 (when range
9550 (goto-char (car range))
9551 (while (re-search-forward
9552 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
9553 (cdr range) t)
9554 (setq key (org-match-string-no-properties 1)
9555 value (org-trim (or (org-match-string-no-properties 2) "")))
9556 (unless (member key excluded)
9557 (push (cons key (or value "")) props)))))
9558 (if clocksum
9559 (push (cons "CLOCKSUM"
9560 (org-columns-number-to-string (/ (float clocksum) 60.)
9561 'add_times))
9562 props))
9563 (append sum-props (nreverse props)))))))
9565 (defun org-entry-get (pom property &optional inherit)
9566 "Get value of PROPERTY for entry at point-or-marker POM.
9567 If INHERIT is non-nil and the entry does not have the property,
9568 then also check higher levels of the hierarchy.
9569 If INHERIT is the symbol `selective', use inheritance only if the setting
9570 in `org-use-property-inheritance' selects PROPERTY for inheritance.
9571 If the property is present but empty, the return value is the empty string.
9572 If the property is not present at all, nil is returned."
9573 (org-with-point-at pom
9574 (if (and inherit (if (eq inherit 'selective)
9575 (org-property-inherit-p property)
9577 (org-entry-get-with-inheritance property)
9578 (if (member property org-special-properties)
9579 ;; We need a special property. Use brute force, get all properties.
9580 (cdr (assoc property (org-entry-properties nil 'special)))
9581 (let ((range (org-get-property-block)))
9582 (if (and range
9583 (goto-char (car range))
9584 (re-search-forward
9585 (concat "^[ \t]*:" property ":[ \t]*\\(.*\\S-\\)?")
9586 (cdr range) t))
9587 ;; Found the property, return it.
9588 (if (match-end 1)
9589 (org-match-string-no-properties 1)
9590 "")))))))
9592 (defun org-property-or-variable-value (var &optional inherit)
9593 "Check if there is a property fixing the value of VAR.
9594 If yes, return this value. If not, return the current value of the variable."
9595 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
9596 (if (and prop (stringp prop) (string-match "\\S-" prop))
9597 (read prop)
9598 (symbol-value var))))
9600 (defun org-entry-delete (pom property)
9601 "Delete the property PROPERTY from entry at point-or-marker POM."
9602 (org-with-point-at pom
9603 (if (member property org-special-properties)
9604 nil ; cannot delete these properties.
9605 (let ((range (org-get-property-block)))
9606 (if (and range
9607 (goto-char (car range))
9608 (re-search-forward
9609 (concat "^[ \t]*:" property ":[ \t]*\\(.*\\S-\\)")
9610 (cdr range) t))
9611 (progn
9612 (delete-region (match-beginning 0) (1+ (point-at-eol)))
9614 nil)))))
9616 ;; Multi-values properties are properties that contain multiple values
9617 ;; These values are assumed to be single words, separated by whitespace.
9618 (defun org-entry-add-to-multivalued-property (pom property value)
9619 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
9620 (let* ((old (org-entry-get pom property))
9621 (values (and old (org-split-string old "[ \t]"))))
9622 (unless (member value values)
9623 (setq values (cons value values))
9624 (org-entry-put pom property
9625 (mapconcat 'identity values " ")))))
9627 (defun org-entry-remove-from-multivalued-property (pom property value)
9628 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
9629 (let* ((old (org-entry-get pom property))
9630 (values (and old (org-split-string old "[ \t]"))))
9631 (when (member value values)
9632 (setq values (delete value values))
9633 (org-entry-put pom property
9634 (mapconcat 'identity values " ")))))
9636 (defun org-entry-member-in-multivalued-property (pom property value)
9637 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
9638 (let* ((old (org-entry-get pom property))
9639 (values (and old (org-split-string old "[ \t]"))))
9640 (member value values)))
9642 (defvar org-entry-property-inherited-from (make-marker))
9644 (defun org-entry-get-with-inheritance (property)
9645 "Get entry property, and search higher levels if not present."
9646 (let (tmp)
9647 (save-excursion
9648 (save-restriction
9649 (widen)
9650 (catch 'ex
9651 (while t
9652 (when (setq tmp (org-entry-get nil property))
9653 (org-back-to-heading t)
9654 (move-marker org-entry-property-inherited-from (point))
9655 (throw 'ex tmp))
9656 (or (org-up-heading-safe) (throw 'ex nil)))))
9657 (or tmp (cdr (assoc property org-local-properties))
9658 (cdr (assoc property org-global-properties))))))
9660 (defun org-entry-put (pom property value)
9661 "Set PROPERTY to VALUE for entry at point-or-marker POM."
9662 (org-with-point-at pom
9663 (org-back-to-heading t)
9664 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
9665 range)
9666 (cond
9667 ((equal property "TODO")
9668 (when (and (stringp value) (string-match "\\S-" value)
9669 (not (member value org-todo-keywords-1)))
9670 (error "\"%s\" is not a valid TODO state" value))
9671 (if (or (not value)
9672 (not (string-match "\\S-" value)))
9673 (setq value 'none))
9674 (org-todo value)
9675 (org-set-tags nil 'align))
9676 ((equal property "PRIORITY")
9677 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
9678 (string-to-char value) ?\ ))
9679 (org-set-tags nil 'align))
9680 ((equal property "SCHEDULED")
9681 (if (re-search-forward org-scheduled-time-regexp end t)
9682 (cond
9683 ((eq value 'earlier) (org-timestamp-change -1 'day))
9684 ((eq value 'later) (org-timestamp-change 1 'day))
9685 (t (call-interactively 'org-schedule)))
9686 (call-interactively 'org-schedule)))
9687 ((equal property "DEADLINE")
9688 (if (re-search-forward org-deadline-time-regexp end t)
9689 (cond
9690 ((eq value 'earlier) (org-timestamp-change -1 'day))
9691 ((eq value 'later) (org-timestamp-change 1 'day))
9692 (t (call-interactively 'org-deadline)))
9693 (call-interactively 'org-deadline)))
9694 ((member property org-special-properties)
9695 (error "The %s property can not yet be set with `org-entry-put'"
9696 property))
9697 (t ; a non-special property
9698 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
9699 (setq range (org-get-property-block beg end 'force))
9700 (goto-char (car range))
9701 (if (re-search-forward
9702 (concat "^[ \t]*:" property ":\\(.*\\)") (cdr range) t)
9703 (progn
9704 (delete-region (match-beginning 1) (match-end 1))
9705 (goto-char (match-beginning 1)))
9706 (goto-char (cdr range))
9707 (insert "\n")
9708 (backward-char 1)
9709 (org-indent-line-function)
9710 (insert ":" property ":"))
9711 (and value (insert " " value))
9712 (org-indent-line-function)))))))
9714 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
9715 "Get all property keys in the current buffer.
9716 With INCLUDE-SPECIALS, also list the special properties that relect things
9717 like tags and TODO state.
9718 With INCLUDE-DEFAULTS, also include properties that has special meaning
9719 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING.
9720 With INCLUDE-COLUMNS, also include property names given in COLUMN
9721 formats in the current buffer."
9722 (let (rtn range cfmt cols s p)
9723 (save-excursion
9724 (save-restriction
9725 (widen)
9726 (goto-char (point-min))
9727 (while (re-search-forward org-property-start-re nil t)
9728 (setq range (org-get-property-block))
9729 (goto-char (car range))
9730 (while (re-search-forward
9731 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
9732 (cdr range) t)
9733 (add-to-list 'rtn (org-match-string-no-properties 1)))
9734 (outline-next-heading))))
9736 (when include-specials
9737 (setq rtn (append org-special-properties rtn)))
9739 (when include-defaults
9740 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties))
9742 (when include-columns
9743 (save-excursion
9744 (save-restriction
9745 (widen)
9746 (goto-char (point-min))
9747 (while (re-search-forward
9748 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
9749 nil t)
9750 (setq cfmt (match-string 2) s 0)
9751 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
9752 cfmt s)
9753 (setq s (match-end 0)
9754 p (match-string 1 cfmt))
9755 (unless (or (equal p "ITEM")
9756 (member p org-special-properties))
9757 (add-to-list 'rtn (match-string 1 cfmt))))))))
9759 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
9761 (defun org-property-values (key)
9762 "Return a list of all values of property KEY."
9763 (save-excursion
9764 (save-restriction
9765 (widen)
9766 (goto-char (point-min))
9767 (let ((re (concat "^[ \t]*:" key ":[ \t]*\\(\\S-.*\\)"))
9768 values)
9769 (while (re-search-forward re nil t)
9770 (add-to-list 'values (org-trim (match-string 1))))
9771 (delete "" values)))))
9773 (defun org-insert-property-drawer ()
9774 "Insert a property drawer into the current entry."
9775 (interactive)
9776 (org-back-to-heading t)
9777 (looking-at outline-regexp)
9778 (let ((indent (- (match-end 0)(match-beginning 0)))
9779 (beg (point))
9780 (re (concat "^[ \t]*" org-keyword-time-regexp))
9781 end hiddenp)
9782 (outline-next-heading)
9783 (setq end (point))
9784 (goto-char beg)
9785 (while (re-search-forward re end t))
9786 (setq hiddenp (org-invisible-p))
9787 (end-of-line 1)
9788 (and (equal (char-after) ?\n) (forward-char 1))
9789 (while (looking-at "^[ \t]*\\(:CLOCK:\\|CLOCK\\|:END:\\)")
9790 (beginning-of-line 2))
9791 (org-skip-over-state-notes)
9792 (skip-chars-backward " \t\n\r")
9793 (if (eq (char-before) ?*) (forward-char 1))
9794 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
9795 (beginning-of-line 0)
9796 (org-indent-to-column indent)
9797 (beginning-of-line 2)
9798 (org-indent-to-column indent)
9799 (beginning-of-line 0)
9800 (if hiddenp
9801 (save-excursion
9802 (org-back-to-heading t)
9803 (hide-entry))
9804 (org-flag-drawer t))))
9806 (defun org-set-property (property value)
9807 "In the current entry, set PROPERTY to VALUE.
9808 When called interactively, this will prompt for a property name, offering
9809 completion on existing and default properties. And then it will prompt
9810 for a value, offering competion either on allowed values (via an inherited
9811 xxx_ALL property) or on existing values in other instances of this property
9812 in the current file."
9813 (interactive
9814 (let* ((prop (completing-read
9815 "Property: " (mapcar 'list (org-buffer-property-keys nil t t))))
9816 (cur (org-entry-get nil prop))
9817 (allowed (org-property-get-allowed-values nil prop 'table))
9818 (existing (mapcar 'list (org-property-values prop)))
9819 (val (if allowed
9820 (completing-read "Value: " allowed nil 'req-match)
9821 (completing-read
9822 (concat "Value" (if (and cur (string-match "\\S-" cur))
9823 (concat "[" cur "]") "")
9824 ": ")
9825 existing nil nil "" nil cur))))
9826 (list prop (if (equal val "") cur val))))
9827 (unless (equal (org-entry-get nil property) value)
9828 (org-entry-put nil property value)))
9830 (defun org-delete-property (property)
9831 "In the current entry, delete PROPERTY."
9832 (interactive
9833 (let* ((prop (completing-read
9834 "Property: " (org-entry-properties nil 'standard))))
9835 (list prop)))
9836 (message "Property %s %s" property
9837 (if (org-entry-delete nil property)
9838 "deleted"
9839 "was not present in the entry")))
9841 (defun org-delete-property-globally (property)
9842 "Remove PROPERTY globally, from all entries."
9843 (interactive
9844 (let* ((prop (completing-read
9845 "Globally remove property: "
9846 (mapcar 'list (org-buffer-property-keys)))))
9847 (list prop)))
9848 (save-excursion
9849 (save-restriction
9850 (widen)
9851 (goto-char (point-min))
9852 (let ((cnt 0))
9853 (while (re-search-forward
9854 (concat "^[ \t]*:" (regexp-quote property) ":.*\n?")
9855 nil t)
9856 (setq cnt (1+ cnt))
9857 (replace-match ""))
9858 (message "Property \"%s\" removed from %d entries" property cnt)))))
9860 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
9862 (defun org-compute-property-at-point ()
9863 "Compute the property at point.
9864 This looks for an enclosing column format, extracts the operator and
9865 then applies it to the proerty in the column format's scope."
9866 (interactive)
9867 (unless (org-at-property-p)
9868 (error "Not at a property"))
9869 (let ((prop (org-match-string-no-properties 2)))
9870 (org-columns-get-format-and-top-level)
9871 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
9872 (error "No operator defined for property %s" prop))
9873 (org-columns-compute prop)))
9875 (defun org-property-get-allowed-values (pom property &optional table)
9876 "Get allowed values for the property PROPERTY.
9877 When TABLE is non-nil, return an alist that can directly be used for
9878 completion."
9879 (let (vals)
9880 (cond
9881 ((equal property "TODO")
9882 (setq vals (org-with-point-at pom
9883 (append org-todo-keywords-1 '("")))))
9884 ((equal property "PRIORITY")
9885 (let ((n org-lowest-priority))
9886 (while (>= n org-highest-priority)
9887 (push (char-to-string n) vals)
9888 (setq n (1- n)))))
9889 ((member property org-special-properties))
9891 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
9893 (when (and vals (string-match "\\S-" vals))
9894 (setq vals (car (read-from-string (concat "(" vals ")"))))
9895 (setq vals (mapcar (lambda (x)
9896 (cond ((stringp x) x)
9897 ((numberp x) (number-to-string x))
9898 ((symbolp x) (symbol-name x))
9899 (t "???")))
9900 vals)))))
9901 (if table (mapcar 'list vals) vals)))
9903 (defun org-property-previous-allowed-value (&optional previous)
9904 "Switch to the next allowed value for this property."
9905 (interactive)
9906 (org-property-next-allowed-value t))
9908 (defun org-property-next-allowed-value (&optional previous)
9909 "Switch to the next allowed value for this property."
9910 (interactive)
9911 (unless (org-at-property-p)
9912 (error "Not at a property"))
9913 (let* ((key (match-string 2))
9914 (value (match-string 3))
9915 (allowed (or (org-property-get-allowed-values (point) key)
9916 (and (member value '("[ ]" "[-]" "[X]"))
9917 '("[ ]" "[X]"))))
9918 nval)
9919 (unless allowed
9920 (error "Allowed values for this property have not been defined"))
9921 (if previous (setq allowed (reverse allowed)))
9922 (if (member value allowed)
9923 (setq nval (car (cdr (member value allowed)))))
9924 (setq nval (or nval (car allowed)))
9925 (if (equal nval value)
9926 (error "Only one allowed value for this property"))
9927 (org-at-property-p)
9928 (replace-match (concat " :" key ": " nval) t t)
9929 (org-indent-line-function)
9930 (beginning-of-line 1)
9931 (skip-chars-forward " \t")))
9933 (defun org-find-entry-with-id (ident)
9934 "Locate the entry that contains the ID property with exact value IDENT.
9935 IDENT can be a string, a symbol or a number, this function will search for
9936 the string representation of it.
9937 Return the position where this entry starts, or nil if there is no such entry."
9938 (let ((id (cond
9939 ((stringp ident) ident)
9940 ((symbol-name ident) (symbol-name ident))
9941 ((numberp ident) (number-to-string ident))
9942 (t (error "IDENT %s must be a string, symbol or number" ident))))
9943 (case-fold-search nil))
9944 (save-excursion
9945 (save-restriction
9946 (widen)
9947 (goto-char (point-min))
9948 (when (re-search-forward
9949 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
9950 nil t)
9951 (org-back-to-heading)
9952 (point))))))
9954 ;;;; Timestamps
9956 (defvar org-last-changed-timestamp nil)
9957 (defvar org-time-was-given) ; dynamically scoped parameter
9958 (defvar org-end-time-was-given) ; dynamically scoped parameter
9959 (defvar org-ts-what) ; dynamically scoped parameter
9961 (defun org-time-stamp (arg)
9962 "Prompt for a date/time and insert a time stamp.
9963 If the user specifies a time like HH:MM, or if this command is called
9964 with a prefix argument, the time stamp will contain date and time.
9965 Otherwise, only the date will be included. All parts of a date not
9966 specified by the user will be filled in from the current date/time.
9967 So if you press just return without typing anything, the time stamp
9968 will represent the current date/time. If there is already a timestamp
9969 at the cursor, it will be modified."
9970 (interactive "P")
9971 (let* ((ts nil)
9972 (default-time
9973 ;; Default time is either today, or, when entering a range,
9974 ;; the range start.
9975 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
9976 (save-excursion
9977 (re-search-backward
9978 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
9979 (- (point) 20) t)))
9980 (apply 'encode-time (org-parse-time-string (match-string 1)))
9981 (current-time)))
9982 (default-input (and ts (org-get-compact-tod ts)))
9983 org-time-was-given org-end-time-was-given time)
9984 (cond
9985 ((and (org-at-timestamp-p)
9986 (eq last-command 'org-time-stamp)
9987 (eq this-command 'org-time-stamp))
9988 (insert "--")
9989 (setq time (let ((this-command this-command))
9990 (org-read-date arg 'totime nil nil default-time default-input)))
9991 (org-insert-time-stamp time (or org-time-was-given arg)))
9992 ((org-at-timestamp-p)
9993 (setq time (let ((this-command this-command))
9994 (org-read-date arg 'totime nil nil default-time default-input)))
9995 (when (org-at-timestamp-p) ; just to get the match data
9996 (replace-match "")
9997 (setq org-last-changed-timestamp
9998 (org-insert-time-stamp
9999 time (or org-time-was-given arg)
10000 nil nil nil (list org-end-time-was-given))))
10001 (message "Timestamp updated"))
10003 (setq time (let ((this-command this-command))
10004 (org-read-date arg 'totime nil nil default-time default-input)))
10005 (org-insert-time-stamp time (or org-time-was-given arg)
10006 nil nil nil (list org-end-time-was-given))))))
10008 ;; FIXME: can we use this for something else, like computing time differences?
10009 (defun org-get-compact-tod (s)
10010 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
10011 (let* ((t1 (match-string 1 s))
10012 (h1 (string-to-number (match-string 2 s)))
10013 (m1 (string-to-number (match-string 3 s)))
10014 (t2 (and (match-end 4) (match-string 5 s)))
10015 (h2 (and t2 (string-to-number (match-string 6 s))))
10016 (m2 (and t2 (string-to-number (match-string 7 s))))
10017 dh dm)
10018 (if (not t2)
10020 (setq dh (- h2 h1) dm (- m2 m1))
10021 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
10022 (concat t1 "+" (number-to-string dh)
10023 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
10025 (defun org-time-stamp-inactive (&optional arg)
10026 "Insert an inactive time stamp.
10027 An inactive time stamp is enclosed in square brackets instead of angle
10028 brackets. It is inactive in the sense that it does not trigger agenda entries,
10029 does not link to the calendar and cannot be changed with the S-cursor keys.
10030 So these are more for recording a certain time/date."
10031 (interactive "P")
10032 (let (org-time-was-given org-end-time-was-given time)
10033 (setq time (org-read-date arg 'totime))
10034 (org-insert-time-stamp time (or org-time-was-given arg) 'inactive
10035 nil nil (list org-end-time-was-given))))
10037 (defvar org-date-ovl (org-make-overlay 1 1))
10038 (org-overlay-put org-date-ovl 'face 'org-warning)
10039 (org-detach-overlay org-date-ovl)
10041 (defvar org-ans1) ; dynamically scoped parameter
10042 (defvar org-ans2) ; dynamically scoped parameter
10044 (defvar org-plain-time-of-day-regexp) ; defined below
10046 (defvar org-read-date-overlay nil)
10047 (defvar org-dcst nil) ; dynamically scoped
10049 (defun org-read-date (&optional with-time to-time from-string prompt
10050 default-time default-input)
10051 "Read a date, possibly a time, and make things smooth for the user.
10052 The prompt will suggest to enter an ISO date, but you can also enter anything
10053 which will at least partially be understood by `parse-time-string'.
10054 Unrecognized parts of the date will default to the current day, month, year,
10055 hour and minute. If this command is called to replace a timestamp at point,
10056 of to enter the second timestamp of a range, the default time is taken from the
10057 existing stamp. For example,
10058 3-2-5 --> 2003-02-05
10059 feb 15 --> currentyear-02-15
10060 sep 12 9 --> 2009-09-12
10061 12:45 --> today 12:45
10062 22 sept 0:34 --> currentyear-09-22 0:34
10063 12 --> currentyear-currentmonth-12
10064 Fri --> nearest Friday (today or later)
10065 etc.
10067 Furthermore you can specify a relative date by giving, as the *first* thing
10068 in the input: a plus/minus sign, a number and a letter [dwmy] to indicate
10069 change in days weeks, months, years.
10070 With a single plus or minus, the date is relative to today. With a double
10071 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
10072 +4d --> four days from today
10073 +4 --> same as above
10074 +2w --> two weeks from today
10075 ++5 --> five days from default date
10077 The function understands only English month and weekday abbreviations,
10078 but this can be configured with the variables `parse-time-months' and
10079 `parse-time-weekdays'.
10081 While prompting, a calendar is popped up - you can also select the
10082 date with the mouse (button 1). The calendar shows a period of three
10083 months. To scroll it to other months, use the keys `>' and `<'.
10084 If you don't like the calendar, turn it off with
10085 \(setq org-read-date-popup-calendar nil)
10087 With optional argument TO-TIME, the date will immediately be converted
10088 to an internal time.
10089 With an optional argument WITH-TIME, the prompt will suggest to also
10090 insert a time. Note that when WITH-TIME is not set, you can still
10091 enter a time, and this function will inform the calling routine about
10092 this change. The calling routine may then choose to change the format
10093 used to insert the time stamp into the buffer to include the time.
10094 With optional argument FROM-STRING, read from this string instead from
10095 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
10096 the time/date that is used for everything that is not specified by the
10097 user."
10098 (require 'parse-time)
10099 (let* ((org-time-stamp-rounding-minutes
10100 (if (equal with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
10101 (org-dcst org-display-custom-times)
10102 (ct (org-current-time))
10103 (def (or default-time ct))
10104 (defdecode (decode-time def))
10105 (dummy (progn
10106 (when (< (nth 2 defdecode) org-extend-today-until)
10107 (setcar (nthcdr 2 defdecode) -1)
10108 (setcar (nthcdr 1 defdecode) 59)
10109 (setq def (apply 'encode-time defdecode)
10110 defdecode (decode-time def)))))
10111 (calendar-move-hook nil)
10112 (calendar-view-diary-initially-flag nil)
10113 (view-diary-entries-initially nil)
10114 (calendar-view-holidays-initially-flag nil)
10115 (view-calendar-holidays-initially nil)
10116 (timestr (format-time-string
10117 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") def))
10118 (prompt (concat (if prompt (concat prompt " ") "")
10119 (format "Date+time [%s]: " timestr)))
10120 ans (org-ans0 "") org-ans1 org-ans2 final)
10122 (cond
10123 (from-string (setq ans from-string))
10124 (org-read-date-popup-calendar
10125 (save-excursion
10126 (save-window-excursion
10127 (calendar)
10128 (calendar-forward-day (- (time-to-days def)
10129 (calendar-absolute-from-gregorian
10130 (calendar-current-date))))
10131 (org-eval-in-calendar nil t)
10132 (let* ((old-map (current-local-map))
10133 (map (copy-keymap calendar-mode-map))
10134 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
10135 (org-defkey map (kbd "RET") 'org-calendar-select)
10136 (org-defkey map (if (featurep 'xemacs) [button1] [mouse-1])
10137 'org-calendar-select-mouse)
10138 (org-defkey map (if (featurep 'xemacs) [button2] [mouse-2])
10139 'org-calendar-select-mouse)
10140 (org-defkey minibuffer-local-map [(meta shift left)]
10141 (lambda () (interactive)
10142 (org-eval-in-calendar '(calendar-backward-month 1))))
10143 (org-defkey minibuffer-local-map [(meta shift right)]
10144 (lambda () (interactive)
10145 (org-eval-in-calendar '(calendar-forward-month 1))))
10146 (org-defkey minibuffer-local-map [(meta shift up)]
10147 (lambda () (interactive)
10148 (org-eval-in-calendar '(calendar-backward-year 1))))
10149 (org-defkey minibuffer-local-map [(meta shift down)]
10150 (lambda () (interactive)
10151 (org-eval-in-calendar '(calendar-forward-year 1))))
10152 (org-defkey minibuffer-local-map [(shift up)]
10153 (lambda () (interactive)
10154 (org-eval-in-calendar '(calendar-backward-week 1))))
10155 (org-defkey minibuffer-local-map [(shift down)]
10156 (lambda () (interactive)
10157 (org-eval-in-calendar '(calendar-forward-week 1))))
10158 (org-defkey minibuffer-local-map [(shift left)]
10159 (lambda () (interactive)
10160 (org-eval-in-calendar '(calendar-backward-day 1))))
10161 (org-defkey minibuffer-local-map [(shift right)]
10162 (lambda () (interactive)
10163 (org-eval-in-calendar '(calendar-forward-day 1))))
10164 (org-defkey minibuffer-local-map ">"
10165 (lambda () (interactive)
10166 (org-eval-in-calendar '(scroll-calendar-left 1))))
10167 (org-defkey minibuffer-local-map "<"
10168 (lambda () (interactive)
10169 (org-eval-in-calendar '(scroll-calendar-right 1))))
10170 (unwind-protect
10171 (progn
10172 (use-local-map map)
10173 (add-hook 'post-command-hook 'org-read-date-display)
10174 (setq org-ans0 (read-string prompt default-input nil nil))
10175 ;; org-ans0: from prompt
10176 ;; org-ans1: from mouse click
10177 ;; org-ans2: from calendar motion
10178 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
10179 (remove-hook 'post-command-hook 'org-read-date-display)
10180 (use-local-map old-map)
10181 (when org-read-date-overlay
10182 (org-delete-overlay org-read-date-overlay)
10183 (setq org-read-date-overlay nil)))))))
10185 (t ; Naked prompt only
10186 (unwind-protect
10187 (setq ans (read-string prompt default-input nil timestr))
10188 (when org-read-date-overlay
10189 (org-delete-overlay org-read-date-overlay)
10190 (setq org-read-date-overlay nil)))))
10192 (setq final (org-read-date-analyze ans def defdecode))
10194 (if to-time
10195 (apply 'encode-time final)
10196 (if (and (boundp 'org-time-was-given) org-time-was-given)
10197 (format "%04d-%02d-%02d %02d:%02d"
10198 (nth 5 final) (nth 4 final) (nth 3 final)
10199 (nth 2 final) (nth 1 final))
10200 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
10201 (defvar def)
10202 (defvar defdecode)
10203 (defvar with-time)
10204 (defun org-read-date-display ()
10205 "Display the currrent date prompt interpretation in the minibuffer."
10206 (when org-read-date-display-live
10207 (when org-read-date-overlay
10208 (org-delete-overlay org-read-date-overlay))
10209 (let ((p (point)))
10210 (end-of-line 1)
10211 (while (not (equal (buffer-substring
10212 (max (point-min) (- (point) 4)) (point))
10213 " "))
10214 (insert " "))
10215 (goto-char p))
10216 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
10217 " " (or org-ans1 org-ans2)))
10218 (org-end-time-was-given nil)
10219 (f (org-read-date-analyze ans def defdecode))
10220 (fmts (if org-dcst
10221 org-time-stamp-custom-formats
10222 org-time-stamp-formats))
10223 (fmt (if (or with-time
10224 (and (boundp 'org-time-was-given) org-time-was-given))
10225 (cdr fmts)
10226 (car fmts)))
10227 (txt (concat "=> " (format-time-string fmt (apply 'encode-time f)))))
10228 (when (and org-end-time-was-given
10229 (string-match org-plain-time-of-day-regexp txt))
10230 (setq txt (concat (substring txt 0 (match-end 0)) "-"
10231 org-end-time-was-given
10232 (substring txt (match-end 0)))))
10233 (setq org-read-date-overlay
10234 (make-overlay (1- (point-at-eol)) (point-at-eol)))
10235 (org-overlay-display org-read-date-overlay txt 'secondary-selection))))
10237 (defun org-read-date-analyze (ans def defdecode)
10238 "Analyze the combined answer of the date prompt."
10239 ;; FIXME: cleanup and comment
10240 (let (delta deltan deltaw deltadef year month day
10241 hour minute second wday pm h2 m2 tl wday1
10242 iso-year iso-weekday iso-week iso-year iso-date)
10244 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
10245 (setq ans "+0"))
10247 (when (setq delta (org-read-date-get-relative ans (current-time) def))
10248 (setq ans (replace-match "" t t ans)
10249 deltan (car delta)
10250 deltaw (nth 1 delta)
10251 deltadef (nth 2 delta)))
10253 ;; Check if there is an iso week date in there
10254 ;; If yes, sore the info and ostpone interpreting it until the rest
10255 ;; of the parsing is done
10256 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
10257 (setq iso-year (if (match-end 1) (org-small-year-to-year (string-to-number (match-string 1 ans))))
10258 iso-weekday (if (match-end 3) (string-to-number (match-string 3 ans)))
10259 iso-week (string-to-number (match-string 2 ans)))
10260 (setq ans (replace-match "" t t ans)))
10262 ;; Help matching ISO dates with single digit month ot day, like 2006-8-11.
10263 (when (string-match
10264 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
10265 (setq year (if (match-end 2)
10266 (string-to-number (match-string 2 ans))
10267 (string-to-number (format-time-string "%Y")))
10268 month (string-to-number (match-string 3 ans))
10269 day (string-to-number (match-string 4 ans)))
10270 (if (< year 100) (setq year (+ 2000 year)))
10271 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
10272 t nil ans)))
10273 ;; Help matching am/pm times, because `parse-time-string' does not do that.
10274 ;; If there is a time with am/pm, and *no* time without it, we convert
10275 ;; so that matching will be successful.
10276 (loop for i from 1 to 2 do ; twice, for end time as well
10277 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
10278 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
10279 (setq hour (string-to-number (match-string 1 ans))
10280 minute (if (match-end 3)
10281 (string-to-number (match-string 3 ans))
10283 pm (equal ?p
10284 (string-to-char (downcase (match-string 4 ans)))))
10285 (if (and (= hour 12) (not pm))
10286 (setq hour 0)
10287 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
10288 (setq ans (replace-match (format "%02d:%02d" hour minute)
10289 t t ans))))
10291 ;; Check if a time range is given as a duration
10292 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
10293 (setq hour (string-to-number (match-string 1 ans))
10294 h2 (+ hour (string-to-number (match-string 3 ans)))
10295 minute (string-to-number (match-string 2 ans))
10296 m2 (+ minute (if (match-end 5) (string-to-number
10297 (match-string 5 ans))0)))
10298 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
10299 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
10300 t t ans)))
10302 ;; Check if there is a time range
10303 (when (boundp 'org-end-time-was-given)
10304 (setq org-time-was-given nil)
10305 (when (and (string-match org-plain-time-of-day-regexp ans)
10306 (match-end 8))
10307 (setq org-end-time-was-given (match-string 8 ans))
10308 (setq ans (concat (substring ans 0 (match-beginning 7))
10309 (substring ans (match-end 7))))))
10311 (setq tl (parse-time-string ans)
10312 day (or (nth 3 tl) (nth 3 defdecode))
10313 month (or (nth 4 tl)
10314 (if (and org-read-date-prefer-future
10315 (nth 3 tl) (< (nth 3 tl) (nth 3 defdecode)))
10316 (1+ (nth 4 defdecode))
10317 (nth 4 defdecode)))
10318 year (or (nth 5 tl)
10319 (if (and org-read-date-prefer-future
10320 (nth 4 tl) (< (nth 4 tl) (nth 4 defdecode)))
10321 (1+ (nth 5 defdecode))
10322 (nth 5 defdecode)))
10323 hour (or (nth 2 tl) (nth 2 defdecode))
10324 minute (or (nth 1 tl) (nth 1 defdecode))
10325 second (or (nth 0 tl) 0)
10326 wday (nth 6 tl))
10328 ;; Special date definitions below
10329 (cond
10330 (iso-week
10331 ;; There was an iso week
10332 (setq year (or iso-year year)
10333 day (or iso-weekday wday 1)
10334 wday nil ; to make sure that the trigger below does not match
10335 iso-date (calendar-gregorian-from-absolute
10336 (calendar-absolute-from-iso
10337 (list iso-week day year))))
10338 ; FIXME: Should we also push ISO weeks into the future?
10339 ; (when (and org-read-date-prefer-future
10340 ; (not iso-year)
10341 ; (< (calendar-absolute-from-gregorian iso-date)
10342 ; (time-to-days (current-time))))
10343 ; (setq year (1+ year)
10344 ; iso-date (calendar-gregorian-from-absolute
10345 ; (calendar-absolute-from-iso
10346 ; (list iso-week day year)))))
10347 (setq month (car iso-date)
10348 year (nth 2 iso-date)
10349 day (nth 1 iso-date)))
10350 (deltan
10351 (unless deltadef
10352 (let ((now (decode-time (current-time))))
10353 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
10354 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
10355 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
10356 ((equal deltaw "m") (setq month (+ month deltan)))
10357 ((equal deltaw "y") (setq year (+ year deltan)))))
10358 ((and wday (not (nth 3 tl)))
10359 ;; Weekday was given, but no day, so pick that day in the week
10360 ;; on or after the derived date.
10361 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
10362 (unless (equal wday wday1)
10363 (setq day (+ day (% (- wday wday1 -7) 7))))))
10364 (if (and (boundp 'org-time-was-given)
10365 (nth 2 tl))
10366 (setq org-time-was-given t))
10367 (if (< year 100) (setq year (+ 2000 year)))
10368 (if (< year 1970) (setq year (nth 5 defdecode))) ; not representable
10369 (list second minute hour day month year)))
10371 (defvar parse-time-weekdays)
10373 (defun org-read-date-get-relative (s today default)
10374 "Check string S for special relative date string.
10375 TODAY and DEFAULT are internal times, for today and for a default.
10376 Return shift list (N what def-flag)
10377 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
10378 N is the number of WHATs to shift.
10379 DEF-FLAG is t when a double ++ or -- indicates shift relative to
10380 the DEFAULT date rather than TODAY."
10381 (when (string-match
10382 (concat
10383 "\\`[ \t]*\\([-+]\\{1,2\\}\\)"
10384 "\\([0-9]+\\)?"
10385 "\\([dwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
10386 "\\([ \t]\\|$\\)") s)
10387 (let* ((dir (if (match-end 1)
10388 (string-to-char (substring (match-string 1 s) -1))
10389 ?+))
10390 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
10391 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
10392 (what (if (match-end 3) (match-string 3 s) "d"))
10393 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
10394 (date (if rel default today))
10395 (wday (nth 6 (decode-time date)))
10396 delta)
10397 (if wday1
10398 (progn
10399 (setq delta (mod (+ 7 (- wday1 wday)) 7))
10400 (if (= dir ?-) (setq delta (- delta 7)))
10401 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
10402 (list delta "d" rel))
10403 (list (* n (if (= dir ?-) -1 1)) what rel)))))
10405 (defun org-eval-in-calendar (form &optional keepdate)
10406 "Eval FORM in the calendar window and return to current window.
10407 Also, store the cursor date in variable org-ans2."
10408 (let ((sw (selected-window)))
10409 (select-window (get-buffer-window "*Calendar*"))
10410 (eval form)
10411 (when (and (not keepdate) (calendar-cursor-to-date))
10412 (let* ((date (calendar-cursor-to-date))
10413 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
10414 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
10415 (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
10416 (select-window sw)))
10418 ; ;; Update the prompt to show new default date
10419 ; (save-excursion
10420 ; (goto-char (point-min))
10421 ; (when (and org-ans2
10422 ; (re-search-forward "\\[[-0-9]+\\]" nil t)
10423 ; (get-text-property (match-end 0) 'field))
10424 ; (let ((inhibit-read-only t))
10425 ; (replace-match (concat "[" org-ans2 "]") t t)
10426 ; (add-text-properties (point-min) (1+ (match-end 0))
10427 ; (text-properties-at (1+ (point-min)))))))))
10429 (defun org-calendar-select ()
10430 "Return to `org-read-date' with the date currently selected.
10431 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
10432 (interactive)
10433 (when (calendar-cursor-to-date)
10434 (let* ((date (calendar-cursor-to-date))
10435 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
10436 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
10437 (if (active-minibuffer-window) (exit-minibuffer))))
10439 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
10440 "Insert a date stamp for the date given by the internal TIME.
10441 WITH-HM means, use the stamp format that includes the time of the day.
10442 INACTIVE means use square brackets instead of angular ones, so that the
10443 stamp will not contribute to the agenda.
10444 PRE and POST are optional strings to be inserted before and after the
10445 stamp.
10446 The command returns the inserted time stamp."
10447 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
10448 stamp)
10449 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
10450 (insert-before-markers (or pre ""))
10451 (insert-before-markers (setq stamp (format-time-string fmt time)))
10452 (when (listp extra)
10453 (setq extra (car extra))
10454 (if (and (stringp extra)
10455 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
10456 (setq extra (format "-%02d:%02d"
10457 (string-to-number (match-string 1 extra))
10458 (string-to-number (match-string 2 extra))))
10459 (setq extra nil)))
10460 (when extra
10461 (backward-char 1)
10462 (insert-before-markers extra)
10463 (forward-char 1))
10464 (insert-before-markers (or post ""))
10465 stamp))
10467 (defun org-toggle-time-stamp-overlays ()
10468 "Toggle the use of custom time stamp formats."
10469 (interactive)
10470 (setq org-display-custom-times (not org-display-custom-times))
10471 (unless org-display-custom-times
10472 (let ((p (point-min)) (bmp (buffer-modified-p)))
10473 (while (setq p (next-single-property-change p 'display))
10474 (if (and (get-text-property p 'display)
10475 (eq (get-text-property p 'face) 'org-date))
10476 (remove-text-properties
10477 p (setq p (next-single-property-change p 'display))
10478 '(display t))))
10479 (set-buffer-modified-p bmp)))
10480 (if (featurep 'xemacs)
10481 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
10482 (org-restart-font-lock)
10483 (setq org-table-may-need-update t)
10484 (if org-display-custom-times
10485 (message "Time stamps are overlayed with custom format")
10486 (message "Time stamp overlays removed")))
10488 (defun org-display-custom-time (beg end)
10489 "Overlay modified time stamp format over timestamp between BEG and END."
10490 (let* ((ts (buffer-substring beg end))
10491 t1 w1 with-hm tf time str w2 (off 0))
10492 (save-match-data
10493 (setq t1 (org-parse-time-string ts t))
10494 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[dwmy]\\)?\\'" ts)
10495 (setq off (- (match-end 0) (match-beginning 0)))))
10496 (setq end (- end off))
10497 (setq w1 (- end beg)
10498 with-hm (and (nth 1 t1) (nth 2 t1))
10499 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
10500 time (org-fix-decoded-time t1)
10501 str (org-add-props
10502 (format-time-string
10503 (substring tf 1 -1) (apply 'encode-time time))
10504 nil 'mouse-face 'highlight)
10505 w2 (length str))
10506 (if (not (= w2 w1))
10507 (add-text-properties (1+ beg) (+ 2 beg)
10508 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
10509 (if (featurep 'xemacs)
10510 (progn
10511 (put-text-property beg end 'invisible t)
10512 (put-text-property beg end 'end-glyph (make-glyph str)))
10513 (put-text-property beg end 'display str))))
10515 (defun org-translate-time (string)
10516 "Translate all timestamps in STRING to custom format.
10517 But do this only if the variable `org-display-custom-times' is set."
10518 (when org-display-custom-times
10519 (save-match-data
10520 (let* ((start 0)
10521 (re org-ts-regexp-both)
10522 t1 with-hm inactive tf time str beg end)
10523 (while (setq start (string-match re string start))
10524 (setq beg (match-beginning 0)
10525 end (match-end 0)
10526 t1 (save-match-data
10527 (org-parse-time-string (substring string beg end) t))
10528 with-hm (and (nth 1 t1) (nth 2 t1))
10529 inactive (equal (substring string beg (1+ beg)) "[")
10530 tf (funcall (if with-hm 'cdr 'car)
10531 org-time-stamp-custom-formats)
10532 time (org-fix-decoded-time t1)
10533 str (format-time-string
10534 (concat
10535 (if inactive "[" "<") (substring tf 1 -1)
10536 (if inactive "]" ">"))
10537 (apply 'encode-time time))
10538 string (replace-match str t t string)
10539 start (+ start (length str)))))))
10540 string)
10542 (defun org-fix-decoded-time (time)
10543 "Set 0 instead of nil for the first 6 elements of time.
10544 Don't touch the rest."
10545 (let ((n 0))
10546 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
10548 (defun org-days-to-time (timestamp-string)
10549 "Difference between TIMESTAMP-STRING and now in days."
10550 (- (time-to-days (org-time-string-to-time timestamp-string))
10551 (time-to-days (current-time))))
10553 (defun org-deadline-close (timestamp-string &optional ndays)
10554 "Is the time in TIMESTAMP-STRING close to the current date?"
10555 (setq ndays (or ndays (org-get-wdays timestamp-string)))
10556 (and (< (org-days-to-time timestamp-string) ndays)
10557 (not (org-entry-is-done-p))))
10559 (defun org-get-wdays (ts)
10560 "Get the deadline lead time appropriate for timestring TS."
10561 (cond
10562 ((<= org-deadline-warning-days 0)
10563 ;; 0 or negative, enforce this value no matter what
10564 (- org-deadline-warning-days))
10565 ((string-match "-\\([0-9]+\\)\\([dwmy]\\)\\(\\'\\|>\\)" ts)
10566 ;; lead time is specified.
10567 (floor (* (string-to-number (match-string 1 ts))
10568 (cdr (assoc (match-string 2 ts)
10569 '(("d" . 1) ("w" . 7)
10570 ("m" . 30.4) ("y" . 365.25)))))))
10571 ;; go for the default.
10572 (t org-deadline-warning-days)))
10574 (defun org-calendar-select-mouse (ev)
10575 "Return to `org-read-date' with the date currently selected.
10576 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
10577 (interactive "e")
10578 (mouse-set-point ev)
10579 (when (calendar-cursor-to-date)
10580 (let* ((date (calendar-cursor-to-date))
10581 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
10582 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
10583 (if (active-minibuffer-window) (exit-minibuffer))))
10585 (defun org-check-deadlines (ndays)
10586 "Check if there are any deadlines due or past due.
10587 A deadline is considered due if it happens within `org-deadline-warning-days'
10588 days from today's date. If the deadline appears in an entry marked DONE,
10589 it is not shown. The prefix arg NDAYS can be used to test that many
10590 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
10591 (interactive "P")
10592 (let* ((org-warn-days
10593 (cond
10594 ((equal ndays '(4)) 100000)
10595 (ndays (prefix-numeric-value ndays))
10596 (t (abs org-deadline-warning-days))))
10597 (case-fold-search nil)
10598 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
10599 (callback
10600 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
10602 (message "%d deadlines past-due or due within %d days"
10603 (org-occur regexp nil callback)
10604 org-warn-days)))
10606 (defun org-check-before-date (date)
10607 "Check if there are deadlines or scheduled entries before DATE."
10608 (interactive (list (org-read-date)))
10609 (let ((case-fold-search nil)
10610 (regexp (concat "\\<\\(" org-deadline-string
10611 "\\|" org-scheduled-string
10612 "\\) *<\\([^>]+\\)>"))
10613 (callback
10614 (lambda () (time-less-p
10615 (org-time-string-to-time (match-string 2))
10616 (org-time-string-to-time date)))))
10617 (message "%d entries before %s"
10618 (org-occur regexp nil callback) date)))
10620 (defun org-evaluate-time-range (&optional to-buffer)
10621 "Evaluate a time range by computing the difference between start and end.
10622 Normally the result is just printed in the echo area, but with prefix arg
10623 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
10624 If the time range is actually in a table, the result is inserted into the
10625 next column.
10626 For time difference computation, a year is assumed to be exactly 365
10627 days in order to avoid rounding problems."
10628 (interactive "P")
10630 (org-clock-update-time-maybe)
10631 (save-excursion
10632 (unless (org-at-date-range-p t)
10633 (goto-char (point-at-bol))
10634 (re-search-forward org-tr-regexp-both (point-at-eol) t))
10635 (if (not (org-at-date-range-p t))
10636 (error "Not at a time-stamp range, and none found in current line")))
10637 (let* ((ts1 (match-string 1))
10638 (ts2 (match-string 2))
10639 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
10640 (match-end (match-end 0))
10641 (time1 (org-time-string-to-time ts1))
10642 (time2 (org-time-string-to-time ts2))
10643 (t1 (time-to-seconds time1))
10644 (t2 (time-to-seconds time2))
10645 (diff (abs (- t2 t1)))
10646 (negative (< (- t2 t1) 0))
10647 ;; (ys (floor (* 365 24 60 60)))
10648 (ds (* 24 60 60))
10649 (hs (* 60 60))
10650 (fy "%dy %dd %02d:%02d")
10651 (fy1 "%dy %dd")
10652 (fd "%dd %02d:%02d")
10653 (fd1 "%dd")
10654 (fh "%02d:%02d")
10655 y d h m align)
10656 (if havetime
10657 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
10659 d (floor (/ diff ds)) diff (mod diff ds)
10660 h (floor (/ diff hs)) diff (mod diff hs)
10661 m (floor (/ diff 60)))
10662 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
10664 d (floor (+ (/ diff ds) 0.5))
10665 h 0 m 0))
10666 (if (not to-buffer)
10667 (message "%s" (org-make-tdiff-string y d h m))
10668 (if (org-at-table-p)
10669 (progn
10670 (goto-char match-end)
10671 (setq align t)
10672 (and (looking-at " *|") (goto-char (match-end 0))))
10673 (goto-char match-end))
10674 (if (looking-at
10675 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
10676 (replace-match ""))
10677 (if negative (insert " -"))
10678 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
10679 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
10680 (insert " " (format fh h m))))
10681 (if align (org-table-align))
10682 (message "Time difference inserted")))))
10684 (defun org-make-tdiff-string (y d h m)
10685 (let ((fmt "")
10686 (l nil))
10687 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
10688 l (push y l)))
10689 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
10690 l (push d l)))
10691 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
10692 l (push h l)))
10693 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
10694 l (push m l)))
10695 (apply 'format fmt (nreverse l))))
10697 (defun org-time-string-to-time (s)
10698 (apply 'encode-time (org-parse-time-string s)))
10700 (defun org-time-string-to-absolute (s &optional daynr prefer show-all)
10701 "Convert a time stamp to an absolute day number.
10702 If there is a specifyer for a cyclic time stamp, get the closest date to
10703 DAYNR.
10704 PREFER and SHOW_ALL are passed through to `org-closest-date'."
10705 (cond
10706 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
10707 (if (org-diary-sexp-entry (match-string 1 s) "" date)
10708 daynr
10709 (+ daynr 1000)))
10710 ((and daynr (string-match "\\+[0-9]+[dwmy]" s))
10711 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
10712 (time-to-days (current-time))) (match-string 0 s)
10713 prefer show-all))
10714 (t (time-to-days (apply 'encode-time (org-parse-time-string s))))))
10716 (defun org-days-to-iso-week (days)
10717 "Return the iso week number."
10718 (require 'cal-iso)
10719 (car (calendar-iso-from-absolute days)))
10721 (defun org-small-year-to-year (year)
10722 "Convert 2-digit years into 4-digit years.
10723 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
10724 The year 2000 cannot be abbreviated. Any year lager than 99
10725 is retrned unchanged."
10726 (if (< year 38)
10727 (setq year (+ 2000 year))
10728 (if (< year 100)
10729 (setq year (+ 1900 year))))
10730 year)
10732 (defun org-time-from-absolute (d)
10733 "Return the time corresponding to date D.
10734 D may be an absolute day number, or a calendar-type list (month day year)."
10735 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
10736 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
10738 (defun org-calendar-holiday ()
10739 "List of holidays, for Diary display in Org-mode."
10740 (require 'holidays)
10741 (let ((hl (funcall
10742 (if (fboundp 'calendar-check-holidays)
10743 'calendar-check-holidays 'check-calendar-holidays) date)))
10744 (if hl (mapconcat 'identity hl "; "))))
10746 (defun org-diary-sexp-entry (sexp entry date)
10747 "Process a SEXP diary ENTRY for DATE."
10748 (require 'diary-lib)
10749 (let ((result (if calendar-debug-sexp
10750 (let ((stack-trace-on-error t))
10751 (eval (car (read-from-string sexp))))
10752 (condition-case nil
10753 (eval (car (read-from-string sexp)))
10754 (error
10755 (beep)
10756 (message "Bad sexp at line %d in %s: %s"
10757 (org-current-line)
10758 (buffer-file-name) sexp)
10759 (sleep-for 2))))))
10760 (cond ((stringp result) result)
10761 ((and (consp result)
10762 (stringp (cdr result))) (cdr result))
10763 (result entry)
10764 (t nil))))
10766 (defun org-diary-to-ical-string (frombuf)
10767 "Get iCalendar entries from diary entries in buffer FROMBUF.
10768 This uses the icalendar.el library."
10769 (let* ((tmpdir (if (featurep 'xemacs)
10770 (temp-directory)
10771 temporary-file-directory))
10772 (tmpfile (make-temp-name
10773 (expand-file-name "orgics" tmpdir)))
10774 buf rtn b e)
10775 (save-excursion
10776 (set-buffer frombuf)
10777 (icalendar-export-region (point-min) (point-max) tmpfile)
10778 (setq buf (find-buffer-visiting tmpfile))
10779 (set-buffer buf)
10780 (goto-char (point-min))
10781 (if (re-search-forward "^BEGIN:VEVENT" nil t)
10782 (setq b (match-beginning 0)))
10783 (goto-char (point-max))
10784 (if (re-search-backward "^END:VEVENT" nil t)
10785 (setq e (match-end 0)))
10786 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
10787 (kill-buffer buf)
10788 (kill-buffer frombuf)
10789 (delete-file tmpfile)
10790 rtn))
10792 (defun org-closest-date (start current change prefer show-all)
10793 "Find the date closest to CURRENT that is consistent with START and CHANGE.
10794 When PREFER is `past' return a date that is either CURRENT or past.
10795 When PREFER is `future', return a date that is either CURRENT or future.
10796 When SHOW-ALL is nil, only return the current occurence of a time stamp."
10797 ;; Make the proper lists from the dates
10798 (catch 'exit
10799 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
10800 dn dw sday cday n1 n2
10801 d m y y1 y2 date1 date2 nmonths nm ny m2)
10803 (setq start (org-date-to-gregorian start)
10804 current (org-date-to-gregorian
10805 (if show-all
10806 current
10807 (time-to-days (current-time))))
10808 sday (calendar-absolute-from-gregorian start)
10809 cday (calendar-absolute-from-gregorian current))
10811 (if (<= cday sday) (throw 'exit sday))
10813 (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
10814 (setq dn (string-to-number (match-string 1 change))
10815 dw (cdr (assoc (match-string 2 change) a1)))
10816 (error "Invalid change specifyer: %s" change))
10817 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
10818 (cond
10819 ((eq dw 'day)
10820 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
10821 n2 (+ n1 dn)))
10822 ((eq dw 'year)
10823 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
10824 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
10825 (setq date1 (list m d y1)
10826 n1 (calendar-absolute-from-gregorian date1)
10827 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
10828 n2 (calendar-absolute-from-gregorian date2)))
10829 ((eq dw 'month)
10830 ;; approx number of month between the tow dates
10831 (setq nmonths (floor (/ (- cday sday) 30.436875)))
10832 ;; How often does dn fit in there?
10833 (setq d (nth 1 start) m (car start) y (nth 2 start)
10834 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
10835 m (+ m nm)
10836 ny (floor (/ m 12))
10837 y (+ y ny)
10838 m (- m (* ny 12)))
10839 (while (> m 12) (setq m (- m 12) y (1+ y)))
10840 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
10841 (setq m2 (+ m dn) y2 y)
10842 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
10843 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
10844 (while (< n2 cday)
10845 (setq n1 n2 m m2 y y2)
10846 (setq m2 (+ m dn) y2 y)
10847 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
10848 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
10850 (if show-all
10851 (cond
10852 ((eq prefer 'past) n1)
10853 ((eq prefer 'future) (if (= cday n1) n1 n2))
10854 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
10855 (cond
10856 ((eq prefer 'past) n1)
10857 ((eq prefer 'future) (if (= cday n1) n1 n2))
10858 (t (if (= cday n1) n1 n2)))))))
10860 (defun org-date-to-gregorian (date)
10861 "Turn any specification of DATE into a gregorian date for the calendar."
10862 (cond ((integerp date) (calendar-gregorian-from-absolute date))
10863 ((and (listp date) (= (length date) 3)) date)
10864 ((stringp date)
10865 (setq date (org-parse-time-string date))
10866 (list (nth 4 date) (nth 3 date) (nth 5 date)))
10867 ((listp date)
10868 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
10870 (defun org-parse-time-string (s &optional nodefault)
10871 "Parse the standard Org-mode time string.
10872 This should be a lot faster than the normal `parse-time-string'.
10873 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
10874 hour and minute fields will be nil if not given."
10875 (if (string-match org-ts-regexp0 s)
10876 (list 0
10877 (if (or (match-beginning 8) (not nodefault))
10878 (string-to-number (or (match-string 8 s) "0")))
10879 (if (or (match-beginning 7) (not nodefault))
10880 (string-to-number (or (match-string 7 s) "0")))
10881 (string-to-number (match-string 4 s))
10882 (string-to-number (match-string 3 s))
10883 (string-to-number (match-string 2 s))
10884 nil nil nil)
10885 (make-list 9 0)))
10887 (defun org-timestamp-up (&optional arg)
10888 "Increase the date item at the cursor by one.
10889 If the cursor is on the year, change the year. If it is on the month or
10890 the day, change that.
10891 With prefix ARG, change by that many units."
10892 (interactive "p")
10893 (org-timestamp-change (prefix-numeric-value arg)))
10895 (defun org-timestamp-down (&optional arg)
10896 "Decrease the date item at the cursor by one.
10897 If the cursor is on the year, change the year. If it is on the month or
10898 the day, change that.
10899 With prefix ARG, change by that many units."
10900 (interactive "p")
10901 (org-timestamp-change (- (prefix-numeric-value arg))))
10903 (defun org-timestamp-up-day (&optional arg)
10904 "Increase the date in the time stamp by one day.
10905 With prefix ARG, change that many days."
10906 (interactive "p")
10907 (if (and (not (org-at-timestamp-p t))
10908 (org-on-heading-p))
10909 (org-todo 'up)
10910 (org-timestamp-change (prefix-numeric-value arg) 'day)))
10912 (defun org-timestamp-down-day (&optional arg)
10913 "Decrease the date in the time stamp by one day.
10914 With prefix ARG, change that many days."
10915 (interactive "p")
10916 (if (and (not (org-at-timestamp-p t))
10917 (org-on-heading-p))
10918 (org-todo 'down)
10919 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
10921 (defun org-at-timestamp-p (&optional inactive-ok)
10922 "Determine if the cursor is in or at a timestamp."
10923 (interactive)
10924 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
10925 (pos (point))
10926 (ans (or (looking-at tsr)
10927 (save-excursion
10928 (skip-chars-backward "^[<\n\r\t")
10929 (if (> (point) (point-min)) (backward-char 1))
10930 (and (looking-at tsr)
10931 (> (- (match-end 0) pos) -1))))))
10932 (and ans
10933 (boundp 'org-ts-what)
10934 (setq org-ts-what
10935 (cond
10936 ((= pos (match-beginning 0)) 'bracket)
10937 ((= pos (1- (match-end 0))) 'bracket)
10938 ((org-pos-in-match-range pos 2) 'year)
10939 ((org-pos-in-match-range pos 3) 'month)
10940 ((org-pos-in-match-range pos 7) 'hour)
10941 ((org-pos-in-match-range pos 8) 'minute)
10942 ((or (org-pos-in-match-range pos 4)
10943 (org-pos-in-match-range pos 5)) 'day)
10944 ((and (> pos (or (match-end 8) (match-end 5)))
10945 (< pos (match-end 0)))
10946 (- pos (or (match-end 8) (match-end 5))))
10947 (t 'day))))
10948 ans))
10950 (defun org-toggle-timestamp-type ()
10951 "Toggle the type (<active> or [inactive]) of a time stamp."
10952 (interactive)
10953 (when (org-at-timestamp-p t)
10954 (save-excursion
10955 (goto-char (match-beginning 0))
10956 (insert (if (equal (char-after) ?<) "[" "<")) (delete-char 1)
10957 (goto-char (1- (match-end 0)))
10958 (insert (if (equal (char-after) ?>) "]" ">")) (delete-char 1))
10959 (message "Timestamp is now %sactive"
10960 (if (equal (char-before) ?>) "in" ""))))
10962 (defun org-timestamp-change (n &optional what)
10963 "Change the date in the time stamp at point.
10964 The date will be changed by N times WHAT. WHAT can be `day', `month',
10965 `year', `minute', `second'. If WHAT is not given, the cursor position
10966 in the timestamp determines what will be changed."
10967 (let ((pos (point))
10968 with-hm inactive
10969 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
10970 org-ts-what
10971 extra rem
10972 ts time time0)
10973 (if (not (org-at-timestamp-p t))
10974 (error "Not at a timestamp"))
10975 (if (and (not what) (eq org-ts-what 'bracket))
10976 (org-toggle-timestamp-type)
10977 (if (and (not what) (not (eq org-ts-what 'day))
10978 org-display-custom-times
10979 (get-text-property (point) 'display)
10980 (not (get-text-property (1- (point)) 'display)))
10981 (setq org-ts-what 'day))
10982 (setq org-ts-what (or what org-ts-what)
10983 inactive (= (char-after (match-beginning 0)) ?\[)
10984 ts (match-string 0))
10985 (replace-match "")
10986 (if (string-match
10987 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[dwmy]\\)*\\)[]>]"
10989 (setq extra (match-string 1 ts)))
10990 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
10991 (setq with-hm t))
10992 (setq time0 (org-parse-time-string ts))
10993 (when (and (eq org-ts-what 'minute)
10994 (eq current-prefix-arg nil))
10995 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
10996 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
10997 (setcar (cdr time0) (+ (nth 1 time0)
10998 (if (> n 0) (- rem) (- dm rem))))))
10999 (setq time
11000 (encode-time (or (car time0) 0)
11001 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
11002 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
11003 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
11004 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
11005 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
11006 (nthcdr 6 time0)))
11007 (when (integerp org-ts-what)
11008 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
11009 (if (eq what 'calendar)
11010 (let ((cal-date (org-get-date-from-calendar)))
11011 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
11012 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
11013 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
11014 (setcar time0 (or (car time0) 0))
11015 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
11016 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
11017 (setq time (apply 'encode-time time0))))
11018 (setq org-last-changed-timestamp
11019 (org-insert-time-stamp time with-hm inactive nil nil extra))
11020 (org-clock-update-time-maybe)
11021 (goto-char pos)
11022 ;; Try to recenter the calendar window, if any
11023 (if (and org-calendar-follow-timestamp-change
11024 (get-buffer-window "*Calendar*" t)
11025 (memq org-ts-what '(day month year)))
11026 (org-recenter-calendar (time-to-days time))))))
11028 (defun org-modify-ts-extra (s pos n dm)
11029 "Change the different parts of the lead-time and repeat fields in timestamp."
11030 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
11031 ng h m new rem)
11032 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
11033 (cond
11034 ((or (org-pos-in-match-range pos 2)
11035 (org-pos-in-match-range pos 3))
11036 (setq m (string-to-number (match-string 3 s))
11037 h (string-to-number (match-string 2 s)))
11038 (if (org-pos-in-match-range pos 2)
11039 (setq h (+ h n))
11040 (setq n (* dm (org-no-warnings (signum n))))
11041 (when (not (= 0 (setq rem (% m dm))))
11042 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
11043 (setq m (+ m n)))
11044 (if (< m 0) (setq m (+ m 60) h (1- h)))
11045 (if (> m 59) (setq m (- m 60) h (1+ h)))
11046 (setq h (min 24 (max 0 h)))
11047 (setq ng 1 new (format "-%02d:%02d" h m)))
11048 ((org-pos-in-match-range pos 6)
11049 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
11050 ((org-pos-in-match-range pos 5)
11051 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
11053 ((org-pos-in-match-range pos 9)
11054 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
11055 ((org-pos-in-match-range pos 8)
11056 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
11058 (when ng
11059 (setq s (concat
11060 (substring s 0 (match-beginning ng))
11062 (substring s (match-end ng))))))
11065 (defun org-recenter-calendar (date)
11066 "If the calendar is visible, recenter it to DATE."
11067 (let* ((win (selected-window))
11068 (cwin (get-buffer-window "*Calendar*" t))
11069 (calendar-move-hook nil))
11070 (when cwin
11071 (select-window cwin)
11072 (calendar-goto-date (if (listp date) date
11073 (calendar-gregorian-from-absolute date)))
11074 (select-window win))))
11076 (defun org-goto-calendar (&optional arg)
11077 "Go to the Emacs calendar at the current date.
11078 If there is a time stamp in the current line, go to that date.
11079 A prefix ARG can be used to force the current date."
11080 (interactive "P")
11081 (let ((tsr org-ts-regexp) diff
11082 (calendar-move-hook nil)
11083 (calendar-view-holidays-initially-flag nil)
11084 (view-calendar-holidays-initially nil)
11085 (calendar-view-diary-initially-flag nil)
11086 (view-diary-entries-initially nil))
11087 (if (or (org-at-timestamp-p)
11088 (save-excursion
11089 (beginning-of-line 1)
11090 (looking-at (concat ".*" tsr))))
11091 (let ((d1 (time-to-days (current-time)))
11092 (d2 (time-to-days
11093 (org-time-string-to-time (match-string 1)))))
11094 (setq diff (- d2 d1))))
11095 (calendar)
11096 (calendar-goto-today)
11097 (if (and diff (not arg)) (calendar-forward-day diff))))
11099 (defun org-get-date-from-calendar ()
11100 "Return a list (month day year) of date at point in calendar."
11101 (with-current-buffer "*Calendar*"
11102 (save-match-data
11103 (calendar-cursor-to-date))))
11105 (defun org-date-from-calendar ()
11106 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
11107 If there is already a time stamp at the cursor position, update it."
11108 (interactive)
11109 (if (org-at-timestamp-p t)
11110 (org-timestamp-change 0 'calendar)
11111 (let ((cal-date (org-get-date-from-calendar)))
11112 (org-insert-time-stamp
11113 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
11115 (defun org-minutes-to-hh:mm-string (m)
11116 "Compute H:MM from a number of minutes."
11117 (let ((h (/ m 60)))
11118 (setq m (- m (* 60 h)))
11119 (format "%d:%02d" h m)))
11121 (defun org-hh:mm-string-to-minutes (s)
11122 "Convert a string H:MM to a number of minutes."
11123 (if (string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
11124 (+ (* (string-to-number (match-string 1 s)) 60)
11125 (string-to-number (match-string 2 s)))
11128 ;;;; Agenda files
11130 ;;;###autoload
11131 (defun org-iswitchb (&optional arg)
11132 "Use `iswitchb-read-buffer' to prompt for an Org buffer to switch to.
11133 With a prefix argument, restrict available to files.
11134 With two prefix arguments, restrict available buffers to agenda files.
11136 Due to some yet unresolved reason, global function
11137 `iswitchb-mode' needs to be active for this function to work."
11138 (interactive "P")
11139 (require 'iswitchb)
11140 (let ((enabled iswitchb-mode) blist)
11141 (or enabled (iswitchb-mode 1))
11142 (setq blist (cond ((equal arg '(4)) (org-buffer-list 'files))
11143 ((equal arg '(16)) (org-buffer-list 'agenda))
11144 (t (org-buffer-list))))
11145 (unwind-protect
11146 (let ((iswitchb-make-buflist-hook
11147 (lambda ()
11148 (setq iswitchb-temp-buflist
11149 (mapcar 'buffer-name blist)))))
11150 (switch-to-buffer
11151 (iswitchb-read-buffer
11152 "Switch-to: " nil t))
11153 (or enabled (iswitchb-mode -1))))))
11155 (defun org-buffer-list (&optional predicate tmp)
11156 "Return a list of Org buffers.
11157 PREDICATE can be either 'export, 'files or 'agenda.
11159 'export restrict the list to Export buffers.
11160 'files restrict the list to buffers visiting Org files.
11161 'agenda restrict the list to buffers visiting agenda files.
11163 If TMP is non-nil, don't include temporary buffers."
11164 (let (filter blist)
11165 (setq filter
11166 (cond ((eq predicate 'files) "\.org$")
11167 ((eq predicate 'export) "\*Org .*Export")
11168 (t "\*Org \\|\.org$")))
11169 (setq blist
11170 (mapcar
11171 (lambda(b)
11172 (let ((bname (buffer-name b))
11173 (bfile (buffer-file-name b)))
11174 (if (and (string-match filter bname)
11175 (if (eq predicate 'agenda)
11176 (member bfile
11177 (mapcar (lambda(f) (file-truename f))
11178 org-agenda-files)) t)
11179 (if tmp (not (string-match "tmp" bname)) t)) b)))
11180 (buffer-list)))
11181 (delete nil blist)))
11183 (defun org-agenda-files (&optional unrestricted ext)
11184 "Get the list of agenda files.
11185 Optional UNRESTRICTED means return the full list even if a restriction
11186 is currently in place.
11187 When EXT is non-nil, try to add all files that are created by adding EXT
11188 to the file nemes. Basically, this is a way to add the archive files
11189 to the list, by setting EXT to \"_archive\" If EXT is non-nil, but not
11190 a string, \"_archive\" will be used."
11191 (let ((files
11192 (cond
11193 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
11194 ((stringp org-agenda-files) (org-read-agenda-file-list))
11195 ((listp org-agenda-files) org-agenda-files)
11196 (t (error "Invalid value of `org-agenda-files'")))))
11197 (setq files (apply 'append
11198 (mapcar (lambda (f)
11199 (if (file-directory-p f)
11200 (directory-files
11201 f t org-agenda-file-regexp)
11202 (list f)))
11203 files)))
11204 (when org-agenda-skip-unavailable-files
11205 (setq files (delq nil
11206 (mapcar (function
11207 (lambda (file)
11208 (and (file-readable-p file) file)))
11209 files))))
11210 (when ext
11211 (setq ext (if (and (stringp ext) (string-match "\\S-" ext))
11212 ext "_archive"))
11213 (setq files (apply 'append
11214 (mapcar
11215 (lambda (f)
11216 (if (file-exists-p (concat f ext))
11217 (list f (concat f ext))
11218 (list f)))
11219 files))))
11220 files))
11222 (defun org-edit-agenda-file-list ()
11223 "Edit the list of agenda files.
11224 Depending on setup, this either uses customize to edit the variable
11225 `org-agenda-files', or it visits the file that is holding the list. In the
11226 latter case, the buffer is set up in a way that saving it automatically kills
11227 the buffer and restores the previous window configuration."
11228 (interactive)
11229 (if (stringp org-agenda-files)
11230 (let ((cw (current-window-configuration)))
11231 (find-file org-agenda-files)
11232 (org-set-local 'org-window-configuration cw)
11233 (org-add-hook 'after-save-hook
11234 (lambda ()
11235 (set-window-configuration
11236 (prog1 org-window-configuration
11237 (kill-buffer (current-buffer))))
11238 (org-install-agenda-files-menu)
11239 (message "New agenda file list installed"))
11240 nil 'local)
11241 (message "%s" (substitute-command-keys
11242 "Edit list and finish with \\[save-buffer]")))
11243 (customize-variable 'org-agenda-files)))
11245 (defun org-store-new-agenda-file-list (list)
11246 "Set new value for the agenda file list and save it correcly."
11247 (if (stringp org-agenda-files)
11248 (let ((f org-agenda-files) b)
11249 (while (setq b (find-buffer-visiting f)) (kill-buffer b))
11250 (with-temp-file f
11251 (insert (mapconcat 'identity list "\n") "\n")))
11252 (let ((org-mode-hook nil) (default-major-mode 'fundamental-mode))
11253 (setq org-agenda-files list)
11254 (customize-save-variable 'org-agenda-files org-agenda-files))))
11256 (defun org-read-agenda-file-list ()
11257 "Read the list of agenda files from a file."
11258 (when (file-directory-p org-agenda-files)
11259 (error "`org-agenda-files' cannot be a single directory"))
11260 (when (stringp org-agenda-files)
11261 (with-temp-buffer
11262 (insert-file-contents org-agenda-files)
11263 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*"))))
11266 ;;;###autoload
11267 (defun org-cycle-agenda-files ()
11268 "Cycle through the files in `org-agenda-files'.
11269 If the current buffer visits an agenda file, find the next one in the list.
11270 If the current buffer does not, find the first agenda file."
11271 (interactive)
11272 (let* ((fs (org-agenda-files t))
11273 (files (append fs (list (car fs))))
11274 (tcf (if buffer-file-name (file-truename buffer-file-name)))
11275 file)
11276 (unless files (error "No agenda files"))
11277 (catch 'exit
11278 (while (setq file (pop files))
11279 (if (equal (file-truename file) tcf)
11280 (when (car files)
11281 (find-file (car files))
11282 (throw 'exit t))))
11283 (find-file (car fs)))
11284 (if (buffer-base-buffer) (switch-to-buffer (buffer-base-buffer)))))
11286 (defun org-agenda-file-to-front (&optional to-end)
11287 "Move/add the current file to the top of the agenda file list.
11288 If the file is not present in the list, it is added to the front. If it is
11289 present, it is moved there. With optional argument TO-END, add/move to the
11290 end of the list."
11291 (interactive "P")
11292 (let ((org-agenda-skip-unavailable-files nil)
11293 (file-alist (mapcar (lambda (x)
11294 (cons (file-truename x) x))
11295 (org-agenda-files t)))
11296 (ctf (file-truename buffer-file-name))
11297 x had)
11298 (setq x (assoc ctf file-alist) had x)
11300 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
11301 (if to-end
11302 (setq file-alist (append (delq x file-alist) (list x)))
11303 (setq file-alist (cons x (delq x file-alist))))
11304 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
11305 (org-install-agenda-files-menu)
11306 (message "File %s to %s of agenda file list"
11307 (if had "moved" "added") (if to-end "end" "front"))))
11309 (defun org-remove-file (&optional file)
11310 "Remove current file from the list of files in variable `org-agenda-files'.
11311 These are the files which are being checked for agenda entries.
11312 Optional argument FILE means, use this file instead of the current."
11313 (interactive)
11314 (let* ((org-agenda-skip-unavailable-files nil)
11315 (file (or file buffer-file-name))
11316 (true-file (file-truename file))
11317 (afile (abbreviate-file-name file))
11318 (files (delq nil (mapcar
11319 (lambda (x)
11320 (if (equal true-file
11321 (file-truename x))
11322 nil x))
11323 (org-agenda-files t)))))
11324 (if (not (= (length files) (length (org-agenda-files t))))
11325 (progn
11326 (org-store-new-agenda-file-list files)
11327 (org-install-agenda-files-menu)
11328 (message "Removed file: %s" afile))
11329 (message "File was not in list: %s (not removed)" afile))))
11331 (defun org-file-menu-entry (file)
11332 (vector file (list 'find-file file) t))
11334 (defun org-check-agenda-file (file)
11335 "Make sure FILE exists. If not, ask user what to do."
11336 (when (not (file-exists-p file))
11337 (message "non-existent file %s. [R]emove from list or [A]bort?"
11338 (abbreviate-file-name file))
11339 (let ((r (downcase (read-char-exclusive))))
11340 (cond
11341 ((equal r ?r)
11342 (org-remove-file file)
11343 (throw 'nextfile t))
11344 (t (error "Abort"))))))
11346 (defun org-get-agenda-file-buffer (file)
11347 "Get a buffer visiting FILE. If the buffer needs to be created, add
11348 it to the list of buffers which might be released later."
11349 (let ((buf (org-find-base-buffer-visiting file)))
11350 (if buf
11351 buf ; just return it
11352 ;; Make a new buffer and remember it
11353 (setq buf (find-file-noselect file))
11354 (if buf (push buf org-agenda-new-buffers))
11355 buf)))
11357 (defun org-release-buffers (blist)
11358 "Release all buffers in list, asking the user for confirmation when needed.
11359 When a buffer is unmodified, it is just killed. When modified, it is saved
11360 \(if the user agrees) and then killed."
11361 (let (buf file)
11362 (while (setq buf (pop blist))
11363 (setq file (buffer-file-name buf))
11364 (when (and (buffer-modified-p buf)
11365 file
11366 (y-or-n-p (format "Save file %s? " file)))
11367 (with-current-buffer buf (save-buffer)))
11368 (kill-buffer buf))))
11370 (defun org-prepare-agenda-buffers (files)
11371 "Create buffers for all agenda files, protect archived trees and comments."
11372 (interactive)
11373 (let ((pa '(:org-archived t))
11374 (pc '(:org-comment t))
11375 (pall '(:org-archived t :org-comment t))
11376 (inhibit-read-only t)
11377 (rea (concat ":" org-archive-tag ":"))
11378 bmp file re)
11379 (save-excursion
11380 (save-restriction
11381 (while (setq file (pop files))
11382 (if (bufferp file)
11383 (set-buffer file)
11384 (org-check-agenda-file file)
11385 (set-buffer (org-get-agenda-file-buffer file)))
11386 (widen)
11387 (setq bmp (buffer-modified-p))
11388 (org-refresh-category-properties)
11389 (setq org-todo-keywords-for-agenda
11390 (append org-todo-keywords-for-agenda org-todo-keywords-1))
11391 (setq org-done-keywords-for-agenda
11392 (append org-done-keywords-for-agenda org-done-keywords))
11393 (save-excursion
11394 (remove-text-properties (point-min) (point-max) pall)
11395 (when org-agenda-skip-archived-trees
11396 (goto-char (point-min))
11397 (while (re-search-forward rea nil t)
11398 (if (org-on-heading-p t)
11399 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
11400 (goto-char (point-min))
11401 (setq re (concat "^\\*+ +" org-comment-string "\\>"))
11402 (while (re-search-forward re nil t)
11403 (add-text-properties
11404 (match-beginning 0) (org-end-of-subtree t) pc)))
11405 (set-buffer-modified-p bmp))))))
11407 ;;;; Embedded LaTeX
11409 (defvar org-cdlatex-mode-map (make-sparse-keymap)
11410 "Keymap for the minor `org-cdlatex-mode'.")
11412 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
11413 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
11414 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
11415 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
11416 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
11418 (defvar org-cdlatex-texmathp-advice-is-done nil
11419 "Flag remembering if we have applied the advice to texmathp already.")
11421 (define-minor-mode org-cdlatex-mode
11422 "Toggle the minor `org-cdlatex-mode'.
11423 This mode supports entering LaTeX environment and math in LaTeX fragments
11424 in Org-mode.
11425 \\{org-cdlatex-mode-map}"
11426 nil " OCDL" nil
11427 (when org-cdlatex-mode (require 'cdlatex))
11428 (unless org-cdlatex-texmathp-advice-is-done
11429 (setq org-cdlatex-texmathp-advice-is-done t)
11430 (defadvice texmathp (around org-math-always-on activate)
11431 "Always return t in org-mode buffers.
11432 This is because we want to insert math symbols without dollars even outside
11433 the LaTeX math segments. If Orgmode thinks that point is actually inside
11434 en embedded LaTeX fragement, let texmathp do its job.
11435 \\[org-cdlatex-mode-map]"
11436 (interactive)
11437 (let (p)
11438 (cond
11439 ((not (org-mode-p)) ad-do-it)
11440 ((eq this-command 'cdlatex-math-symbol)
11441 (setq ad-return-value t
11442 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
11444 (let ((p (org-inside-LaTeX-fragment-p)))
11445 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
11446 (setq ad-return-value t
11447 texmathp-why '("Org-mode embedded math" . 0))
11448 (if p ad-do-it)))))))))
11450 (defun turn-on-org-cdlatex ()
11451 "Unconditionally turn on `org-cdlatex-mode'."
11452 (org-cdlatex-mode 1))
11454 (defun org-inside-LaTeX-fragment-p ()
11455 "Test if point is inside a LaTeX fragment.
11456 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
11457 sequence appearing also before point.
11458 Even though the matchers for math are configurable, this function assumes
11459 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
11460 delimiters are skipped when they have been removed by customization.
11461 The return value is nil, or a cons cell with the delimiter and
11462 and the position of this delimiter.
11464 This function does a reasonably good job, but can locally be fooled by
11465 for example currency specifications. For example it will assume being in
11466 inline math after \"$22.34\". The LaTeX fragment formatter will only format
11467 fragments that are properly closed, but during editing, we have to live
11468 with the uncertainty caused by missing closing delimiters. This function
11469 looks only before point, not after."
11470 (catch 'exit
11471 (let ((pos (point))
11472 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
11473 (lim (progn
11474 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
11475 (point)))
11476 dd-on str (start 0) m re)
11477 (goto-char pos)
11478 (when dodollar
11479 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
11480 re (nth 1 (assoc "$" org-latex-regexps)))
11481 (while (string-match re str start)
11482 (cond
11483 ((= (match-end 0) (length str))
11484 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
11485 ((= (match-end 0) (- (length str) 5))
11486 (throw 'exit nil))
11487 (t (setq start (match-end 0))))))
11488 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
11489 (goto-char pos)
11490 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
11491 (and (match-beginning 2) (throw 'exit nil))
11492 ;; count $$
11493 (while (re-search-backward "\\$\\$" lim t)
11494 (setq dd-on (not dd-on)))
11495 (goto-char pos)
11496 (if dd-on (cons "$$" m))))))
11499 (defun org-try-cdlatex-tab ()
11500 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
11501 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
11502 - inside a LaTeX fragment, or
11503 - after the first word in a line, where an abbreviation expansion could
11504 insert a LaTeX environment."
11505 (when org-cdlatex-mode
11506 (cond
11507 ((save-excursion
11508 (skip-chars-backward "a-zA-Z0-9*")
11509 (skip-chars-backward " \t")
11510 (bolp))
11511 (cdlatex-tab) t)
11512 ((org-inside-LaTeX-fragment-p)
11513 (cdlatex-tab) t)
11514 (t nil))))
11516 (defun org-cdlatex-underscore-caret (&optional arg)
11517 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
11518 Revert to the normal definition outside of these fragments."
11519 (interactive "P")
11520 (if (org-inside-LaTeX-fragment-p)
11521 (call-interactively 'cdlatex-sub-superscript)
11522 (let (org-cdlatex-mode)
11523 (call-interactively (key-binding (vector last-input-event))))))
11525 (defun org-cdlatex-math-modify (&optional arg)
11526 "Execute `cdlatex-math-modify' in LaTeX fragments.
11527 Revert to the normal definition outside of these fragments."
11528 (interactive "P")
11529 (if (org-inside-LaTeX-fragment-p)
11530 (call-interactively 'cdlatex-math-modify)
11531 (let (org-cdlatex-mode)
11532 (call-interactively (key-binding (vector last-input-event))))))
11534 (defvar org-latex-fragment-image-overlays nil
11535 "List of overlays carrying the images of latex fragments.")
11536 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
11538 (defun org-remove-latex-fragment-image-overlays ()
11539 "Remove all overlays with LaTeX fragment images in current buffer."
11540 (mapc 'org-delete-overlay org-latex-fragment-image-overlays)
11541 (setq org-latex-fragment-image-overlays nil))
11543 (defun org-preview-latex-fragment (&optional subtree)
11544 "Preview the LaTeX fragment at point, or all locally or globally.
11545 If the cursor is in a LaTeX fragment, create the image and overlay
11546 it over the source code. If there is no fragment at point, display
11547 all fragments in the current text, from one headline to the next. With
11548 prefix SUBTREE, display all fragments in the current subtree. With a
11549 double prefix `C-u C-u', or when the cursor is before the first headline,
11550 display all fragments in the buffer.
11551 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
11552 (interactive "P")
11553 (org-remove-latex-fragment-image-overlays)
11554 (save-excursion
11555 (save-restriction
11556 (let (beg end at msg)
11557 (cond
11558 ((or (equal subtree '(16))
11559 (not (save-excursion
11560 (re-search-backward (concat "^" outline-regexp) nil t))))
11561 (setq beg (point-min) end (point-max)
11562 msg "Creating images for buffer...%s"))
11563 ((equal subtree '(4))
11564 (org-back-to-heading)
11565 (setq beg (point) end (org-end-of-subtree t)
11566 msg "Creating images for subtree...%s"))
11568 (if (setq at (org-inside-LaTeX-fragment-p))
11569 (goto-char (max (point-min) (- (cdr at) 2)))
11570 (org-back-to-heading))
11571 (setq beg (point) end (progn (outline-next-heading) (point))
11572 msg (if at "Creating image...%s"
11573 "Creating images for entry...%s"))))
11574 (message msg "")
11575 (narrow-to-region beg end)
11576 (goto-char beg)
11577 (org-format-latex
11578 (concat "ltxpng/" (file-name-sans-extension
11579 (file-name-nondirectory
11580 buffer-file-name)))
11581 default-directory 'overlays msg at 'forbuffer)
11582 (message msg "done. Use `C-c C-c' to remove images.")))))
11584 (defvar org-latex-regexps
11585 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
11586 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
11587 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
11588 ("$" "\\([^$]\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([ .,?;:'\")\000]\\|$\\)" 2 nil)
11589 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
11590 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 t)
11591 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 t))
11592 "Regular expressions for matching embedded LaTeX.")
11594 (defun org-format-latex (prefix &optional dir overlays msg at forbuffer)
11595 "Replace LaTeX fragments with links to an image, and produce images."
11596 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
11597 (let* ((prefixnodir (file-name-nondirectory prefix))
11598 (absprefix (expand-file-name prefix dir))
11599 (todir (file-name-directory absprefix))
11600 (opt org-format-latex-options)
11601 (matchers (plist-get opt :matchers))
11602 (re-list org-latex-regexps)
11603 (cnt 0) txt link beg end re e checkdir
11604 m n block linkfile movefile ov)
11605 ;; Check if there are old images files with this prefix, and remove them
11606 (when (file-directory-p todir)
11607 (mapc 'delete-file
11608 (directory-files
11609 todir 'full
11610 (concat (regexp-quote prefixnodir) "_[0-9]+\\.png$"))))
11611 ;; Check the different regular expressions
11612 (while (setq e (pop re-list))
11613 (setq m (car e) re (nth 1 e) n (nth 2 e)
11614 block (if (nth 3 e) "\n\n" ""))
11615 (when (member m matchers)
11616 (goto-char (point-min))
11617 (while (re-search-forward re nil t)
11618 (when (or (not at) (equal (cdr at) (match-beginning n)))
11619 (setq txt (match-string n)
11620 beg (match-beginning n) end (match-end n)
11621 cnt (1+ cnt)
11622 linkfile (format "%s_%04d.png" prefix cnt)
11623 movefile (format "%s_%04d.png" absprefix cnt)
11624 link (concat block "[[file:" linkfile "]]" block))
11625 (if msg (message msg cnt))
11626 (goto-char beg)
11627 (unless checkdir ; make sure the directory exists
11628 (setq checkdir t)
11629 (or (file-directory-p todir) (make-directory todir)))
11630 (org-create-formula-image
11631 txt movefile opt forbuffer)
11632 (if overlays
11633 (progn
11634 (setq ov (org-make-overlay beg end))
11635 (if (featurep 'xemacs)
11636 (progn
11637 (org-overlay-put ov 'invisible t)
11638 (org-overlay-put
11639 ov 'end-glyph
11640 (make-glyph (vector 'png :file movefile))))
11641 (org-overlay-put
11642 ov 'display
11643 (list 'image :type 'png :file movefile :ascent 'center)))
11644 (push ov org-latex-fragment-image-overlays)
11645 (goto-char end))
11646 (delete-region beg end)
11647 (insert link))))))))
11649 ;; This function borrows from Ganesh Swami's latex2png.el
11650 (defun org-create-formula-image (string tofile options buffer)
11651 (let* ((tmpdir (if (featurep 'xemacs)
11652 (temp-directory)
11653 temporary-file-directory))
11654 (texfilebase (make-temp-name
11655 (expand-file-name "orgtex" tmpdir)))
11656 (texfile (concat texfilebase ".tex"))
11657 (dvifile (concat texfilebase ".dvi"))
11658 (pngfile (concat texfilebase ".png"))
11659 (fnh (if (featurep 'xemacs)
11660 (font-height (get-face-font 'default))
11661 (face-attribute 'default :height nil)))
11662 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
11663 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
11664 (fg (or (plist-get options (if buffer :foreground :html-foreground))
11665 "Black"))
11666 (bg (or (plist-get options (if buffer :background :html-background))
11667 "Transparent")))
11668 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
11669 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
11670 (with-temp-file texfile
11671 (insert org-format-latex-header
11672 "\n\\begin{document}\n" string "\n\\end{document}\n"))
11673 (let ((dir default-directory))
11674 (condition-case nil
11675 (progn
11676 (cd tmpdir)
11677 (call-process "latex" nil nil nil texfile))
11678 (error nil))
11679 (cd dir))
11680 (if (not (file-exists-p dvifile))
11681 (progn (message "Failed to create dvi file from %s" texfile) nil)
11682 (call-process "dvipng" nil nil nil
11683 "-E" "-fg" fg "-bg" bg
11684 "-D" dpi
11685 ;;"-x" scale "-y" scale
11686 "-T" "tight"
11687 "-o" pngfile
11688 dvifile)
11689 (if (not (file-exists-p pngfile))
11690 (progn (message "Failed to create png file from %s" texfile) nil)
11691 ;; Use the requested file name and clean up
11692 (copy-file pngfile tofile 'replace)
11693 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
11694 (delete-file (concat texfilebase e)))
11695 pngfile))))
11697 (defun org-dvipng-color (attr)
11698 "Return an rgb color specification for dvipng."
11699 (apply 'format "rgb %s %s %s"
11700 (mapcar 'org-normalize-color
11701 (color-values (face-attribute 'default attr nil)))))
11703 (defun org-normalize-color (value)
11704 "Return string to be used as color value for an RGB component."
11705 (format "%g" (/ value 65535.0)))
11708 ;;;; Key bindings
11710 ;; Make `C-c C-x' a prefix key
11711 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
11713 ;; TAB key with modifiers
11714 (org-defkey org-mode-map "\C-i" 'org-cycle)
11715 (org-defkey org-mode-map [(tab)] 'org-cycle)
11716 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
11717 (org-defkey org-mode-map [(meta tab)] 'org-complete)
11718 (org-defkey org-mode-map "\M-\t" 'org-complete)
11719 (org-defkey org-mode-map "\M-\C-i" 'org-complete)
11720 ;; The following line is necessary under Suse GNU/Linux
11721 (unless (featurep 'xemacs)
11722 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
11723 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
11724 (define-key org-mode-map [backtab] 'org-shifttab)
11726 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
11727 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
11728 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
11730 ;; Cursor keys with modifiers
11731 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
11732 (org-defkey org-mode-map [(meta right)] 'org-metaright)
11733 (org-defkey org-mode-map [(meta up)] 'org-metaup)
11734 (org-defkey org-mode-map [(meta down)] 'org-metadown)
11736 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
11737 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
11738 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
11739 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
11741 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
11742 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
11743 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
11744 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
11746 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
11747 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
11749 ;;; Extra keys for tty access.
11750 ;; We only set them when really needed because otherwise the
11751 ;; menus don't show the simple keys
11753 (when (or (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
11754 (not window-system))
11755 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
11756 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
11757 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
11758 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
11759 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
11760 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
11761 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
11762 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
11763 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
11764 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
11765 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
11766 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
11767 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
11768 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
11769 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
11770 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
11771 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
11772 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
11773 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
11774 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
11775 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
11776 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft))
11778 ;; All the other keys
11780 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
11781 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
11782 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree)
11783 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
11784 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
11785 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-toggle-archive-tag)
11786 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
11787 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
11788 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
11789 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
11790 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
11791 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
11792 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
11793 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
11794 (org-defkey org-mode-map "\C-c\C-v" 'org-show-todo-tree)
11795 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
11796 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
11797 (org-defkey org-mode-map "\C-c\\" 'org-tags-sparse-tree) ; Minor-mode res.
11798 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
11799 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
11800 (org-defkey org-mode-map [(control return)] 'org-insert-heading-after-current)
11801 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
11802 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
11803 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
11804 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
11805 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
11806 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
11807 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
11808 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
11809 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
11810 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
11811 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
11812 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
11813 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
11814 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
11815 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
11816 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
11817 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
11818 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
11819 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
11820 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
11821 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
11822 (org-defkey org-mode-map "\C-c^" 'org-sort)
11823 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
11824 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
11825 (org-defkey org-mode-map "\C-c#" 'org-update-checkbox-count)
11826 (org-defkey org-mode-map "\C-m" 'org-return)
11827 (org-defkey org-mode-map "\C-j" 'org-return-indent)
11828 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
11829 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
11830 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
11831 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
11832 (org-defkey org-mode-map "\C-c'" 'org-table-edit-formulas)
11833 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
11834 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
11835 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
11836 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
11837 (org-defkey org-mode-map "\C-c\C-q" 'org-table-wrap-region)
11838 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
11839 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
11840 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
11841 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
11842 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
11844 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-cut-special)
11845 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
11846 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
11847 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
11849 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
11850 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
11851 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
11852 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
11853 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
11854 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
11855 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
11856 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
11857 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
11858 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
11859 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
11860 (org-defkey org-mode-map "\C-c\C-xr" 'org-insert-columns-dblock)
11862 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
11864 (when (featurep 'xemacs)
11865 (org-defkey org-mode-map 'button3 'popup-mode-menu))
11867 (defvar org-table-auto-blank-field) ; defined in org-table.el
11868 (defun org-self-insert-command (N)
11869 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
11870 If the cursor is in a table looking at whitespace, the whitespace is
11871 overwritten, and the table is not marked as requiring realignment."
11872 (interactive "p")
11873 (if (and (org-table-p)
11874 (progn
11875 ;; check if we blank the field, and if that triggers align
11876 (and (featurep 'org-table) org-table-auto-blank-field
11877 (member last-command
11878 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
11879 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
11880 ;; got extra space, this field does not determine column width
11881 (let (org-table-may-need-update) (org-table-blank-field))
11882 ;; no extra space, this field may determine column width
11883 (org-table-blank-field)))
11885 (eq N 1)
11886 (looking-at "[^|\n]* |"))
11887 (let (org-table-may-need-update)
11888 (goto-char (1- (match-end 0)))
11889 (delete-backward-char 1)
11890 (goto-char (match-beginning 0))
11891 (self-insert-command N))
11892 (setq org-table-may-need-update t)
11893 (self-insert-command N)
11894 (org-fix-tags-on-the-fly)))
11896 (defun org-fix-tags-on-the-fly ()
11897 (when (and (equal (char-after (point-at-bol)) ?*)
11898 (org-on-heading-p))
11899 (org-align-tags-here org-tags-column)))
11901 (defun org-delete-backward-char (N)
11902 "Like `delete-backward-char', insert whitespace at field end in tables.
11903 When deleting backwards, in tables this function will insert whitespace in
11904 front of the next \"|\" separator, to keep the table aligned. The table will
11905 still be marked for re-alignment if the field did fill the entire column,
11906 because, in this case the deletion might narrow the column."
11907 (interactive "p")
11908 (if (and (org-table-p)
11909 (eq N 1)
11910 (string-match "|" (buffer-substring (point-at-bol) (point)))
11911 (looking-at ".*?|"))
11912 (let ((pos (point))
11913 (noalign (looking-at "[^|\n\r]* |"))
11914 (c org-table-may-need-update))
11915 (backward-delete-char N)
11916 (skip-chars-forward "^|")
11917 (insert " ")
11918 (goto-char (1- pos))
11919 ;; noalign: if there were two spaces at the end, this field
11920 ;; does not determine the width of the column.
11921 (if noalign (setq org-table-may-need-update c)))
11922 (backward-delete-char N)
11923 (org-fix-tags-on-the-fly)))
11925 (defun org-delete-char (N)
11926 "Like `delete-char', but insert whitespace at field end in tables.
11927 When deleting characters, in tables this function will insert whitespace in
11928 front of the next \"|\" separator, to keep the table aligned. The table will
11929 still be marked for re-alignment if the field did fill the entire column,
11930 because, in this case the deletion might narrow the column."
11931 (interactive "p")
11932 (if (and (org-table-p)
11933 (not (bolp))
11934 (not (= (char-after) ?|))
11935 (eq N 1))
11936 (if (looking-at ".*?|")
11937 (let ((pos (point))
11938 (noalign (looking-at "[^|\n\r]* |"))
11939 (c org-table-may-need-update))
11940 (replace-match (concat
11941 (substring (match-string 0) 1 -1)
11942 " |"))
11943 (goto-char pos)
11944 ;; noalign: if there were two spaces at the end, this field
11945 ;; does not determine the width of the column.
11946 (if noalign (setq org-table-may-need-update c)))
11947 (delete-char N))
11948 (delete-char N)
11949 (org-fix-tags-on-the-fly)))
11951 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
11952 (put 'org-self-insert-command 'delete-selection t)
11953 (put 'orgtbl-self-insert-command 'delete-selection t)
11954 (put 'org-delete-char 'delete-selection 'supersede)
11955 (put 'org-delete-backward-char 'delete-selection 'supersede)
11957 ;; Make `flyspell-mode' delay after some commands
11958 (put 'org-self-insert-command 'flyspell-delayed t)
11959 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
11960 (put 'org-delete-char 'flyspell-delayed t)
11961 (put 'org-delete-backward-char 'flyspell-delayed t)
11963 ;; Make pabbrev-mode expand after org-mode commands
11964 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
11965 (put 'orgybl-self-insert-command 'pabbrev-expand-after-command t)
11967 ;; How to do this: Measure non-white length of current string
11968 ;; If equal to column width, we should realign.
11970 (defun org-remap (map &rest commands)
11971 "In MAP, remap the functions given in COMMANDS.
11972 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
11973 (let (new old)
11974 (while commands
11975 (setq old (pop commands) new (pop commands))
11976 (if (fboundp 'command-remapping)
11977 (org-defkey map (vector 'remap old) new)
11978 (substitute-key-definition old new map global-map)))))
11980 (when (eq org-enable-table-editor 'optimized)
11981 ;; If the user wants maximum table support, we need to hijack
11982 ;; some standard editing functions
11983 (org-remap org-mode-map
11984 'self-insert-command 'org-self-insert-command
11985 'delete-char 'org-delete-char
11986 'delete-backward-char 'org-delete-backward-char)
11987 (org-defkey org-mode-map "|" 'org-force-self-insert))
11989 (defun org-shiftcursor-error ()
11990 "Throw an error because Shift-Cursor command was applied in wrong context."
11991 (error "This command is active in special context like tables, headlines or timestamps"))
11993 (defun org-shifttab (&optional arg)
11994 "Global visibility cycling or move to previous table field.
11995 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
11996 on context.
11997 See the individual commands for more information."
11998 (interactive "P")
11999 (cond
12000 ((org-at-table-p) (call-interactively 'org-table-previous-field))
12001 (arg (message "Content view to level: ")
12002 (org-content (prefix-numeric-value arg))
12003 (setq org-cycle-global-status 'overview))
12004 (t (call-interactively 'org-global-cycle))))
12006 (defun org-shiftmetaleft ()
12007 "Promote subtree or delete table column.
12008 Calls `org-promote-subtree', `org-outdent-item',
12009 or `org-table-delete-column', depending on context.
12010 See the individual commands for more information."
12011 (interactive)
12012 (cond
12013 ((org-at-table-p) (call-interactively 'org-table-delete-column))
12014 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
12015 ((org-at-item-p) (call-interactively 'org-outdent-item))
12016 (t (org-shiftcursor-error))))
12018 (defun org-shiftmetaright ()
12019 "Demote subtree or insert table column.
12020 Calls `org-demote-subtree', `org-indent-item',
12021 or `org-table-insert-column', depending on context.
12022 See the individual commands for more information."
12023 (interactive)
12024 (cond
12025 ((org-at-table-p) (call-interactively 'org-table-insert-column))
12026 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
12027 ((org-at-item-p) (call-interactively 'org-indent-item))
12028 (t (org-shiftcursor-error))))
12030 (defun org-shiftmetaup (&optional arg)
12031 "Move subtree up or kill table row.
12032 Calls `org-move-subtree-up' or `org-table-kill-row' or
12033 `org-move-item-up' depending on context. See the individual commands
12034 for more information."
12035 (interactive "P")
12036 (cond
12037 ((org-at-table-p) (call-interactively 'org-table-kill-row))
12038 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
12039 ((org-at-item-p) (call-interactively 'org-move-item-up))
12040 (t (org-shiftcursor-error))))
12041 (defun org-shiftmetadown (&optional arg)
12042 "Move subtree down or insert table row.
12043 Calls `org-move-subtree-down' or `org-table-insert-row' or
12044 `org-move-item-down', depending on context. See the individual
12045 commands for more information."
12046 (interactive "P")
12047 (cond
12048 ((org-at-table-p) (call-interactively 'org-table-insert-row))
12049 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
12050 ((org-at-item-p) (call-interactively 'org-move-item-down))
12051 (t (org-shiftcursor-error))))
12053 (defun org-metaleft (&optional arg)
12054 "Promote heading or move table column to left.
12055 Calls `org-do-promote' or `org-table-move-column', depending on context.
12056 With no specific context, calls the Emacs default `backward-word'.
12057 See the individual commands for more information."
12058 (interactive "P")
12059 (cond
12060 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
12061 ((or (org-on-heading-p) (org-region-active-p))
12062 (call-interactively 'org-do-promote))
12063 ((org-at-item-p) (call-interactively 'org-outdent-item))
12064 (t (call-interactively 'backward-word))))
12066 (defun org-metaright (&optional arg)
12067 "Demote subtree or move table column to right.
12068 Calls `org-do-demote' or `org-table-move-column', depending on context.
12069 With no specific context, calls the Emacs default `forward-word'.
12070 See the individual commands for more information."
12071 (interactive "P")
12072 (cond
12073 ((org-at-table-p) (call-interactively 'org-table-move-column))
12074 ((or (org-on-heading-p) (org-region-active-p))
12075 (call-interactively 'org-do-demote))
12076 ((org-at-item-p) (call-interactively 'org-indent-item))
12077 (t (call-interactively 'forward-word))))
12079 (defun org-metaup (&optional arg)
12080 "Move subtree up or move table row up.
12081 Calls `org-move-subtree-up' or `org-table-move-row' or
12082 `org-move-item-up', depending on context. See the individual commands
12083 for more information."
12084 (interactive "P")
12085 (cond
12086 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
12087 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
12088 ((org-at-item-p) (call-interactively 'org-move-item-up))
12089 (t (transpose-lines 1) (beginning-of-line -1))))
12091 (defun org-metadown (&optional arg)
12092 "Move subtree down or move table row down.
12093 Calls `org-move-subtree-down' or `org-table-move-row' or
12094 `org-move-item-down', depending on context. See the individual
12095 commands for more information."
12096 (interactive "P")
12097 (cond
12098 ((org-at-table-p) (call-interactively 'org-table-move-row))
12099 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
12100 ((org-at-item-p) (call-interactively 'org-move-item-down))
12101 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
12103 (defun org-shiftup (&optional arg)
12104 "Increase item in timestamp or increase priority of current headline.
12105 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
12106 depending on context. See the individual commands for more information."
12107 (interactive "P")
12108 (cond
12109 ((org-at-timestamp-p t)
12110 (call-interactively (if org-edit-timestamp-down-means-later
12111 'org-timestamp-down 'org-timestamp-up)))
12112 ((org-on-heading-p) (call-interactively 'org-priority-up))
12113 ((org-at-item-p) (call-interactively 'org-previous-item))
12114 ((org-clocktable-try-shift 'up arg))
12115 (t (call-interactively 'org-beginning-of-item) (beginning-of-line 1))))
12117 (defun org-shiftdown (&optional arg)
12118 "Decrease item in timestamp or decrease priority of current headline.
12119 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
12120 depending on context. See the individual commands for more information."
12121 (interactive "P")
12122 (cond
12123 ((org-at-timestamp-p t)
12124 (call-interactively (if org-edit-timestamp-down-means-later
12125 'org-timestamp-up 'org-timestamp-down)))
12126 ((org-on-heading-p) (call-interactively 'org-priority-down))
12127 ((org-clocktable-try-shift 'down arg))
12128 (t (call-interactively 'org-next-item))))
12130 (defun org-shiftright (&optional arg)
12131 "Next TODO keyword or timestamp one day later, depending on context."
12132 (interactive "P")
12133 (cond
12134 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
12135 ((org-on-heading-p) (org-call-with-arg 'org-todo 'right))
12136 ((org-at-item-p) (org-call-with-arg 'org-cycle-list-bullet nil))
12137 ((org-at-property-p) (call-interactively 'org-property-next-allowed-value))
12138 ((org-clocktable-try-shift 'right arg))
12139 (t (org-shiftcursor-error))))
12141 (defun org-shiftleft (&optional arg)
12142 "Previous TODO keyword or timestamp one day earlier, depending on context."
12143 (interactive "P")
12144 (cond
12145 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
12146 ((org-on-heading-p) (org-call-with-arg 'org-todo 'left))
12147 ((org-at-item-p) (org-call-with-arg 'org-cycle-list-bullet 'previous))
12148 ((org-at-property-p)
12149 (call-interactively 'org-property-previous-allowed-value))
12150 ((org-clocktable-try-shift 'left arg))
12151 (t (org-shiftcursor-error))))
12153 (defun org-shiftcontrolright ()
12154 "Switch to next TODO set."
12155 (interactive)
12156 (cond
12157 ((org-on-heading-p) (org-call-with-arg 'org-todo 'nextset))
12158 (t (org-shiftcursor-error))))
12160 (defun org-shiftcontrolleft ()
12161 "Switch to previous TODO set."
12162 (interactive)
12163 (cond
12164 ((org-on-heading-p) (org-call-with-arg 'org-todo 'previousset))
12165 (t (org-shiftcursor-error))))
12167 (defun org-ctrl-c-ret ()
12168 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
12169 (interactive)
12170 (cond
12171 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
12172 (t (call-interactively 'org-insert-heading))))
12174 (defun org-copy-special ()
12175 "Copy region in table or copy current subtree.
12176 Calls `org-table-copy' or `org-copy-subtree', depending on context.
12177 See the individual commands for more information."
12178 (interactive)
12179 (call-interactively
12180 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
12182 (defun org-cut-special ()
12183 "Cut region in table or cut current subtree.
12184 Calls `org-table-copy' or `org-cut-subtree', depending on context.
12185 See the individual commands for more information."
12186 (interactive)
12187 (call-interactively
12188 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
12190 (defun org-paste-special (arg)
12191 "Paste rectangular region into table, or past subtree relative to level.
12192 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
12193 See the individual commands for more information."
12194 (interactive "P")
12195 (if (org-at-table-p)
12196 (org-table-paste-rectangle)
12197 (org-paste-subtree arg)))
12199 (defun org-ctrl-c-ctrl-c (&optional arg)
12200 "Set tags in headline, or update according to changed information at point.
12202 This command does many different things, depending on context:
12204 - If the cursor is in a headline, prompt for tags and insert them
12205 into the current line, aligned to `org-tags-column'. When called
12206 with prefix arg, realign all tags in the current buffer.
12208 - If the cursor is in one of the special #+KEYWORD lines, this
12209 triggers scanning the buffer for these lines and updating the
12210 information.
12212 - If the cursor is inside a table, realign the table. This command
12213 works even if the automatic table editor has been turned off.
12215 - If the cursor is on a #+TBLFM line, re-apply the formulas to
12216 the entire table.
12218 - If the cursor is a the beginning of a dynamic block, update it.
12220 - If the cursor is inside a table created by the table.el package,
12221 activate that table.
12223 - If the current buffer is a remember buffer, close note and file it.
12224 with a prefix argument, file it without further interaction to the default
12225 location.
12227 - If the cursor is on a <<<target>>>, update radio targets and corresponding
12228 links in this buffer.
12230 - If the cursor is on a numbered item in a plain list, renumber the
12231 ordered list.
12233 - If the cursor is on a checkbox, toggle it."
12234 (interactive "P")
12235 (let ((org-enable-table-editor t))
12236 (cond
12237 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
12238 org-occur-highlights
12239 org-latex-fragment-image-overlays)
12240 (and (boundp 'org-clock-overlays) (org-remove-clock-overlays))
12241 (org-remove-occur-highlights)
12242 (org-remove-latex-fragment-image-overlays)
12243 (message "Temporary highlights/overlays removed from current buffer"))
12244 ((and (local-variable-p 'org-finish-function (current-buffer))
12245 (fboundp org-finish-function))
12246 (funcall org-finish-function))
12247 ((org-at-property-p)
12248 (call-interactively 'org-property-action))
12249 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
12250 ((org-on-heading-p) (call-interactively 'org-set-tags))
12251 ((org-at-table.el-p)
12252 (require 'table)
12253 (beginning-of-line 1)
12254 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
12255 (call-interactively 'table-recognize-table))
12256 ((org-at-table-p)
12257 (org-table-maybe-eval-formula)
12258 (if arg
12259 (call-interactively 'org-table-recalculate)
12260 (org-table-maybe-recalculate-line))
12261 (call-interactively 'org-table-align))
12262 ((org-at-item-checkbox-p)
12263 (call-interactively 'org-toggle-checkbox))
12264 ((org-at-item-p)
12265 (call-interactively 'org-maybe-renumber-ordered-list))
12266 ((save-excursion (beginning-of-line 1) (looking-at "#\\+BEGIN:"))
12267 ;; Dynamic block
12268 (beginning-of-line 1)
12269 (org-update-dblock))
12270 ((save-excursion (beginning-of-line 1) (looking-at "#\\+\\([A-Z]+\\)"))
12271 (cond
12272 ((equal (match-string 1) "TBLFM")
12273 ;; Recalculate the table before this line
12274 (save-excursion
12275 (beginning-of-line 1)
12276 (skip-chars-backward " \r\n\t")
12277 (if (org-at-table-p)
12278 (org-call-with-arg 'org-table-recalculate t))))
12280 (call-interactively 'org-mode-restart))))
12281 (t (error "C-c C-c can do nothing useful at this location.")))))
12283 (defun org-mode-restart ()
12284 "Restart Org-mode, to scan again for special lines.
12285 Also updates the keyword regular expressions."
12286 (interactive)
12287 (let ((org-inhibit-startup t)) (org-mode))
12288 (message "Org-mode restarted to refresh keyword and special line setup"))
12290 (defun org-kill-note-or-show-branches ()
12291 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
12292 (interactive)
12293 (if (not org-finish-function)
12294 (call-interactively 'show-branches)
12295 (let ((org-note-abort t))
12296 (funcall org-finish-function))))
12298 (defun org-return (&optional indent)
12299 "Goto next table row or insert a newline.
12300 Calls `org-table-next-row' or `newline', depending on context.
12301 See the individual commands for more information."
12302 (interactive)
12303 (cond
12304 ((bobp) (if indent (newline-and-indent) (newline)))
12305 ((and (org-at-heading-p)
12306 (looking-at
12307 (org-re "\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$")))
12308 (org-show-entry)
12309 (end-of-line 1)
12310 (newline))
12311 ((org-at-table-p)
12312 (org-table-justify-field-maybe)
12313 (call-interactively 'org-table-next-row))
12314 (t (if indent (newline-and-indent) (newline)))))
12316 (defun org-return-indent ()
12317 "Goto next table row or insert a newline and indent.
12318 Calls `org-table-next-row' or `newline-and-indent', depending on
12319 context. See the individual commands for more information."
12320 (interactive)
12321 (org-return t))
12323 (defun org-ctrl-c-star ()
12324 "Compute table, or change heading status of lines.
12325 Calls `org-table-recalculate' or `org-toggle-region-headlines',
12326 depending on context. This will also turn a plain list item or a normal
12327 line into a subheading."
12328 (interactive)
12329 (cond
12330 ((org-at-table-p)
12331 (call-interactively 'org-table-recalculate))
12332 ((org-region-active-p)
12333 ;; Convert all lines in region to list items
12334 (call-interactively 'org-toggle-region-headings))
12335 ((org-on-heading-p)
12336 (org-toggle-region-headings (point-at-bol)
12337 (min (1+ (point-at-eol)) (point-max))))
12338 ((org-at-item-p)
12339 ;; Convert to heading
12340 (let ((level (save-match-data
12341 (save-excursion
12342 (condition-case nil
12343 (progn
12344 (org-back-to-heading t)
12345 (funcall outline-level))
12346 (error 0))))))
12347 (replace-match
12348 (concat (make-string (org-get-valid-level level 1) ?*) " ") t t)))
12349 (t (org-toggle-region-headings (point-at-bol)
12350 (min (1+ (point-at-eol)) (point-max))))))
12352 (defun org-ctrl-c-minus ()
12353 "Insert separator line in table or modify bullet status of line.
12354 Also turns a plain line or a region of lines into list items.
12355 Calls `org-table-insert-hline', `org-toggle-region-items', or
12356 `org-cycle-list-bullet', depending on context."
12357 (interactive)
12358 (cond
12359 ((org-at-table-p)
12360 (call-interactively 'org-table-insert-hline))
12361 ((org-on-heading-p)
12362 ;; Convert to item
12363 (save-excursion
12364 (beginning-of-line 1)
12365 (if (looking-at "\\*+ ")
12366 (replace-match (concat (make-string (- (match-end 0) (point) 1) ?\ ) "- ")))))
12367 ((org-region-active-p)
12368 ;; Convert all lines in region to list items
12369 (call-interactively 'org-toggle-region-items))
12370 ((org-in-item-p)
12371 (call-interactively 'org-cycle-list-bullet))
12372 (t (org-toggle-region-items (point-at-bol)
12373 (min (1+ (point-at-eol)) (point-max))))))
12375 (defun org-toggle-region-items (beg end)
12376 "Convert all lines in region to list items.
12377 If the first line is already an item, convert all list items in the region
12378 to normal lines."
12379 (interactive "r")
12380 (let (l2 l)
12381 (save-excursion
12382 (goto-char end)
12383 (setq l2 (org-current-line))
12384 (goto-char beg)
12385 (beginning-of-line 1)
12386 (setq l (1- (org-current-line)))
12387 (if (org-at-item-p)
12388 ;; We already have items, de-itemize
12389 (while (< (setq l (1+ l)) l2)
12390 (when (org-at-item-p)
12391 (goto-char (match-beginning 2))
12392 (delete-region (match-beginning 2) (match-end 2))
12393 (and (looking-at "[ \t]+") (replace-match "")))
12394 (beginning-of-line 2))
12395 (while (< (setq l (1+ l)) l2)
12396 (unless (org-at-item-p)
12397 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
12398 (replace-match "\\1- \\2")))
12399 (beginning-of-line 2))))))
12401 (defun org-toggle-region-headings (beg end)
12402 "Convert all lines in region to list items.
12403 If the first line is already an item, convert all list items in the region
12404 to normal lines."
12405 (interactive "r")
12406 (let (l2 l)
12407 (save-excursion
12408 (goto-char end)
12409 (setq l2 (org-current-line))
12410 (goto-char beg)
12411 (beginning-of-line 1)
12412 (setq l (1- (org-current-line)))
12413 (if (org-on-heading-p)
12414 ;; We already have headlines, de-star them
12415 (while (< (setq l (1+ l)) l2)
12416 (when (org-on-heading-p t)
12417 (and (looking-at outline-regexp) (replace-match "")))
12418 (beginning-of-line 2))
12419 (let* ((stars (save-excursion
12420 (re-search-backward org-complex-heading-regexp nil t)
12421 (or (match-string 1) "*")))
12422 (add-stars (if org-odd-levels-only "**" "*"))
12423 (rpl (concat stars add-stars " \\2")))
12424 (while (< (setq l (1+ l)) l2)
12425 (unless (org-on-heading-p)
12426 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
12427 (replace-match rpl)))
12428 (beginning-of-line 2)))))))
12430 (defun org-meta-return (&optional arg)
12431 "Insert a new heading or wrap a region in a table.
12432 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
12433 See the individual commands for more information."
12434 (interactive "P")
12435 (cond
12436 ((org-at-table-p)
12437 (call-interactively 'org-table-wrap-region))
12438 (t (call-interactively 'org-insert-heading))))
12440 ;;; Menu entries
12442 ;; Define the Org-mode menus
12443 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
12444 '("Tbl"
12445 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
12446 ["Next Field" org-cycle (org-at-table-p)]
12447 ["Previous Field" org-shifttab (org-at-table-p)]
12448 ["Next Row" org-return (org-at-table-p)]
12449 "--"
12450 ["Blank Field" org-table-blank-field (org-at-table-p)]
12451 ["Edit Field" org-table-edit-field (org-at-table-p)]
12452 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
12453 "--"
12454 ("Column"
12455 ["Move Column Left" org-metaleft (org-at-table-p)]
12456 ["Move Column Right" org-metaright (org-at-table-p)]
12457 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
12458 ["Insert Column" org-shiftmetaright (org-at-table-p)])
12459 ("Row"
12460 ["Move Row Up" org-metaup (org-at-table-p)]
12461 ["Move Row Down" org-metadown (org-at-table-p)]
12462 ["Delete Row" org-shiftmetaup (org-at-table-p)]
12463 ["Insert Row" org-shiftmetadown (org-at-table-p)]
12464 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
12465 "--"
12466 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
12467 ("Rectangle"
12468 ["Copy Rectangle" org-copy-special (org-at-table-p)]
12469 ["Cut Rectangle" org-cut-special (org-at-table-p)]
12470 ["Paste Rectangle" org-paste-special (org-at-table-p)]
12471 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
12472 "--"
12473 ("Calculate"
12474 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
12475 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
12476 ["Edit Formulas" org-table-edit-formulas (org-at-table-p)]
12477 "--"
12478 ["Recalculate line" org-table-recalculate (org-at-table-p)]
12479 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
12480 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
12481 "--"
12482 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
12483 "--"
12484 ["Sum Column/Rectangle" org-table-sum
12485 (or (org-at-table-p) (org-region-active-p))]
12486 ["Which Column?" org-table-current-column (org-at-table-p)])
12487 ["Debug Formulas"
12488 org-table-toggle-formula-debugger
12489 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
12490 ["Show Col/Row Numbers"
12491 org-table-toggle-coordinate-overlays
12492 :style toggle
12493 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
12494 "--"
12495 ["Create" org-table-create (and (not (org-at-table-p))
12496 org-enable-table-editor)]
12497 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
12498 ["Import from File" org-table-import (not (org-at-table-p))]
12499 ["Export to File" org-table-export (org-at-table-p)]
12500 "--"
12501 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
12503 (easy-menu-define org-org-menu org-mode-map "Org menu"
12504 '("Org"
12505 ("Show/Hide"
12506 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
12507 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
12508 ["Sparse Tree..." org-sparse-tree t]
12509 ["Reveal Context" org-reveal t]
12510 ["Show All" show-all t]
12511 "--"
12512 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
12513 "--"
12514 ["New Heading" org-insert-heading t]
12515 ("Navigate Headings"
12516 ["Up" outline-up-heading t]
12517 ["Next" outline-next-visible-heading t]
12518 ["Previous" outline-previous-visible-heading t]
12519 ["Next Same Level" outline-forward-same-level t]
12520 ["Previous Same Level" outline-backward-same-level t]
12521 "--"
12522 ["Jump" org-goto t])
12523 ("Edit Structure"
12524 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
12525 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
12526 "--"
12527 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
12528 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
12529 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
12530 "--"
12531 ["Promote Heading" org-metaleft (not (org-at-table-p))]
12532 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
12533 ["Demote Heading" org-metaright (not (org-at-table-p))]
12534 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
12535 "--"
12536 ["Sort Region/Children" org-sort (not (org-at-table-p))]
12537 "--"
12538 ["Convert to odd levels" org-convert-to-odd-levels t]
12539 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
12540 ("Editing"
12541 ["Emphasis..." org-emphasize t])
12542 ("Archive"
12543 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
12544 ; ["Check and Tag Children" (org-toggle-archive-tag (4))
12545 ; :active t :keys "C-u C-c C-x C-a"]
12546 ["Sparse trees open ARCHIVE trees"
12547 (setq org-sparse-tree-open-archived-trees
12548 (not org-sparse-tree-open-archived-trees))
12549 :style toggle :selected org-sparse-tree-open-archived-trees]
12550 ["Cycling opens ARCHIVE trees"
12551 (setq org-cycle-open-archived-trees (not org-cycle-open-archived-trees))
12552 :style toggle :selected org-cycle-open-archived-trees]
12553 ["Agenda includes ARCHIVE trees"
12554 (setq org-agenda-skip-archived-trees (not org-agenda-skip-archived-trees))
12555 :style toggle :selected (not org-agenda-skip-archived-trees)]
12556 "--"
12557 ["Move Subtree to Archive" org-advertized-archive-subtree t]
12558 ; ["Check and Move Children" (org-archive-subtree '(4))
12559 ; :active t :keys "C-u C-c C-x C-s"]
12561 "--"
12562 ("TODO Lists"
12563 ["TODO/DONE/-" org-todo t]
12564 ("Select keyword"
12565 ["Next keyword" org-shiftright (org-on-heading-p)]
12566 ["Previous keyword" org-shiftleft (org-on-heading-p)]
12567 ["Complete Keyword" org-complete (assq :todo-keyword (org-context))]
12568 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))]
12569 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))])
12570 ["Show TODO Tree" org-show-todo-tree t]
12571 ["Global TODO list" org-todo-list t]
12572 "--"
12573 ["Set Priority" org-priority t]
12574 ["Priority Up" org-shiftup t]
12575 ["Priority Down" org-shiftdown t])
12576 ("TAGS and Properties"
12577 ["Set Tags" 'org-ctrl-c-ctrl-c (org-at-heading-p)]
12578 ["Change tag in region" 'org-change-tag-in-region (org-region-active-p)]
12579 "--"
12580 ["Set property" 'org-set-property t]
12581 ["Column view of properties" org-columns t]
12582 ["Insert Column View DBlock" org-insert-columns-dblock t])
12583 ("Dates and Scheduling"
12584 ["Timestamp" org-time-stamp t]
12585 ["Timestamp (inactive)" org-time-stamp-inactive t]
12586 ("Change Date"
12587 ["1 Day Later" org-shiftright t]
12588 ["1 Day Earlier" org-shiftleft t]
12589 ["1 ... Later" org-shiftup t]
12590 ["1 ... Earlier" org-shiftdown t])
12591 ["Compute Time Range" org-evaluate-time-range t]
12592 ["Schedule Item" org-schedule t]
12593 ["Deadline" org-deadline t]
12594 "--"
12595 ["Custom time format" org-toggle-time-stamp-overlays
12596 :style radio :selected org-display-custom-times]
12597 "--"
12598 ["Goto Calendar" org-goto-calendar t]
12599 ["Date from Calendar" org-date-from-calendar t])
12600 ("Logging work"
12601 ["Clock in" org-clock-in t]
12602 ["Clock out" org-clock-out t]
12603 ["Clock cancel" org-clock-cancel t]
12604 ["Goto running clock" org-clock-goto t]
12605 ["Display times" org-clock-display t]
12606 ["Create clock table" org-clock-report t]
12607 "--"
12608 ["Record DONE time"
12609 (progn (setq org-log-done (not org-log-done))
12610 (message "Switching to %s will %s record a timestamp"
12611 (car org-done-keywords)
12612 (if org-log-done "automatically" "not")))
12613 :style toggle :selected org-log-done])
12614 "--"
12615 ["Agenda Command..." org-agenda t]
12616 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
12617 ("File List for Agenda")
12618 ("Special views current file"
12619 ["TODO Tree" org-show-todo-tree t]
12620 ["Check Deadlines" org-check-deadlines t]
12621 ["Timeline" org-timeline t]
12622 ["Tags Tree" org-tags-sparse-tree t])
12623 "--"
12624 ("Hyperlinks"
12625 ["Store Link (Global)" org-store-link t]
12626 ["Insert Link" org-insert-link t]
12627 ["Follow Link" org-open-at-point t]
12628 "--"
12629 ["Next link" org-next-link t]
12630 ["Previous link" org-previous-link t]
12631 "--"
12632 ["Descriptive Links"
12633 (progn (org-add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
12634 :style radio
12635 :selected (member '(org-link) buffer-invisibility-spec)]
12636 ["Literal Links"
12637 (progn
12638 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
12639 :style radio
12640 :selected (not (member '(org-link) buffer-invisibility-spec))])
12641 "--"
12642 ["Export/Publish..." org-export t]
12643 ("LaTeX"
12644 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
12645 :selected org-cdlatex-mode]
12646 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
12647 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
12648 ["Modify math symbol" org-cdlatex-math-modify
12649 (org-inside-LaTeX-fragment-p)]
12650 ["Export LaTeX fragments as images"
12651 (if (featurep 'org-exp)
12652 (setq org-export-with-LaTeX-fragments
12653 (not org-export-with-LaTeX-fragments))
12654 (require 'org-exp))
12655 :style toggle :selected (and (boundp 'org-export-with-LaTeX-fragments)
12656 org-export-with-LaTeX-fragments)])
12657 "--"
12658 ("Documentation"
12659 ["Show Version" org-version t]
12660 ["Info Documentation" org-info t])
12661 ("Customize"
12662 ["Browse Org Group" org-customize t]
12663 "--"
12664 ["Expand This Menu" org-create-customize-menu
12665 (fboundp 'customize-menu-create)])
12666 "--"
12667 ["Refresh setup" org-mode-restart t]
12670 (defun org-info (&optional node)
12671 "Read documentation for Org-mode in the info system.
12672 With optional NODE, go directly to that node."
12673 (interactive)
12674 (info (format "(org)%s" (or node ""))))
12676 (defun org-install-agenda-files-menu ()
12677 (let ((bl (buffer-list)))
12678 (save-excursion
12679 (while bl
12680 (set-buffer (pop bl))
12681 (if (org-mode-p) (setq bl nil)))
12682 (when (org-mode-p)
12683 (easy-menu-change
12684 '("Org") "File List for Agenda"
12685 (append
12686 (list
12687 ["Edit File List" (org-edit-agenda-file-list) t]
12688 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
12689 ["Remove Current File from List" org-remove-file t]
12690 ["Cycle through agenda files" org-cycle-agenda-files t]
12691 ["Occur in all agenda files" org-occur-in-agenda-files t]
12692 "--")
12693 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
12695 ;;;; Documentation
12697 (defun org-require-autoloaded-modules ()
12698 (interactive)
12699 (mapc 'require
12700 '(org-agenda org-archive org-clock org-colview
12701 org-exp org-export-latex org-publish
12702 org-remember org-table)))
12704 (defun org-customize ()
12705 "Call the customize function with org as argument."
12706 (interactive)
12707 (org-load-modules-maybe)
12708 (org-require-autoloaded-modules)
12709 (customize-browse 'org))
12711 (defun org-create-customize-menu ()
12712 "Create a full customization menu for Org-mode, insert it into the menu."
12713 (interactive)
12714 (org-load-modules-maybe)
12715 (org-require-autoloaded-modules)
12716 (if (fboundp 'customize-menu-create)
12717 (progn
12718 (easy-menu-change
12719 '("Org") "Customize"
12720 `(["Browse Org group" org-customize t]
12721 "--"
12722 ,(customize-menu-create 'org)
12723 ["Set" Custom-set t]
12724 ["Save" Custom-save t]
12725 ["Reset to Current" Custom-reset-current t]
12726 ["Reset to Saved" Custom-reset-saved t]
12727 ["Reset to Standard Settings" Custom-reset-standard t]))
12728 (message "\"Org\"-menu now contains full customization menu"))
12729 (error "Cannot expand menu (outdated version of cus-edit.el)")))
12731 ;;;; Miscellaneous stuff
12733 ;;; Generally useful functions
12735 (defun org-plist-delete (plist property)
12736 "Delete PROPERTY from PLIST.
12737 This is in contrast to merely setting it to 0."
12738 (let (p)
12739 (while plist
12740 (if (not (eq property (car plist)))
12741 (setq p (plist-put p (car plist) (nth 1 plist))))
12742 (setq plist (cddr plist)))
12745 (defun org-force-self-insert (N)
12746 "Needed to enforce self-insert under remapping."
12747 (interactive "p")
12748 (self-insert-command N))
12750 (defun org-string-width (s)
12751 "Compute width of string, ignoring invisible characters.
12752 This ignores character with invisibility property `org-link', and also
12753 characters with property `org-cwidth', because these will become invisible
12754 upon the next fontification round."
12755 (let (b l)
12756 (when (or (eq t buffer-invisibility-spec)
12757 (assq 'org-link buffer-invisibility-spec))
12758 (while (setq b (text-property-any 0 (length s)
12759 'invisible 'org-link s))
12760 (setq s (concat (substring s 0 b)
12761 (substring s (or (next-single-property-change
12762 b 'invisible s) (length s)))))))
12763 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
12764 (setq s (concat (substring s 0 b)
12765 (substring s (or (next-single-property-change
12766 b 'org-cwidth s) (length s))))))
12767 (setq l (string-width s) b -1)
12768 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
12769 (setq l (- l (get-text-property b 'org-dwidth-n s))))
12772 (defun org-base-buffer (buffer)
12773 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
12774 (if (not buffer)
12775 buffer
12776 (or (buffer-base-buffer buffer)
12777 buffer)))
12779 (defun org-trim (s)
12780 "Remove whitespace at beginning and end of string."
12781 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
12782 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
12785 (defun org-wrap (string &optional width lines)
12786 "Wrap string to either a number of lines, or a width in characters.
12787 If WIDTH is non-nil, the string is wrapped to that width, however many lines
12788 that costs. If there is a word longer than WIDTH, the text is actually
12789 wrapped to the length of that word.
12790 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
12791 many lines, whatever width that takes.
12792 The return value is a list of lines, without newlines at the end."
12793 (let* ((words (org-split-string string "[ \t\n]+"))
12794 (maxword (apply 'max (mapcar 'org-string-width words)))
12795 w ll)
12796 (cond (width
12797 (org-do-wrap words (max maxword width)))
12798 (lines
12799 (setq w maxword)
12800 (setq ll (org-do-wrap words maxword))
12801 (if (<= (length ll) lines)
12803 (setq ll words)
12804 (while (> (length ll) lines)
12805 (setq w (1+ w))
12806 (setq ll (org-do-wrap words w)))
12807 ll))
12808 (t (error "Cannot wrap this")))))
12810 (defun org-do-wrap (words width)
12811 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
12812 (let (lines line)
12813 (while words
12814 (setq line (pop words))
12815 (while (and words (< (+ (length line) (length (car words))) width))
12816 (setq line (concat line " " (pop words))))
12817 (setq lines (push line lines)))
12818 (nreverse lines)))
12820 (defun org-split-string (string &optional separators)
12821 "Splits STRING into substrings at SEPARATORS.
12822 No empty strings are returned if there are matches at the beginning
12823 and end of string."
12824 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
12825 (start 0)
12826 notfirst
12827 (list nil))
12828 (while (and (string-match rexp string
12829 (if (and notfirst
12830 (= start (match-beginning 0))
12831 (< start (length string)))
12832 (1+ start) start))
12833 (< (match-beginning 0) (length string)))
12834 (setq notfirst t)
12835 (or (eq (match-beginning 0) 0)
12836 (and (eq (match-beginning 0) (match-end 0))
12837 (eq (match-beginning 0) start))
12838 (setq list
12839 (cons (substring string start (match-beginning 0))
12840 list)))
12841 (setq start (match-end 0)))
12842 (or (eq start (length string))
12843 (setq list
12844 (cons (substring string start)
12845 list)))
12846 (nreverse list)))
12848 (defun org-context ()
12849 "Return a list of contexts of the current cursor position.
12850 If several contexts apply, all are returned.
12851 Each context entry is a list with a symbol naming the context, and
12852 two positions indicating start and end of the context. Possible
12853 contexts are:
12855 :headline anywhere in a headline
12856 :headline-stars on the leading stars in a headline
12857 :todo-keyword on a TODO keyword (including DONE) in a headline
12858 :tags on the TAGS in a headline
12859 :priority on the priority cookie in a headline
12860 :item on the first line of a plain list item
12861 :item-bullet on the bullet/number of a plain list item
12862 :checkbox on the checkbox in a plain list item
12863 :table in an org-mode table
12864 :table-special on a special filed in a table
12865 :table-table in a table.el table
12866 :link on a hyperlink
12867 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
12868 :target on a <<target>>
12869 :radio-target on a <<<radio-target>>>
12870 :latex-fragment on a LaTeX fragment
12871 :latex-preview on a LaTeX fragment with overlayed preview image
12873 This function expects the position to be visible because it uses font-lock
12874 faces as a help to recognize the following contexts: :table-special, :link,
12875 and :keyword."
12876 (let* ((f (get-text-property (point) 'face))
12877 (faces (if (listp f) f (list f)))
12878 (p (point)) clist o)
12879 ;; First the large context
12880 (cond
12881 ((org-on-heading-p t)
12882 (push (list :headline (point-at-bol) (point-at-eol)) clist)
12883 (when (progn
12884 (beginning-of-line 1)
12885 (looking-at org-todo-line-tags-regexp))
12886 (push (org-point-in-group p 1 :headline-stars) clist)
12887 (push (org-point-in-group p 2 :todo-keyword) clist)
12888 (push (org-point-in-group p 4 :tags) clist))
12889 (goto-char p)
12890 (skip-chars-backward "^[\n\r \t") (or (eobp) (backward-char 1))
12891 (if (looking-at "\\[#[A-Z0-9]\\]")
12892 (push (org-point-in-group p 0 :priority) clist)))
12894 ((org-at-item-p)
12895 (push (org-point-in-group p 2 :item-bullet) clist)
12896 (push (list :item (point-at-bol)
12897 (save-excursion (org-end-of-item) (point)))
12898 clist)
12899 (and (org-at-item-checkbox-p)
12900 (push (org-point-in-group p 0 :checkbox) clist)))
12902 ((org-at-table-p)
12903 (push (list :table (org-table-begin) (org-table-end)) clist)
12904 (if (memq 'org-formula faces)
12905 (push (list :table-special
12906 (previous-single-property-change p 'face)
12907 (next-single-property-change p 'face)) clist)))
12908 ((org-at-table-p 'any)
12909 (push (list :table-table) clist)))
12910 (goto-char p)
12912 ;; Now the small context
12913 (cond
12914 ((org-at-timestamp-p)
12915 (push (org-point-in-group p 0 :timestamp) clist))
12916 ((memq 'org-link faces)
12917 (push (list :link
12918 (previous-single-property-change p 'face)
12919 (next-single-property-change p 'face)) clist))
12920 ((memq 'org-special-keyword faces)
12921 (push (list :keyword
12922 (previous-single-property-change p 'face)
12923 (next-single-property-change p 'face)) clist))
12924 ((org-on-target-p)
12925 (push (org-point-in-group p 0 :target) clist)
12926 (goto-char (1- (match-beginning 0)))
12927 (if (looking-at org-radio-target-regexp)
12928 (push (org-point-in-group p 0 :radio-target) clist))
12929 (goto-char p))
12930 ((setq o (car (delq nil
12931 (mapcar
12932 (lambda (x)
12933 (if (memq x org-latex-fragment-image-overlays) x))
12934 (org-overlays-at (point))))))
12935 (push (list :latex-fragment
12936 (org-overlay-start o) (org-overlay-end o)) clist)
12937 (push (list :latex-preview
12938 (org-overlay-start o) (org-overlay-end o)) clist))
12939 ((org-inside-LaTeX-fragment-p)
12940 ;; FIXME: positions wrong.
12941 (push (list :latex-fragment (point) (point)) clist)))
12943 (setq clist (nreverse (delq nil clist)))
12944 clist))
12946 ;; FIXME: Compare with at-regexp-p Do we need both?
12947 (defun org-in-regexp (re &optional nlines visually)
12948 "Check if point is inside a match of regexp.
12949 Normally only the current line is checked, but you can include NLINES extra
12950 lines both before and after point into the search.
12951 If VISUALLY is set, require that the cursor is not after the match but
12952 really on, so that the block visually is on the match."
12953 (catch 'exit
12954 (let ((pos (point))
12955 (eol (point-at-eol (+ 1 (or nlines 0))))
12956 (inc (if visually 1 0)))
12957 (save-excursion
12958 (beginning-of-line (- 1 (or nlines 0)))
12959 (while (re-search-forward re eol t)
12960 (if (and (<= (match-beginning 0) pos)
12961 (>= (+ inc (match-end 0)) pos))
12962 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
12964 (defun org-at-regexp-p (regexp)
12965 "Is point inside a match of REGEXP in the current line?"
12966 (catch 'exit
12967 (save-excursion
12968 (let ((pos (point)) (end (point-at-eol)))
12969 (beginning-of-line 1)
12970 (while (re-search-forward regexp end t)
12971 (if (and (<= (match-beginning 0) pos)
12972 (>= (match-end 0) pos))
12973 (throw 'exit t)))
12974 nil))))
12976 (defun org-occur-in-agenda-files (regexp &optional nlines)
12977 "Call `multi-occur' with buffers for all agenda files."
12978 (interactive "sOrg-files matching: \np")
12979 (let* ((files (org-agenda-files))
12980 (tnames (mapcar 'file-truename files))
12981 (extra org-agenda-text-search-extra-files)
12983 (when (eq (car extra) 'agenda-archives)
12984 (setq extra (cdr extra))
12985 (setq files (org-add-archive-files files)))
12986 (while (setq f (pop extra))
12987 (unless (member (file-truename f) tnames)
12988 (add-to-list 'files f 'append)
12989 (add-to-list 'tnames (file-truename f) 'append)))
12990 (multi-occur
12991 (mapcar (lambda (x) (or (get-file-buffer x) (find-file-noselect x))) files)
12992 regexp)))
12994 (if (boundp 'occur-mode-find-occurrence-hook)
12995 ;; Emacs 23
12996 (add-hook 'occur-mode-find-occurrence-hook
12997 (lambda ()
12998 (when (org-mode-p)
12999 (org-reveal))))
13000 ;; Emacs 22
13001 (defadvice occur-mode-goto-occurrence
13002 (after org-occur-reveal activate)
13003 (and (org-mode-p) (org-reveal)))
13004 (defadvice occur-mode-goto-occurrence-other-window
13005 (after org-occur-reveal activate)
13006 (and (org-mode-p) (org-reveal)))
13007 (defadvice occur-mode-display-occurrence
13008 (after org-occur-reveal activate)
13009 (when (org-mode-p)
13010 (let ((pos (occur-mode-find-occurrence)))
13011 (with-current-buffer (marker-buffer pos)
13012 (save-excursion
13013 (goto-char pos)
13014 (org-reveal)))))))
13016 (defun org-uniquify (list)
13017 "Remove duplicate elements from LIST."
13018 (let (res)
13019 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
13020 res))
13022 (defun org-delete-all (elts list)
13023 "Remove all elements in ELTS from LIST."
13024 (while elts
13025 (setq list (delete (pop elts) list)))
13026 list)
13028 (defun org-back-over-empty-lines ()
13029 "Move backwards over witespace, to the beginning of the first empty line.
13030 Returns the number of empty lines passed."
13031 (let ((pos (point)))
13032 (skip-chars-backward " \t\n\r")
13033 (beginning-of-line 2)
13034 (goto-char (min (point) pos))
13035 (count-lines (point) pos)))
13037 (defun org-skip-whitespace ()
13038 (skip-chars-forward " \t\n\r"))
13040 (defun org-point-in-group (point group &optional context)
13041 "Check if POINT is in match-group GROUP.
13042 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
13043 match. If the match group does ot exist or point is not inside it,
13044 return nil."
13045 (and (match-beginning group)
13046 (>= point (match-beginning group))
13047 (<= point (match-end group))
13048 (if context
13049 (list context (match-beginning group) (match-end group))
13050 t)))
13052 (defun org-switch-to-buffer-other-window (&rest args)
13053 "Switch to buffer in a second window on the current frame.
13054 In particular, do not allow pop-up frames."
13055 (let (pop-up-frames special-display-buffer-names special-display-regexps
13056 special-display-function)
13057 (apply 'switch-to-buffer-other-window args)))
13059 (defun org-combine-plists (&rest plists)
13060 "Create a single property list from all plists in PLISTS.
13061 The process starts by copying the first list, and then setting properties
13062 from the other lists. Settings in the last list are the most significant
13063 ones and overrule settings in the other lists."
13064 (let ((rtn (copy-sequence (pop plists)))
13065 p v ls)
13066 (while plists
13067 (setq ls (pop plists))
13068 (while ls
13069 (setq p (pop ls) v (pop ls))
13070 (setq rtn (plist-put rtn p v))))
13071 rtn))
13073 (defun org-move-line-down (arg)
13074 "Move the current line down. With prefix argument, move it past ARG lines."
13075 (interactive "p")
13076 (let ((col (current-column))
13077 beg end pos)
13078 (beginning-of-line 1) (setq beg (point))
13079 (beginning-of-line 2) (setq end (point))
13080 (beginning-of-line (+ 1 arg))
13081 (setq pos (move-marker (make-marker) (point)))
13082 (insert (delete-and-extract-region beg end))
13083 (goto-char pos)
13084 (org-move-to-column col)))
13086 (defun org-move-line-up (arg)
13087 "Move the current line up. With prefix argument, move it past ARG lines."
13088 (interactive "p")
13089 (let ((col (current-column))
13090 beg end pos)
13091 (beginning-of-line 1) (setq beg (point))
13092 (beginning-of-line 2) (setq end (point))
13093 (beginning-of-line (- arg))
13094 (setq pos (move-marker (make-marker) (point)))
13095 (insert (delete-and-extract-region beg end))
13096 (goto-char pos)
13097 (org-move-to-column col)))
13099 (defun org-replace-escapes (string table)
13100 "Replace %-escapes in STRING with values in TABLE.
13101 TABLE is an association list with keys like \"%a\" and string values.
13102 The sequences in STRING may contain normal field width and padding information,
13103 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
13104 so values can contain further %-escapes if they are define later in TABLE."
13105 (let ((case-fold-search nil)
13106 e re rpl)
13107 (while (setq e (pop table))
13108 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
13109 (while (string-match re string)
13110 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
13111 (cdr e)))
13112 (setq string (replace-match rpl t t string))))
13113 string))
13116 (defun org-sublist (list start end)
13117 "Return a section of LIST, from START to END.
13118 Counting starts at 1."
13119 (let (rtn (c start))
13120 (setq list (nthcdr (1- start) list))
13121 (while (and list (<= c end))
13122 (push (pop list) rtn)
13123 (setq c (1+ c)))
13124 (nreverse rtn)))
13126 (defun org-find-base-buffer-visiting (file)
13127 "Like `find-buffer-visiting' but alway return the base buffer and
13128 not an indirect buffer."
13129 (let ((buf (find-buffer-visiting file)))
13130 (if buf
13131 (or (buffer-base-buffer buf) buf)
13132 nil)))
13134 (defun org-image-file-name-regexp ()
13135 "Return regexp matching the file names of images."
13136 (if (fboundp 'image-file-name-regexp)
13137 (image-file-name-regexp)
13138 (let ((image-file-name-extensions
13139 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
13140 "xbm" "xpm" "pbm" "pgm" "ppm")))
13141 (concat "\\."
13142 (regexp-opt (nconc (mapcar 'upcase
13143 image-file-name-extensions)
13144 image-file-name-extensions)
13146 "\\'"))))
13148 (defun org-file-image-p (file)
13149 "Return non-nil if FILE is an image."
13150 (save-match-data
13151 (string-match (org-image-file-name-regexp) file)))
13153 ;;; Paragraph filling stuff.
13154 ;; We want this to be just right, so use the full arsenal.
13156 (defun org-indent-line-function ()
13157 "Indent line like previous, but further if previous was headline or item."
13158 (interactive)
13159 (let* ((pos (point))
13160 (itemp (org-at-item-p))
13161 column bpos bcol tpos tcol bullet btype bullet-type)
13162 ;; Find the previous relevant line
13163 (beginning-of-line 1)
13164 (cond
13165 ((looking-at "#") (setq column 0))
13166 ((looking-at "\\*+ ") (setq column 0))
13168 (beginning-of-line 0)
13169 (while (and (not (bobp)) (looking-at "[ \t]*[\n:#|]"))
13170 (beginning-of-line 0))
13171 (cond
13172 ((looking-at "\\*+[ \t]+")
13173 (goto-char (match-end 0))
13174 (setq column (current-column)))
13175 ((org-in-item-p)
13176 (org-beginning-of-item)
13177 ; (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
13178 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*\\(\\[[- X]\\][ \t]*\\)?")
13179 (setq bpos (match-beginning 1) tpos (match-end 0)
13180 bcol (progn (goto-char bpos) (current-column))
13181 tcol (progn (goto-char tpos) (current-column))
13182 bullet (match-string 1)
13183 bullet-type (if (string-match "[0-9]" bullet) "n" bullet))
13184 (if (not itemp)
13185 (setq column tcol)
13186 (goto-char pos)
13187 (beginning-of-line 1)
13188 (if (looking-at "\\S-")
13189 (progn
13190 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
13191 (setq bullet (match-string 1)
13192 btype (if (string-match "[0-9]" bullet) "n" bullet))
13193 (setq column (if (equal btype bullet-type) bcol tcol)))
13194 (setq column (org-get-indentation)))))
13195 (t (setq column (org-get-indentation))))))
13196 (goto-char pos)
13197 (if (<= (current-column) (current-indentation))
13198 (org-indent-line-to column)
13199 (save-excursion (org-indent-line-to column)))
13200 (setq column (current-column))
13201 (beginning-of-line 1)
13202 (if (looking-at
13203 "\\([ \t]+\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
13204 (replace-match (concat "\\1" (format org-property-format
13205 (match-string 2) (match-string 3)))
13206 t nil))
13207 (org-move-to-column column)))
13209 (defun org-set-autofill-regexps ()
13210 (interactive)
13211 ;; In the paragraph separator we include headlines, because filling
13212 ;; text in a line directly attached to a headline would otherwise
13213 ;; fill the headline as well.
13214 (org-set-local 'comment-start-skip "^#+[ \t]*")
13215 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|]")
13216 ;; The paragraph starter includes hand-formatted lists.
13217 (org-set-local 'paragraph-start
13218 "\f\\|[ ]*$\\|\\*+ \\|\f\\|[ \t]*\\([-+*][ \t]+\\|[0-9]+[.)][ \t]+\\)\\|[ \t]*[:|]")
13219 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
13220 ;; But only if the user has not turned off tables or fixed-width regions
13221 (org-set-local
13222 'auto-fill-inhibit-regexp
13223 (concat "\\*+ \\|#\\+"
13224 "\\|[ \t]*" org-keyword-time-regexp
13225 (if (or org-enable-table-editor org-enable-fixed-width-editor)
13226 (concat
13227 "\\|[ \t]*["
13228 (if org-enable-table-editor "|" "")
13229 (if org-enable-fixed-width-editor ":" "")
13230 "]"))))
13231 ;; We use our own fill-paragraph function, to make sure that tables
13232 ;; and fixed-width regions are not wrapped. That function will pass
13233 ;; through to `fill-paragraph' when appropriate.
13234 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
13235 ; Adaptive filling: To get full control, first make sure that
13236 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
13237 (org-set-local 'adaptive-fill-regexp "\000")
13238 (org-set-local 'adaptive-fill-function
13239 'org-adaptive-fill-function)
13240 (org-set-local
13241 'align-mode-rules-list
13242 '((org-in-buffer-settings
13243 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
13244 (modes . '(org-mode))))))
13246 (defun org-fill-paragraph (&optional justify)
13247 "Re-align a table, pass through to fill-paragraph if no table."
13248 (let ((table-p (org-at-table-p))
13249 (table.el-p (org-at-table.el-p)))
13250 (cond ((and (equal (char-after (point-at-bol)) ?*)
13251 (save-excursion (goto-char (point-at-bol))
13252 (looking-at outline-regexp)))
13253 t) ; skip headlines
13254 (table.el-p t) ; skip table.el tables
13255 (table-p (org-table-align) t) ; align org-mode tables
13256 (t nil)))) ; call paragraph-fill
13258 ;; For reference, this is the default value of adaptive-fill-regexp
13259 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
13261 (defun org-adaptive-fill-function ()
13262 "Return a fill prefix for org-mode files.
13263 In particular, this makes sure hanging paragraphs for hand-formatted lists
13264 work correctly."
13265 (cond ((looking-at "#[ \t]+")
13266 (match-string 0))
13267 ((looking-at "[ \t]*\\([-*+] \\|[0-9]+[.)] \\)?")
13268 (save-excursion
13269 (goto-char (match-end 0))
13270 (make-string (current-column) ?\ )))
13271 (t nil)))
13273 ;;; Other stuff.
13275 (defun org-toggle-fixed-width-section (arg)
13276 "Toggle the fixed-width export.
13277 If there is no active region, the QUOTE keyword at the current headline is
13278 inserted or removed. When present, it causes the text between this headline
13279 and the next to be exported as fixed-width text, and unmodified.
13280 If there is an active region, this command adds or removes a colon as the
13281 first character of this line. If the first character of a line is a colon,
13282 this line is also exported in fixed-width font."
13283 (interactive "P")
13284 (let* ((cc 0)
13285 (regionp (org-region-active-p))
13286 (beg (if regionp (region-beginning) (point)))
13287 (end (if regionp (region-end)))
13288 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
13289 (case-fold-search nil)
13290 (re "[ \t]*\\(:\\)")
13291 off)
13292 (if regionp
13293 (save-excursion
13294 (goto-char beg)
13295 (setq cc (current-column))
13296 (beginning-of-line 1)
13297 (setq off (looking-at re))
13298 (while (> nlines 0)
13299 (setq nlines (1- nlines))
13300 (beginning-of-line 1)
13301 (cond
13302 (arg
13303 (org-move-to-column cc t)
13304 (insert ":\n")
13305 (forward-line -1))
13306 ((and off (looking-at re))
13307 (replace-match "" t t nil 1))
13308 ((not off) (org-move-to-column cc t) (insert ":")))
13309 (forward-line 1)))
13310 (save-excursion
13311 (org-back-to-heading)
13312 (if (looking-at (concat outline-regexp
13313 "\\( *\\<" org-quote-string "\\>[ \t]*\\)"))
13314 (replace-match "" t t nil 1)
13315 (if (looking-at outline-regexp)
13316 (progn
13317 (goto-char (match-end 0))
13318 (insert org-quote-string " "))))))))
13320 ;;;; Functions extending outline functionality
13322 (defun org-beginning-of-line (&optional arg)
13323 "Go to the beginning of the current line. If that is invisible, continue
13324 to a visible line beginning. This makes the function of C-a more intuitive.
13325 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
13326 first attempt, and only move to after the tags when the cursor is already
13327 beyond the end of the headline."
13328 (interactive "P")
13329 (let ((pos (point)))
13330 (beginning-of-line 1)
13331 (if (bobp)
13333 (backward-char 1)
13334 (if (org-invisible-p)
13335 (while (and (not (bobp)) (org-invisible-p))
13336 (backward-char 1)
13337 (beginning-of-line 1))
13338 (forward-char 1)))
13339 (when org-special-ctrl-a/e
13340 (cond
13341 ((and (looking-at org-todo-line-regexp)
13342 (= (char-after (match-end 1)) ?\ ))
13343 (goto-char
13344 (if (eq org-special-ctrl-a/e t)
13345 (cond ((> pos (match-beginning 3)) (match-beginning 3))
13346 ((= pos (point)) (match-beginning 3))
13347 (t (point)))
13348 (cond ((> pos (point)) (point))
13349 ((not (eq last-command this-command)) (point))
13350 (t (match-beginning 3))))))
13351 ((org-at-item-p)
13352 (goto-char
13353 (if (eq org-special-ctrl-a/e t)
13354 (cond ((> pos (match-end 4)) (match-end 4))
13355 ((= pos (point)) (match-end 4))
13356 (t (point)))
13357 (cond ((> pos (point)) (point))
13358 ((not (eq last-command this-command)) (point))
13359 (t (match-end 4))))))))))
13361 (defun org-end-of-line (&optional arg)
13362 "Go to the end of the line.
13363 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
13364 first attempt, and only move to after the tags when the cursor is already
13365 beyond the end of the headline."
13366 (interactive "P")
13367 (if (or (not org-special-ctrl-a/e)
13368 (not (org-on-heading-p)))
13369 (end-of-line arg)
13370 (let ((pos (point)))
13371 (beginning-of-line 1)
13372 (if (looking-at (org-re ".*?\\([ \t]*\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
13373 (if (eq org-special-ctrl-a/e t)
13374 (if (or (< pos (match-beginning 1))
13375 (= pos (match-end 0)))
13376 (goto-char (match-beginning 1))
13377 (goto-char (match-end 0)))
13378 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
13379 (goto-char (match-end 0))
13380 (goto-char (match-beginning 1))))
13381 (end-of-line arg)))))
13383 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
13384 (define-key org-mode-map "\C-e" 'org-end-of-line)
13386 (defun org-kill-line (&optional arg)
13387 "Kill line, to tags or end of line."
13388 (interactive "P")
13389 (cond
13390 ((or (not org-special-ctrl-k)
13391 (bolp)
13392 (not (org-on-heading-p)))
13393 (call-interactively 'kill-line))
13394 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$"))
13395 (kill-region (point) (match-beginning 1))
13396 (org-set-tags nil t))
13397 (t (kill-region (point) (point-at-eol)))))
13399 (define-key org-mode-map "\C-k" 'org-kill-line)
13401 (defun org-invisible-p ()
13402 "Check if point is at a character currently not visible."
13403 ;; Early versions of noutline don't have `outline-invisible-p'.
13404 (if (fboundp 'outline-invisible-p)
13405 (outline-invisible-p)
13406 (get-char-property (point) 'invisible)))
13408 (defun org-invisible-p2 ()
13409 "Check if point is at a character currently not visible."
13410 (save-excursion
13411 (if (and (eolp) (not (bobp))) (backward-char 1))
13412 ;; Early versions of noutline don't have `outline-invisible-p'.
13413 (if (fboundp 'outline-invisible-p)
13414 (outline-invisible-p)
13415 (get-char-property (point) 'invisible))))
13417 (defalias 'org-back-to-heading 'outline-back-to-heading)
13418 (defalias 'org-on-heading-p 'outline-on-heading-p)
13419 (defalias 'org-at-heading-p 'outline-on-heading-p)
13420 (defun org-at-heading-or-item-p ()
13421 (or (org-on-heading-p) (org-at-item-p)))
13423 (defun org-on-target-p ()
13424 (or (org-in-regexp org-radio-target-regexp)
13425 (org-in-regexp org-target-regexp)))
13427 (defun org-up-heading-all (arg)
13428 "Move to the heading line of which the present line is a subheading.
13429 This function considers both visible and invisible heading lines.
13430 With argument, move up ARG levels."
13431 (if (fboundp 'outline-up-heading-all)
13432 (outline-up-heading-all arg) ; emacs 21 version of outline.el
13433 (outline-up-heading arg t))) ; emacs 22 version of outline.el
13435 (defun org-up-heading-safe ()
13436 "Move to the heading line of which the present line is a subheading.
13437 This version will not throw an error. It will return the level of the
13438 headline found, or nil if no higher level is found."
13439 (let ((pos (point)) start-level level
13440 (re (concat "^" outline-regexp)))
13441 (catch 'exit
13442 (outline-back-to-heading t)
13443 (setq start-level (funcall outline-level))
13444 (if (equal start-level 1) (throw 'exit nil))
13445 (while (re-search-backward re nil t)
13446 (setq level (funcall outline-level))
13447 (if (< level start-level) (throw 'exit level)))
13448 nil)))
13450 (defun org-first-sibling-p ()
13451 "Is this heading the first child of its parents?"
13452 (interactive)
13453 (let ((re (concat "^" outline-regexp))
13454 level l)
13455 (unless (org-at-heading-p t)
13456 (error "Not at a heading"))
13457 (setq level (funcall outline-level))
13458 (save-excursion
13459 (if (not (re-search-backward re nil t))
13461 (setq l (funcall outline-level))
13462 (< l level)))))
13464 (defun org-goto-sibling (&optional previous)
13465 "Goto the next sibling, even if it is invisible.
13466 When PREVIOUS is set, go to the previous sibling instead. Returns t
13467 when a sibling was found. When none is found, return nil and don't
13468 move point."
13469 (let ((fun (if previous 're-search-backward 're-search-forward))
13470 (pos (point))
13471 (re (concat "^" outline-regexp))
13472 level l)
13473 (when (condition-case nil (org-back-to-heading t) (error nil))
13474 (setq level (funcall outline-level))
13475 (catch 'exit
13476 (or previous (forward-char 1))
13477 (while (funcall fun re nil t)
13478 (setq l (funcall outline-level))
13479 (when (< l level) (goto-char pos) (throw 'exit nil))
13480 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
13481 (goto-char pos)
13482 nil))))
13484 (defun org-show-siblings ()
13485 "Show all siblings of the current headline."
13486 (save-excursion
13487 (while (org-goto-sibling) (org-flag-heading nil)))
13488 (save-excursion
13489 (while (org-goto-sibling 'previous)
13490 (org-flag-heading nil))))
13492 (defun org-show-hidden-entry ()
13493 "Show an entry where even the heading is hidden."
13494 (save-excursion
13495 (org-show-entry)))
13497 (defun org-flag-heading (flag &optional entry)
13498 "Flag the current heading. FLAG non-nil means make invisible.
13499 When ENTRY is non-nil, show the entire entry."
13500 (save-excursion
13501 (org-back-to-heading t)
13502 ;; Check if we should show the entire entry
13503 (if entry
13504 (progn
13505 (org-show-entry)
13506 (save-excursion
13507 (and (outline-next-heading)
13508 (org-flag-heading nil))))
13509 (outline-flag-region (max (point-min) (1- (point)))
13510 (save-excursion (outline-end-of-heading) (point))
13511 flag))))
13513 (defun org-end-of-subtree (&optional invisible-OK to-heading)
13514 ;; This is an exact copy of the original function, but it uses
13515 ;; `org-back-to-heading', to make it work also in invisible
13516 ;; trees. And is uses an invisible-OK argument.
13517 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
13518 (org-back-to-heading invisible-OK)
13519 (let ((first t)
13520 (level (funcall outline-level)))
13521 (while (and (not (eobp))
13522 (or first (> (funcall outline-level) level)))
13523 (setq first nil)
13524 (outline-next-heading))
13525 (unless to-heading
13526 (if (memq (preceding-char) '(?\n ?\^M))
13527 (progn
13528 ;; Go to end of line before heading
13529 (forward-char -1)
13530 (if (memq (preceding-char) '(?\n ?\^M))
13531 ;; leave blank line before heading
13532 (forward-char -1))))))
13533 (point))
13535 (defun org-show-subtree ()
13536 "Show everything after this heading at deeper levels."
13537 (outline-flag-region
13538 (point)
13539 (save-excursion
13540 (outline-end-of-subtree) (outline-next-heading) (point))
13541 nil))
13543 (defun org-show-entry ()
13544 "Show the body directly following this heading.
13545 Show the heading too, if it is currently invisible."
13546 (interactive)
13547 (save-excursion
13548 (condition-case nil
13549 (progn
13550 (org-back-to-heading t)
13551 (outline-flag-region
13552 (max (point-min) (1- (point)))
13553 (save-excursion
13554 (re-search-forward
13555 (concat "[\r\n]\\(" outline-regexp "\\)") nil 'move)
13556 (or (match-beginning 1) (point-max)))
13557 nil))
13558 (error nil))))
13560 (defun org-make-options-regexp (kwds)
13561 "Make a regular expression for keyword lines."
13562 (concat
13564 "#?[ \t]*\\+\\("
13565 (mapconcat 'regexp-quote kwds "\\|")
13566 "\\):[ \t]*"
13567 "\\(.+\\)"))
13569 ;; Make isearch reveal the necessary context
13570 (defun org-isearch-end ()
13571 "Reveal context after isearch exits."
13572 (when isearch-success ; only if search was successful
13573 (if (featurep 'xemacs)
13574 ;; Under XEmacs, the hook is run in the correct place,
13575 ;; we directly show the context.
13576 (org-show-context 'isearch)
13577 ;; In Emacs the hook runs *before* restoring the overlays.
13578 ;; So we have to use a one-time post-command-hook to do this.
13579 ;; (Emacs 22 has a special variable, see function `org-mode')
13580 (unless (and (boundp 'isearch-mode-end-hook-quit)
13581 isearch-mode-end-hook-quit)
13582 ;; Only when the isearch was not quitted.
13583 (org-add-hook 'post-command-hook 'org-isearch-post-command
13584 'append 'local)))))
13586 (defun org-isearch-post-command ()
13587 "Remove self from hook, and show context."
13588 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
13589 (org-show-context 'isearch))
13592 ;;;; Integration with and fixes for other packages
13594 ;;; Imenu support
13596 (defvar org-imenu-markers nil
13597 "All markers currently used by Imenu.")
13598 (make-variable-buffer-local 'org-imenu-markers)
13600 (defun org-imenu-new-marker (&optional pos)
13601 "Return a new marker for use by Imenu, and remember the marker."
13602 (let ((m (make-marker)))
13603 (move-marker m (or pos (point)))
13604 (push m org-imenu-markers)
13607 (defun org-imenu-get-tree ()
13608 "Produce the index for Imenu."
13609 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
13610 (setq org-imenu-markers nil)
13611 (let* ((n org-imenu-depth)
13612 (re (concat "^" outline-regexp))
13613 (subs (make-vector (1+ n) nil))
13614 (last-level 0)
13615 m tree level head)
13616 (save-excursion
13617 (save-restriction
13618 (widen)
13619 (goto-char (point-max))
13620 (while (re-search-backward re nil t)
13621 (setq level (org-reduced-level (funcall outline-level)))
13622 (when (<= level n)
13623 (looking-at org-complex-heading-regexp)
13624 (setq head (org-match-string-no-properties 4)
13625 m (org-imenu-new-marker))
13626 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
13627 (if (>= level last-level)
13628 (push (cons head m) (aref subs level))
13629 (push (cons head (aref subs (1+ level))) (aref subs level))
13630 (loop for i from (1+ level) to n do (aset subs i nil)))
13631 (setq last-level level)))))
13632 (aref subs 1)))
13634 (eval-after-load "imenu"
13635 '(progn
13636 (add-hook 'imenu-after-jump-hook
13637 (lambda () (org-show-context 'org-goto)))))
13639 ;; Speedbar support
13641 (defvar org-speedbar-restriction-lock-overlay (org-make-overlay 1 1)
13642 "Overlay marking the agenda restriction line in speedbar.")
13643 (org-overlay-put org-speedbar-restriction-lock-overlay
13644 'face 'org-agenda-restriction-lock)
13645 (org-overlay-put org-speedbar-restriction-lock-overlay
13646 'help-echo "Agendas are currently limited to this item.")
13647 (org-detach-overlay org-speedbar-restriction-lock-overlay)
13649 (defun org-speedbar-set-agenda-restriction ()
13650 "Restrict future agenda commands to the location at point in speedbar.
13651 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
13652 (interactive)
13653 (require 'org-agenda)
13654 (let (p m tp np dir txt w)
13655 (cond
13656 ((setq p (text-property-any (point-at-bol) (point-at-eol)
13657 'org-imenu t))
13658 (setq m (get-text-property p 'org-imenu-marker))
13659 (save-excursion
13660 (save-restriction
13661 (set-buffer (marker-buffer m))
13662 (goto-char m)
13663 (org-agenda-set-restriction-lock 'subtree))))
13664 ((setq p (text-property-any (point-at-bol) (point-at-eol)
13665 'speedbar-function 'speedbar-find-file))
13666 (setq tp (previous-single-property-change
13667 (1+ p) 'speedbar-function)
13668 np (next-single-property-change
13669 tp 'speedbar-function)
13670 dir (speedbar-line-directory)
13671 txt (buffer-substring-no-properties (or tp (point-min))
13672 (or np (point-max))))
13673 (save-excursion
13674 (save-restriction
13675 (set-buffer (find-file-noselect
13676 (let ((default-directory dir))
13677 (expand-file-name txt))))
13678 (unless (org-mode-p)
13679 (error "Cannot restrict to non-Org-mode file"))
13680 (org-agenda-set-restriction-lock 'file))))
13681 (t (error "Don't know how to restrict Org-mode's agenda")))
13682 (org-move-overlay org-speedbar-restriction-lock-overlay
13683 (point-at-bol) (point-at-eol))
13684 (setq current-prefix-arg nil)
13685 (org-agenda-maybe-redo)))
13687 (eval-after-load "speedbar"
13688 '(progn
13689 (speedbar-add-supported-extension ".org")
13690 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
13691 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
13692 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
13693 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
13694 (add-hook 'speedbar-visiting-tag-hook
13695 (lambda () (org-show-context 'org-goto)))))
13698 ;;; Fixes and Hacks for problems with other packages
13700 ;; Make flyspell not check words in links, to not mess up our keymap
13701 (defun org-mode-flyspell-verify ()
13702 "Don't let flyspell put overlays at active buttons."
13703 (not (get-text-property (point) 'keymap)))
13705 ;; Make `bookmark-jump' show the jump location if it was hidden.
13706 (eval-after-load "bookmark"
13707 '(if (boundp 'bookmark-after-jump-hook)
13708 ;; We can use the hook
13709 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
13710 ;; Hook not available, use advice
13711 (defadvice bookmark-jump (after org-make-visible activate)
13712 "Make the position visible."
13713 (org-bookmark-jump-unhide))))
13715 (defun org-bookmark-jump-unhide ()
13716 "Unhide the current position, to show the bookmark location."
13717 (and (org-mode-p)
13718 (or (org-invisible-p)
13719 (save-excursion (goto-char (max (point-min) (1- (point))))
13720 (org-invisible-p)))
13721 (org-show-context 'bookmark-jump)))
13723 ;; Make session.el ignore our circular variable
13724 (eval-after-load "session"
13725 '(add-to-list 'session-globals-exclude 'org-mark-ring))
13727 ;;;; Experimental code
13729 (defun org-closed-in-range ()
13730 "Sparse tree of items closed in a certain time range.
13731 Still experimental, may disappear in the future."
13732 (interactive)
13733 ;; Get the time interval from the user.
13734 (let* ((time1 (time-to-seconds
13735 (org-read-date nil 'to-time nil "Starting date: ")))
13736 (time2 (time-to-seconds
13737 (org-read-date nil 'to-time nil "End date:")))
13738 ;; callback function
13739 (callback (lambda ()
13740 (let ((time
13741 (time-to-seconds
13742 (apply 'encode-time
13743 (org-parse-time-string
13744 (match-string 1))))))
13745 ;; check if time in interval
13746 (and (>= time time1) (<= time time2))))))
13747 ;; make tree, check each match with the callback
13748 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
13751 ;;;; Finish up
13753 (provide 'org)
13755 (run-hooks 'org-load-hook)
13757 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
13759 ;;; org.el ends here